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 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 296 297 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 301 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 302 if (Subtarget.hasVSX()) 303 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 304 305 if (Subtarget.hasFSQRT()) { 306 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 307 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 308 } 309 310 if (Subtarget.hasFPRND()) { 311 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 312 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 313 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 314 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 315 316 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 317 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 319 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 320 } 321 322 // We don't support sin/cos/sqrt/fmod/pow 323 setOperationAction(ISD::FSIN , MVT::f64, Expand); 324 setOperationAction(ISD::FCOS , MVT::f64, Expand); 325 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 326 setOperationAction(ISD::FREM , MVT::f64, Expand); 327 setOperationAction(ISD::FPOW , MVT::f64, Expand); 328 setOperationAction(ISD::FSIN , MVT::f32, Expand); 329 setOperationAction(ISD::FCOS , MVT::f32, Expand); 330 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 331 setOperationAction(ISD::FREM , MVT::f32, Expand); 332 setOperationAction(ISD::FPOW , MVT::f32, Expand); 333 if (Subtarget.hasSPE()) { 334 setOperationAction(ISD::FMA , MVT::f64, Expand); 335 setOperationAction(ISD::FMA , MVT::f32, Expand); 336 } else { 337 setOperationAction(ISD::FMA , MVT::f64, Legal); 338 setOperationAction(ISD::FMA , MVT::f32, Legal); 339 } 340 341 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 342 343 // If we're enabling GP optimizations, use hardware square root 344 if (!Subtarget.hasFSQRT() && 345 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 346 Subtarget.hasFRE())) 347 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 348 349 if (!Subtarget.hasFSQRT() && 350 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 351 Subtarget.hasFRES())) 352 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 353 354 if (Subtarget.hasFCPSGN()) { 355 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 357 } else { 358 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 359 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 360 } 361 362 if (Subtarget.hasFPRND()) { 363 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 364 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 365 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 366 setOperationAction(ISD::FROUND, MVT::f64, Legal); 367 368 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 369 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 370 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 371 setOperationAction(ISD::FROUND, MVT::f32, Legal); 372 } 373 374 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 375 // to speed up scalar BSWAP64. 376 // CTPOP or CTTZ were introduced in P8/P9 respectively 377 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 378 if (Subtarget.hasP9Vector()) 379 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 380 else 381 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 382 if (Subtarget.isISA3_0()) { 383 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 384 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 385 } else { 386 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 387 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 388 } 389 390 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 391 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 392 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 393 } else { 394 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 395 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 396 } 397 398 // PowerPC does not have ROTR 399 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 400 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 401 402 if (!Subtarget.useCRBits()) { 403 // PowerPC does not have Select 404 setOperationAction(ISD::SELECT, MVT::i32, Expand); 405 setOperationAction(ISD::SELECT, MVT::i64, Expand); 406 setOperationAction(ISD::SELECT, MVT::f32, Expand); 407 setOperationAction(ISD::SELECT, MVT::f64, Expand); 408 } 409 410 // PowerPC wants to turn select_cc of FP into fsel when possible. 411 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 412 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 413 414 // PowerPC wants to optimize integer setcc a bit 415 if (!Subtarget.useCRBits()) 416 setOperationAction(ISD::SETCC, MVT::i32, Custom); 417 418 // PowerPC does not have BRCOND which requires SetCC 419 if (!Subtarget.useCRBits()) 420 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 421 422 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 423 424 if (Subtarget.hasSPE()) { 425 // SPE has built-in conversions 426 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 427 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 428 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 429 } else { 430 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 431 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 432 433 // PowerPC does not have [U|S]INT_TO_FP 434 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 435 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 436 } 437 438 if (Subtarget.hasDirectMove() && isPPC64) { 439 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 440 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 441 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 442 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 443 if (TM.Options.UnsafeFPMath) { 444 setOperationAction(ISD::LRINT, MVT::f64, Legal); 445 setOperationAction(ISD::LRINT, MVT::f32, Legal); 446 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 447 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 448 setOperationAction(ISD::LROUND, MVT::f64, Legal); 449 setOperationAction(ISD::LROUND, MVT::f32, Legal); 450 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 451 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 452 } 453 } else { 454 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 455 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 456 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 457 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 458 } 459 460 // We cannot sextinreg(i1). Expand to shifts. 461 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 462 463 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 464 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 465 // support continuation, user-level threading, and etc.. As a result, no 466 // other SjLj exception interfaces are implemented and please don't build 467 // your own exception handling based on them. 468 // LLVM/Clang supports zero-cost DWARF exception handling. 469 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 470 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 471 472 // We want to legalize GlobalAddress and ConstantPool nodes into the 473 // appropriate instructions to materialize the address. 474 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 475 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 476 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 477 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 478 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 479 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 480 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 481 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 482 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 483 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 484 485 // TRAP is legal. 486 setOperationAction(ISD::TRAP, MVT::Other, Legal); 487 488 // TRAMPOLINE is custom lowered. 489 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 490 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 491 492 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 493 setOperationAction(ISD::VASTART , MVT::Other, Custom); 494 495 if (Subtarget.is64BitELFABI()) { 496 // VAARG always uses double-word chunks, so promote anything smaller. 497 setOperationAction(ISD::VAARG, MVT::i1, Promote); 498 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 499 setOperationAction(ISD::VAARG, MVT::i8, Promote); 500 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 501 setOperationAction(ISD::VAARG, MVT::i16, Promote); 502 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 503 setOperationAction(ISD::VAARG, MVT::i32, Promote); 504 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 505 setOperationAction(ISD::VAARG, MVT::Other, Expand); 506 } else if (Subtarget.is32BitELFABI()) { 507 // VAARG is custom lowered with the 32-bit SVR4 ABI. 508 setOperationAction(ISD::VAARG, MVT::Other, Custom); 509 setOperationAction(ISD::VAARG, MVT::i64, Custom); 510 } else 511 setOperationAction(ISD::VAARG, MVT::Other, Expand); 512 513 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 514 if (Subtarget.is32BitELFABI()) 515 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 516 else 517 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 518 519 // Use the default implementation. 520 setOperationAction(ISD::VAEND , MVT::Other, Expand); 521 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 522 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 523 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 524 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 525 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 526 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 527 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 528 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 529 530 // We want to custom lower some of our intrinsics. 531 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 532 533 // To handle counter-based loop conditions. 534 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 535 536 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 537 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 538 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 539 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 540 541 // Comparisons that require checking two conditions. 542 if (Subtarget.hasSPE()) { 543 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 544 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 545 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 546 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 547 } 548 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 549 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 550 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 551 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 552 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 553 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 554 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 555 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 556 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 557 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 558 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 559 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 560 561 if (Subtarget.has64BitSupport()) { 562 // They also have instructions for converting between i64 and fp. 563 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 565 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 566 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 567 // This is just the low 32 bits of a (signed) fp->i64 conversion. 568 // We cannot do this with Promote because i64 is not a legal type. 569 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 570 571 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 572 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 573 } else { 574 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 575 if (Subtarget.hasSPE()) 576 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 577 else 578 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 579 } 580 581 // With the instructions enabled under FPCVT, we can do everything. 582 if (Subtarget.hasFPCVT()) { 583 if (Subtarget.has64BitSupport()) { 584 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 585 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 586 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 587 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 588 } 589 590 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 591 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 592 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 593 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 594 } 595 596 if (Subtarget.use64BitRegs()) { 597 // 64-bit PowerPC implementations can support i64 types directly 598 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 599 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 600 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 601 // 64-bit PowerPC wants to expand i128 shifts itself. 602 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 603 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 604 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 605 } else { 606 // 32-bit PowerPC wants to expand i64 shifts itself. 607 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 608 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 609 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 610 } 611 612 if (Subtarget.hasVSX()) { 613 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 614 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 615 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 616 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 617 } 618 619 if (Subtarget.hasAltivec()) { 620 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 621 setOperationAction(ISD::SADDSAT, VT, Legal); 622 setOperationAction(ISD::SSUBSAT, VT, Legal); 623 setOperationAction(ISD::UADDSAT, VT, Legal); 624 setOperationAction(ISD::USUBSAT, VT, Legal); 625 } 626 // First set operation action for all vector types to expand. Then we 627 // will selectively turn on ones that can be effectively codegen'd. 628 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 629 // add/sub are legal for all supported vector VT's. 630 setOperationAction(ISD::ADD, VT, Legal); 631 setOperationAction(ISD::SUB, VT, Legal); 632 633 // For v2i64, these are only valid with P8Vector. This is corrected after 634 // the loop. 635 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 636 setOperationAction(ISD::SMAX, VT, Legal); 637 setOperationAction(ISD::SMIN, VT, Legal); 638 setOperationAction(ISD::UMAX, VT, Legal); 639 setOperationAction(ISD::UMIN, VT, Legal); 640 } 641 else { 642 setOperationAction(ISD::SMAX, VT, Expand); 643 setOperationAction(ISD::SMIN, VT, Expand); 644 setOperationAction(ISD::UMAX, VT, Expand); 645 setOperationAction(ISD::UMIN, VT, Expand); 646 } 647 648 if (Subtarget.hasVSX()) { 649 setOperationAction(ISD::FMAXNUM, VT, Legal); 650 setOperationAction(ISD::FMINNUM, VT, Legal); 651 } 652 653 // Vector instructions introduced in P8 654 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 655 setOperationAction(ISD::CTPOP, VT, Legal); 656 setOperationAction(ISD::CTLZ, VT, Legal); 657 } 658 else { 659 setOperationAction(ISD::CTPOP, VT, Expand); 660 setOperationAction(ISD::CTLZ, VT, Expand); 661 } 662 663 // Vector instructions introduced in P9 664 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 665 setOperationAction(ISD::CTTZ, VT, Legal); 666 else 667 setOperationAction(ISD::CTTZ, VT, Expand); 668 669 // We promote all shuffles to v16i8. 670 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 671 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 672 673 // We promote all non-typed operations to v4i32. 674 setOperationAction(ISD::AND , VT, Promote); 675 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 676 setOperationAction(ISD::OR , VT, Promote); 677 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 678 setOperationAction(ISD::XOR , VT, Promote); 679 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 680 setOperationAction(ISD::LOAD , VT, Promote); 681 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 682 setOperationAction(ISD::SELECT, VT, Promote); 683 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 684 setOperationAction(ISD::VSELECT, VT, Legal); 685 setOperationAction(ISD::SELECT_CC, VT, Promote); 686 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 687 setOperationAction(ISD::STORE, VT, Promote); 688 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 689 690 // No other operations are legal. 691 setOperationAction(ISD::MUL , VT, Expand); 692 setOperationAction(ISD::SDIV, VT, Expand); 693 setOperationAction(ISD::SREM, VT, Expand); 694 setOperationAction(ISD::UDIV, VT, Expand); 695 setOperationAction(ISD::UREM, VT, Expand); 696 setOperationAction(ISD::FDIV, VT, Expand); 697 setOperationAction(ISD::FREM, VT, Expand); 698 setOperationAction(ISD::FNEG, VT, Expand); 699 setOperationAction(ISD::FSQRT, VT, Expand); 700 setOperationAction(ISD::FLOG, VT, Expand); 701 setOperationAction(ISD::FLOG10, VT, Expand); 702 setOperationAction(ISD::FLOG2, VT, Expand); 703 setOperationAction(ISD::FEXP, VT, Expand); 704 setOperationAction(ISD::FEXP2, VT, Expand); 705 setOperationAction(ISD::FSIN, VT, Expand); 706 setOperationAction(ISD::FCOS, VT, Expand); 707 setOperationAction(ISD::FABS, VT, Expand); 708 setOperationAction(ISD::FFLOOR, VT, Expand); 709 setOperationAction(ISD::FCEIL, VT, Expand); 710 setOperationAction(ISD::FTRUNC, VT, Expand); 711 setOperationAction(ISD::FRINT, VT, Expand); 712 setOperationAction(ISD::FNEARBYINT, VT, Expand); 713 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 714 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 715 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 716 setOperationAction(ISD::MULHU, VT, Expand); 717 setOperationAction(ISD::MULHS, VT, Expand); 718 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 719 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 720 setOperationAction(ISD::UDIVREM, VT, Expand); 721 setOperationAction(ISD::SDIVREM, VT, Expand); 722 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 723 setOperationAction(ISD::FPOW, VT, Expand); 724 setOperationAction(ISD::BSWAP, VT, Expand); 725 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 726 setOperationAction(ISD::ROTL, VT, Expand); 727 setOperationAction(ISD::ROTR, VT, Expand); 728 729 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 730 setTruncStoreAction(VT, InnerVT, Expand); 731 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 732 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 733 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 734 } 735 } 736 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 737 if (!Subtarget.hasP8Vector()) { 738 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 739 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 740 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 741 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 742 } 743 744 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 745 setOperationAction(ISD::ABS, VT, Custom); 746 747 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 748 // with merges, splats, etc. 749 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 750 751 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 752 // are cheap, so handle them before they get expanded to scalar. 753 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 754 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 755 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 756 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 757 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 758 759 setOperationAction(ISD::AND , MVT::v4i32, Legal); 760 setOperationAction(ISD::OR , MVT::v4i32, Legal); 761 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 762 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 763 setOperationAction(ISD::SELECT, MVT::v4i32, 764 Subtarget.useCRBits() ? Legal : Expand); 765 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 766 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 767 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 768 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 769 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 770 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 771 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 772 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 773 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 774 775 // Without hasP8Altivec set, v2i64 SMAX isn't available. 776 // But ABS custom lowering requires SMAX support. 777 if (!Subtarget.hasP8Altivec()) 778 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 779 780 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 781 if (Subtarget.hasAltivec()) 782 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 783 setOperationAction(ISD::ROTL, VT, Legal); 784 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 785 if (Subtarget.hasP8Altivec()) 786 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 787 788 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 789 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 790 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 791 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 792 793 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 794 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 795 796 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 797 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 798 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 799 } 800 801 if (Subtarget.hasP8Altivec()) 802 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 803 else 804 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 805 806 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 807 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 808 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 811 812 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 813 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 814 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 815 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 816 817 // Altivec does not contain unordered floating-point compare instructions 818 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 819 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 820 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 821 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 822 823 if (Subtarget.hasVSX()) { 824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 826 if (Subtarget.hasP8Vector()) { 827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 829 } 830 if (Subtarget.hasDirectMove() && isPPC64) { 831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 832 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 833 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 835 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 836 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 837 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 839 } 840 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 841 842 // The nearbyint variants are not allowed to raise the inexact exception 843 // so we can only code-gen them with unsafe math. 844 if (TM.Options.UnsafeFPMath) { 845 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 846 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 847 } 848 849 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 850 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 851 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 852 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 853 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 854 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 855 setOperationAction(ISD::FROUND, MVT::f64, Legal); 856 setOperationAction(ISD::FRINT, MVT::f64, Legal); 857 858 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 859 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 860 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 861 setOperationAction(ISD::FROUND, MVT::f32, Legal); 862 setOperationAction(ISD::FRINT, MVT::f32, Legal); 863 864 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 865 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 866 867 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 868 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 869 870 // Share the Altivec comparison restrictions. 871 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 872 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 873 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 874 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 875 876 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 877 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 878 879 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 880 881 if (Subtarget.hasP8Vector()) 882 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 883 884 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 885 886 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 887 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 888 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 889 890 if (Subtarget.hasP8Altivec()) { 891 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 892 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 893 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 894 895 // 128 bit shifts can be accomplished via 3 instructions for SHL and 896 // SRL, but not for SRA because of the instructions available: 897 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 898 // doing 899 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 900 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 901 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 902 903 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 904 } 905 else { 906 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 907 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 908 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 909 910 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 911 912 // VSX v2i64 only supports non-arithmetic operations. 913 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 914 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 915 } 916 917 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 918 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 919 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 920 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 921 922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 923 924 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 925 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 926 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 927 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 928 929 // Custom handling for partial vectors of integers converted to 930 // floating point. We already have optimal handling for v2i32 through 931 // the DAG combine, so those aren't necessary. 932 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 933 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 934 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 935 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 936 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 937 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 938 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 939 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 940 941 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 942 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 943 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 944 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 945 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 946 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 947 948 if (Subtarget.hasDirectMove()) 949 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 950 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 951 952 // Handle constrained floating-point operations of vector. 953 // The predictor is `hasVSX` because altivec instruction has 954 // no exception but VSX vector instruction has. 955 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 956 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 957 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 958 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 959 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 960 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 961 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 962 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 963 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 964 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 965 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 966 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 967 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 968 969 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 970 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 971 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 972 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 973 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 974 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 975 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 976 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 977 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 978 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 979 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 980 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 981 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 982 983 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 984 } 985 986 if (Subtarget.hasP8Altivec()) { 987 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 988 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 989 } 990 991 if (Subtarget.hasP9Vector()) { 992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 994 995 // 128 bit shifts can be accomplished via 3 instructions for SHL and 996 // SRL, but not for SRA because of the instructions available: 997 // VS{RL} and VS{RL}O. 998 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 999 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1000 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1001 1002 if (EnableQuadPrecision) { 1003 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1004 setOperationAction(ISD::FADD, MVT::f128, Legal); 1005 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1006 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1007 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1008 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1009 // No extending loads to f128 on PPC. 1010 for (MVT FPT : MVT::fp_valuetypes()) 1011 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1012 setOperationAction(ISD::FMA, MVT::f128, Legal); 1013 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1014 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1015 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1016 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1017 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1018 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1019 1020 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1021 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1022 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1023 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1024 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1025 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1026 1027 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1028 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1029 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1030 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1031 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1032 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1033 // No implementation for these ops for PowerPC. 1034 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1035 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1036 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1037 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1038 setOperationAction(ISD::FREM, MVT::f128, Expand); 1039 1040 // Handle constrained floating-point operations of fp128 1041 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1042 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1043 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1044 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1045 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1046 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1047 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1048 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1049 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1050 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1051 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1052 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1053 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1054 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1055 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1056 } 1057 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1058 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1059 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1060 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1061 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1062 } 1063 1064 if (Subtarget.hasP9Altivec()) { 1065 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1066 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1067 1068 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1069 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1070 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1071 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1072 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1073 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1074 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1075 } 1076 } 1077 1078 if (Subtarget.hasQPX()) { 1079 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1080 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1081 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1082 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1083 1084 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1086 1087 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1088 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1089 1090 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1091 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1092 1093 if (!Subtarget.useCRBits()) 1094 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1095 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1096 1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1098 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1099 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1100 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1101 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1102 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1103 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1104 1105 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1106 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1107 1108 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1109 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1110 1111 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1112 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1113 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1114 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1115 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1116 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1117 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1118 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1119 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1120 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1121 1122 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1123 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1124 1125 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1126 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1127 1128 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1129 1130 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1131 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1132 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1133 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1134 1135 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1136 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1137 1138 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1139 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1140 1141 if (!Subtarget.useCRBits()) 1142 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1143 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1144 1145 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1146 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1147 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1148 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1149 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1150 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1151 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1152 1153 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1154 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1155 1156 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1157 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1158 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1159 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1160 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1161 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1162 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1163 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1164 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1165 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1166 1167 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1168 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1169 1170 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1171 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1172 1173 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1174 1175 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1176 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1177 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1178 1179 if (!Subtarget.useCRBits()) 1180 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1181 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1182 1183 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1184 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1185 1186 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1187 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1188 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1189 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1190 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1191 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1192 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1193 1194 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1195 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1196 1197 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1198 1199 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1200 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1201 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1202 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1203 1204 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1205 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1206 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1207 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1208 1209 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1210 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1211 1212 // These need to set FE_INEXACT, and so cannot be vectorized here. 1213 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1214 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1215 1216 if (TM.Options.UnsafeFPMath) { 1217 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1218 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1219 1220 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1221 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1222 } else { 1223 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1224 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1225 1226 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1227 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1228 } 1229 1230 // TODO: Handle constrained floating-point operations of v4f64 1231 } 1232 1233 if (Subtarget.has64BitSupport()) 1234 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1235 1236 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1237 1238 if (!isPPC64) { 1239 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1240 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1241 } 1242 1243 setBooleanContents(ZeroOrOneBooleanContent); 1244 1245 if (Subtarget.hasAltivec()) { 1246 // Altivec instructions set fields to all zeros or all ones. 1247 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1248 } 1249 1250 if (!isPPC64) { 1251 // These libcalls are not available in 32-bit. 1252 setLibcallName(RTLIB::SHL_I128, nullptr); 1253 setLibcallName(RTLIB::SRL_I128, nullptr); 1254 setLibcallName(RTLIB::SRA_I128, nullptr); 1255 } 1256 1257 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1258 1259 // We have target-specific dag combine patterns for the following nodes: 1260 setTargetDAGCombine(ISD::ADD); 1261 setTargetDAGCombine(ISD::SHL); 1262 setTargetDAGCombine(ISD::SRA); 1263 setTargetDAGCombine(ISD::SRL); 1264 setTargetDAGCombine(ISD::MUL); 1265 setTargetDAGCombine(ISD::FMA); 1266 setTargetDAGCombine(ISD::SINT_TO_FP); 1267 setTargetDAGCombine(ISD::BUILD_VECTOR); 1268 if (Subtarget.hasFPCVT()) 1269 setTargetDAGCombine(ISD::UINT_TO_FP); 1270 setTargetDAGCombine(ISD::LOAD); 1271 setTargetDAGCombine(ISD::STORE); 1272 setTargetDAGCombine(ISD::BR_CC); 1273 if (Subtarget.useCRBits()) 1274 setTargetDAGCombine(ISD::BRCOND); 1275 setTargetDAGCombine(ISD::BSWAP); 1276 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1277 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1278 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1279 1280 setTargetDAGCombine(ISD::SIGN_EXTEND); 1281 setTargetDAGCombine(ISD::ZERO_EXTEND); 1282 setTargetDAGCombine(ISD::ANY_EXTEND); 1283 1284 setTargetDAGCombine(ISD::TRUNCATE); 1285 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1286 1287 1288 if (Subtarget.useCRBits()) { 1289 setTargetDAGCombine(ISD::TRUNCATE); 1290 setTargetDAGCombine(ISD::SETCC); 1291 setTargetDAGCombine(ISD::SELECT_CC); 1292 } 1293 1294 // Use reciprocal estimates. 1295 if (TM.Options.UnsafeFPMath) { 1296 setTargetDAGCombine(ISD::FDIV); 1297 setTargetDAGCombine(ISD::FSQRT); 1298 } 1299 1300 if (Subtarget.hasP9Altivec()) { 1301 setTargetDAGCombine(ISD::ABS); 1302 setTargetDAGCombine(ISD::VSELECT); 1303 } 1304 1305 if (EnableQuadPrecision) { 1306 setLibcallName(RTLIB::LOG_F128, "logf128"); 1307 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1308 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1309 setLibcallName(RTLIB::EXP_F128, "expf128"); 1310 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1311 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1312 setLibcallName(RTLIB::COS_F128, "cosf128"); 1313 setLibcallName(RTLIB::POW_F128, "powf128"); 1314 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1315 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1316 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1317 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1318 } 1319 1320 // With 32 condition bits, we don't need to sink (and duplicate) compares 1321 // aggressively in CodeGenPrep. 1322 if (Subtarget.useCRBits()) { 1323 setHasMultipleConditionRegisters(); 1324 setJumpIsExpensive(); 1325 } 1326 1327 setMinFunctionAlignment(Align(4)); 1328 1329 switch (Subtarget.getCPUDirective()) { 1330 default: break; 1331 case PPC::DIR_970: 1332 case PPC::DIR_A2: 1333 case PPC::DIR_E500: 1334 case PPC::DIR_E500mc: 1335 case PPC::DIR_E5500: 1336 case PPC::DIR_PWR4: 1337 case PPC::DIR_PWR5: 1338 case PPC::DIR_PWR5X: 1339 case PPC::DIR_PWR6: 1340 case PPC::DIR_PWR6X: 1341 case PPC::DIR_PWR7: 1342 case PPC::DIR_PWR8: 1343 case PPC::DIR_PWR9: 1344 case PPC::DIR_PWR10: 1345 case PPC::DIR_PWR_FUTURE: 1346 setPrefLoopAlignment(Align(16)); 1347 setPrefFunctionAlignment(Align(16)); 1348 break; 1349 } 1350 1351 if (Subtarget.enableMachineScheduler()) 1352 setSchedulingPreference(Sched::Source); 1353 else 1354 setSchedulingPreference(Sched::Hybrid); 1355 1356 computeRegisterProperties(STI.getRegisterInfo()); 1357 1358 // The Freescale cores do better with aggressive inlining of memcpy and 1359 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1360 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1361 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1362 MaxStoresPerMemset = 32; 1363 MaxStoresPerMemsetOptSize = 16; 1364 MaxStoresPerMemcpy = 32; 1365 MaxStoresPerMemcpyOptSize = 8; 1366 MaxStoresPerMemmove = 32; 1367 MaxStoresPerMemmoveOptSize = 8; 1368 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1369 // The A2 also benefits from (very) aggressive inlining of memcpy and 1370 // friends. The overhead of a the function call, even when warm, can be 1371 // over one hundred cycles. 1372 MaxStoresPerMemset = 128; 1373 MaxStoresPerMemcpy = 128; 1374 MaxStoresPerMemmove = 128; 1375 MaxLoadsPerMemcmp = 128; 1376 } else { 1377 MaxLoadsPerMemcmp = 8; 1378 MaxLoadsPerMemcmpOptSize = 4; 1379 } 1380 1381 // Let the subtarget (CPU) decide if a predictable select is more expensive 1382 // than the corresponding branch. This information is used in CGP to decide 1383 // when to convert selects into branches. 1384 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1385 } 1386 1387 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1388 /// the desired ByVal argument alignment. 1389 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1390 unsigned MaxMaxAlign) { 1391 if (MaxAlign == MaxMaxAlign) 1392 return; 1393 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1394 if (MaxMaxAlign >= 32 && 1395 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1396 MaxAlign = 32; 1397 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1398 MaxAlign < 16) 1399 MaxAlign = 16; 1400 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1401 unsigned EltAlign = 0; 1402 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1403 if (EltAlign > MaxAlign) 1404 MaxAlign = EltAlign; 1405 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1406 for (auto *EltTy : STy->elements()) { 1407 unsigned EltAlign = 0; 1408 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1409 if (EltAlign > MaxAlign) 1410 MaxAlign = EltAlign; 1411 if (MaxAlign == MaxMaxAlign) 1412 break; 1413 } 1414 } 1415 } 1416 1417 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1418 /// function arguments in the caller parameter area. 1419 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1420 const DataLayout &DL) const { 1421 // 16byte and wider vectors are passed on 16byte boundary. 1422 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1423 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1424 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1425 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1426 return Align; 1427 } 1428 1429 bool PPCTargetLowering::useSoftFloat() const { 1430 return Subtarget.useSoftFloat(); 1431 } 1432 1433 bool PPCTargetLowering::hasSPE() const { 1434 return Subtarget.hasSPE(); 1435 } 1436 1437 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1438 return VT.isScalarInteger(); 1439 } 1440 1441 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1442 /// type is cheaper than a multiply followed by a shift. 1443 /// This is true for words and doublewords on 64-bit PowerPC. 1444 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1445 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1446 isOperationLegal(ISD::MULHU, Type))) 1447 return true; 1448 return TargetLowering::isMulhCheaperThanMulShift(Type); 1449 } 1450 1451 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1452 switch ((PPCISD::NodeType)Opcode) { 1453 case PPCISD::FIRST_NUMBER: break; 1454 case PPCISD::FSEL: return "PPCISD::FSEL"; 1455 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1456 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1457 case PPCISD::FCFID: return "PPCISD::FCFID"; 1458 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1459 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1460 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1461 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1462 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1463 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1464 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1465 case PPCISD::FP_TO_UINT_IN_VSR: 1466 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1467 case PPCISD::FP_TO_SINT_IN_VSR: 1468 return "PPCISD::FP_TO_SINT_IN_VSR"; 1469 case PPCISD::FRE: return "PPCISD::FRE"; 1470 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1471 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1472 case PPCISD::VPERM: return "PPCISD::VPERM"; 1473 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1474 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1475 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1476 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1477 case PPCISD::CMPB: return "PPCISD::CMPB"; 1478 case PPCISD::Hi: return "PPCISD::Hi"; 1479 case PPCISD::Lo: return "PPCISD::Lo"; 1480 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1481 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1482 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1483 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1484 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1485 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1486 case PPCISD::SRL: return "PPCISD::SRL"; 1487 case PPCISD::SRA: return "PPCISD::SRA"; 1488 case PPCISD::SHL: return "PPCISD::SHL"; 1489 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1490 case PPCISD::CALL: return "PPCISD::CALL"; 1491 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1492 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1493 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1494 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1495 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1496 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1497 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1498 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1499 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1500 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1501 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1502 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1503 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1504 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1505 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1506 case PPCISD::ANDI_rec_1_EQ_BIT: 1507 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1508 case PPCISD::ANDI_rec_1_GT_BIT: 1509 return "PPCISD::ANDI_rec_1_GT_BIT"; 1510 case PPCISD::VCMP: return "PPCISD::VCMP"; 1511 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1512 case PPCISD::LBRX: return "PPCISD::LBRX"; 1513 case PPCISD::STBRX: return "PPCISD::STBRX"; 1514 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1515 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1516 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1517 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1518 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1519 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1520 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1521 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1522 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1523 case PPCISD::ST_VSR_SCAL_INT: 1524 return "PPCISD::ST_VSR_SCAL_INT"; 1525 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1526 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1527 case PPCISD::BDZ: return "PPCISD::BDZ"; 1528 case PPCISD::MFFS: return "PPCISD::MFFS"; 1529 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1530 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1531 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1532 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1533 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1534 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1535 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1536 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1537 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1538 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1539 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1540 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1541 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1542 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1543 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1544 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1545 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1546 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1547 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1548 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1549 case PPCISD::SC: return "PPCISD::SC"; 1550 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1551 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1552 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1553 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1554 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1555 case PPCISD::VABSD: return "PPCISD::VABSD"; 1556 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1557 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1558 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1559 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1560 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1561 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1562 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1563 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1564 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1565 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1566 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1567 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1568 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1569 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1570 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1571 } 1572 return nullptr; 1573 } 1574 1575 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1576 EVT VT) const { 1577 if (!VT.isVector()) 1578 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1579 1580 if (Subtarget.hasQPX()) 1581 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1582 1583 return VT.changeVectorElementTypeToInteger(); 1584 } 1585 1586 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1587 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1588 return true; 1589 } 1590 1591 //===----------------------------------------------------------------------===// 1592 // Node matching predicates, for use by the tblgen matching code. 1593 //===----------------------------------------------------------------------===// 1594 1595 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1596 static bool isFloatingPointZero(SDValue Op) { 1597 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1598 return CFP->getValueAPF().isZero(); 1599 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1600 // Maybe this has already been legalized into the constant pool? 1601 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1602 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1603 return CFP->getValueAPF().isZero(); 1604 } 1605 return false; 1606 } 1607 1608 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1609 /// true if Op is undef or if it matches the specified value. 1610 static bool isConstantOrUndef(int Op, int Val) { 1611 return Op < 0 || Op == Val; 1612 } 1613 1614 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1615 /// VPKUHUM instruction. 1616 /// The ShuffleKind distinguishes between big-endian operations with 1617 /// two different inputs (0), either-endian operations with two identical 1618 /// inputs (1), and little-endian operations with two different inputs (2). 1619 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1620 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1621 SelectionDAG &DAG) { 1622 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1623 if (ShuffleKind == 0) { 1624 if (IsLE) 1625 return false; 1626 for (unsigned i = 0; i != 16; ++i) 1627 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1628 return false; 1629 } else if (ShuffleKind == 2) { 1630 if (!IsLE) 1631 return false; 1632 for (unsigned i = 0; i != 16; ++i) 1633 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1634 return false; 1635 } else if (ShuffleKind == 1) { 1636 unsigned j = IsLE ? 0 : 1; 1637 for (unsigned i = 0; i != 8; ++i) 1638 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1639 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1640 return false; 1641 } 1642 return true; 1643 } 1644 1645 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1646 /// VPKUWUM instruction. 1647 /// The ShuffleKind distinguishes between big-endian operations with 1648 /// two different inputs (0), either-endian operations with two identical 1649 /// inputs (1), and little-endian operations with two different inputs (2). 1650 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1651 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1652 SelectionDAG &DAG) { 1653 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1654 if (ShuffleKind == 0) { 1655 if (IsLE) 1656 return false; 1657 for (unsigned i = 0; i != 16; i += 2) 1658 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1659 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1660 return false; 1661 } else if (ShuffleKind == 2) { 1662 if (!IsLE) 1663 return false; 1664 for (unsigned i = 0; i != 16; i += 2) 1665 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1666 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1667 return false; 1668 } else if (ShuffleKind == 1) { 1669 unsigned j = IsLE ? 0 : 2; 1670 for (unsigned i = 0; i != 8; i += 2) 1671 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1672 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1673 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1674 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1675 return false; 1676 } 1677 return true; 1678 } 1679 1680 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1681 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1682 /// current subtarget. 1683 /// 1684 /// The ShuffleKind distinguishes between big-endian operations with 1685 /// two different inputs (0), either-endian operations with two identical 1686 /// inputs (1), and little-endian operations with two different inputs (2). 1687 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1688 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1689 SelectionDAG &DAG) { 1690 const PPCSubtarget& Subtarget = 1691 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1692 if (!Subtarget.hasP8Vector()) 1693 return false; 1694 1695 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1696 if (ShuffleKind == 0) { 1697 if (IsLE) 1698 return false; 1699 for (unsigned i = 0; i != 16; i += 4) 1700 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1701 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1702 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1703 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1704 return false; 1705 } else if (ShuffleKind == 2) { 1706 if (!IsLE) 1707 return false; 1708 for (unsigned i = 0; i != 16; i += 4) 1709 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1710 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1711 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1712 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1713 return false; 1714 } else if (ShuffleKind == 1) { 1715 unsigned j = IsLE ? 0 : 4; 1716 for (unsigned i = 0; i != 8; i += 4) 1717 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1718 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1719 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1720 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1721 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1722 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1723 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1724 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1725 return false; 1726 } 1727 return true; 1728 } 1729 1730 /// isVMerge - Common function, used to match vmrg* shuffles. 1731 /// 1732 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1733 unsigned LHSStart, unsigned RHSStart) { 1734 if (N->getValueType(0) != MVT::v16i8) 1735 return false; 1736 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1737 "Unsupported merge size!"); 1738 1739 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1740 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1741 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1742 LHSStart+j+i*UnitSize) || 1743 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1744 RHSStart+j+i*UnitSize)) 1745 return false; 1746 } 1747 return true; 1748 } 1749 1750 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1751 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1752 /// The ShuffleKind distinguishes between big-endian merges with two 1753 /// different inputs (0), either-endian merges with two identical inputs (1), 1754 /// and little-endian merges with two different inputs (2). For the latter, 1755 /// the input operands are swapped (see PPCInstrAltivec.td). 1756 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1757 unsigned ShuffleKind, SelectionDAG &DAG) { 1758 if (DAG.getDataLayout().isLittleEndian()) { 1759 if (ShuffleKind == 1) // unary 1760 return isVMerge(N, UnitSize, 0, 0); 1761 else if (ShuffleKind == 2) // swapped 1762 return isVMerge(N, UnitSize, 0, 16); 1763 else 1764 return false; 1765 } else { 1766 if (ShuffleKind == 1) // unary 1767 return isVMerge(N, UnitSize, 8, 8); 1768 else if (ShuffleKind == 0) // normal 1769 return isVMerge(N, UnitSize, 8, 24); 1770 else 1771 return false; 1772 } 1773 } 1774 1775 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1776 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1777 /// The ShuffleKind distinguishes between big-endian merges with two 1778 /// different inputs (0), either-endian merges with two identical inputs (1), 1779 /// and little-endian merges with two different inputs (2). For the latter, 1780 /// the input operands are swapped (see PPCInstrAltivec.td). 1781 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1782 unsigned ShuffleKind, SelectionDAG &DAG) { 1783 if (DAG.getDataLayout().isLittleEndian()) { 1784 if (ShuffleKind == 1) // unary 1785 return isVMerge(N, UnitSize, 8, 8); 1786 else if (ShuffleKind == 2) // swapped 1787 return isVMerge(N, UnitSize, 8, 24); 1788 else 1789 return false; 1790 } else { 1791 if (ShuffleKind == 1) // unary 1792 return isVMerge(N, UnitSize, 0, 0); 1793 else if (ShuffleKind == 0) // normal 1794 return isVMerge(N, UnitSize, 0, 16); 1795 else 1796 return false; 1797 } 1798 } 1799 1800 /** 1801 * Common function used to match vmrgew and vmrgow shuffles 1802 * 1803 * The indexOffset determines whether to look for even or odd words in 1804 * the shuffle mask. This is based on the of the endianness of the target 1805 * machine. 1806 * - Little Endian: 1807 * - Use offset of 0 to check for odd elements 1808 * - Use offset of 4 to check for even elements 1809 * - Big Endian: 1810 * - Use offset of 0 to check for even elements 1811 * - Use offset of 4 to check for odd elements 1812 * A detailed description of the vector element ordering for little endian and 1813 * big endian can be found at 1814 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1815 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1816 * compiler differences mean to you 1817 * 1818 * The mask to the shuffle vector instruction specifies the indices of the 1819 * elements from the two input vectors to place in the result. The elements are 1820 * numbered in array-access order, starting with the first vector. These vectors 1821 * are always of type v16i8, thus each vector will contain 16 elements of size 1822 * 8. More info on the shuffle vector can be found in the 1823 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1824 * Language Reference. 1825 * 1826 * The RHSStartValue indicates whether the same input vectors are used (unary) 1827 * or two different input vectors are used, based on the following: 1828 * - If the instruction uses the same vector for both inputs, the range of the 1829 * indices will be 0 to 15. In this case, the RHSStart value passed should 1830 * be 0. 1831 * - If the instruction has two different vectors then the range of the 1832 * indices will be 0 to 31. In this case, the RHSStart value passed should 1833 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1834 * to 31 specify elements in the second vector). 1835 * 1836 * \param[in] N The shuffle vector SD Node to analyze 1837 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1838 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1839 * vector to the shuffle_vector instruction 1840 * \return true iff this shuffle vector represents an even or odd word merge 1841 */ 1842 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1843 unsigned RHSStartValue) { 1844 if (N->getValueType(0) != MVT::v16i8) 1845 return false; 1846 1847 for (unsigned i = 0; i < 2; ++i) 1848 for (unsigned j = 0; j < 4; ++j) 1849 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1850 i*RHSStartValue+j+IndexOffset) || 1851 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1852 i*RHSStartValue+j+IndexOffset+8)) 1853 return false; 1854 return true; 1855 } 1856 1857 /** 1858 * Determine if the specified shuffle mask is suitable for the vmrgew or 1859 * vmrgow instructions. 1860 * 1861 * \param[in] N The shuffle vector SD Node to analyze 1862 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1863 * \param[in] ShuffleKind Identify the type of merge: 1864 * - 0 = big-endian merge with two different inputs; 1865 * - 1 = either-endian merge with two identical inputs; 1866 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1867 * little-endian merges). 1868 * \param[in] DAG The current SelectionDAG 1869 * \return true iff this shuffle mask 1870 */ 1871 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1872 unsigned ShuffleKind, SelectionDAG &DAG) { 1873 if (DAG.getDataLayout().isLittleEndian()) { 1874 unsigned indexOffset = CheckEven ? 4 : 0; 1875 if (ShuffleKind == 1) // Unary 1876 return isVMerge(N, indexOffset, 0); 1877 else if (ShuffleKind == 2) // swapped 1878 return isVMerge(N, indexOffset, 16); 1879 else 1880 return false; 1881 } 1882 else { 1883 unsigned indexOffset = CheckEven ? 0 : 4; 1884 if (ShuffleKind == 1) // Unary 1885 return isVMerge(N, indexOffset, 0); 1886 else if (ShuffleKind == 0) // Normal 1887 return isVMerge(N, indexOffset, 16); 1888 else 1889 return false; 1890 } 1891 return false; 1892 } 1893 1894 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1895 /// amount, otherwise return -1. 1896 /// The ShuffleKind distinguishes between big-endian operations with two 1897 /// different inputs (0), either-endian operations with two identical inputs 1898 /// (1), and little-endian operations with two different inputs (2). For the 1899 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1900 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1901 SelectionDAG &DAG) { 1902 if (N->getValueType(0) != MVT::v16i8) 1903 return -1; 1904 1905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1906 1907 // Find the first non-undef value in the shuffle mask. 1908 unsigned i; 1909 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1910 /*search*/; 1911 1912 if (i == 16) return -1; // all undef. 1913 1914 // Otherwise, check to see if the rest of the elements are consecutively 1915 // numbered from this value. 1916 unsigned ShiftAmt = SVOp->getMaskElt(i); 1917 if (ShiftAmt < i) return -1; 1918 1919 ShiftAmt -= i; 1920 bool isLE = DAG.getDataLayout().isLittleEndian(); 1921 1922 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1923 // Check the rest of the elements to see if they are consecutive. 1924 for (++i; i != 16; ++i) 1925 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1926 return -1; 1927 } else if (ShuffleKind == 1) { 1928 // Check the rest of the elements to see if they are consecutive. 1929 for (++i; i != 16; ++i) 1930 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1931 return -1; 1932 } else 1933 return -1; 1934 1935 if (isLE) 1936 ShiftAmt = 16 - ShiftAmt; 1937 1938 return ShiftAmt; 1939 } 1940 1941 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1942 /// specifies a splat of a single element that is suitable for input to 1943 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1944 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1945 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1946 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1947 1948 // The consecutive indices need to specify an element, not part of two 1949 // different elements. So abandon ship early if this isn't the case. 1950 if (N->getMaskElt(0) % EltSize != 0) 1951 return false; 1952 1953 // This is a splat operation if each element of the permute is the same, and 1954 // if the value doesn't reference the second vector. 1955 unsigned ElementBase = N->getMaskElt(0); 1956 1957 // FIXME: Handle UNDEF elements too! 1958 if (ElementBase >= 16) 1959 return false; 1960 1961 // Check that the indices are consecutive, in the case of a multi-byte element 1962 // splatted with a v16i8 mask. 1963 for (unsigned i = 1; i != EltSize; ++i) 1964 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1965 return false; 1966 1967 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1968 if (N->getMaskElt(i) < 0) continue; 1969 for (unsigned j = 0; j != EltSize; ++j) 1970 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1971 return false; 1972 } 1973 return true; 1974 } 1975 1976 /// Check that the mask is shuffling N byte elements. Within each N byte 1977 /// element of the mask, the indices could be either in increasing or 1978 /// decreasing order as long as they are consecutive. 1979 /// \param[in] N the shuffle vector SD Node to analyze 1980 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1981 /// Word/DoubleWord/QuadWord). 1982 /// \param[in] StepLen the delta indices number among the N byte element, if 1983 /// the mask is in increasing/decreasing order then it is 1/-1. 1984 /// \return true iff the mask is shuffling N byte elements. 1985 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1986 int StepLen) { 1987 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1988 "Unexpected element width."); 1989 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1990 1991 unsigned NumOfElem = 16 / Width; 1992 unsigned MaskVal[16]; // Width is never greater than 16 1993 for (unsigned i = 0; i < NumOfElem; ++i) { 1994 MaskVal[0] = N->getMaskElt(i * Width); 1995 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1996 return false; 1997 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1998 return false; 1999 } 2000 2001 for (unsigned int j = 1; j < Width; ++j) { 2002 MaskVal[j] = N->getMaskElt(i * Width + j); 2003 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2004 return false; 2005 } 2006 } 2007 } 2008 2009 return true; 2010 } 2011 2012 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2013 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2014 if (!isNByteElemShuffleMask(N, 4, 1)) 2015 return false; 2016 2017 // Now we look at mask elements 0,4,8,12 2018 unsigned M0 = N->getMaskElt(0) / 4; 2019 unsigned M1 = N->getMaskElt(4) / 4; 2020 unsigned M2 = N->getMaskElt(8) / 4; 2021 unsigned M3 = N->getMaskElt(12) / 4; 2022 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2023 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2024 2025 // Below, let H and L be arbitrary elements of the shuffle mask 2026 // where H is in the range [4,7] and L is in the range [0,3]. 2027 // H, 1, 2, 3 or L, 5, 6, 7 2028 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2029 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2030 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2031 InsertAtByte = IsLE ? 12 : 0; 2032 Swap = M0 < 4; 2033 return true; 2034 } 2035 // 0, H, 2, 3 or 4, L, 6, 7 2036 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2037 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2038 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2039 InsertAtByte = IsLE ? 8 : 4; 2040 Swap = M1 < 4; 2041 return true; 2042 } 2043 // 0, 1, H, 3 or 4, 5, L, 7 2044 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2045 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2046 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2047 InsertAtByte = IsLE ? 4 : 8; 2048 Swap = M2 < 4; 2049 return true; 2050 } 2051 // 0, 1, 2, H or 4, 5, 6, L 2052 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2053 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2054 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2055 InsertAtByte = IsLE ? 0 : 12; 2056 Swap = M3 < 4; 2057 return true; 2058 } 2059 2060 // If both vector operands for the shuffle are the same vector, the mask will 2061 // contain only elements from the first one and the second one will be undef. 2062 if (N->getOperand(1).isUndef()) { 2063 ShiftElts = 0; 2064 Swap = true; 2065 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2066 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2067 InsertAtByte = IsLE ? 12 : 0; 2068 return true; 2069 } 2070 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2071 InsertAtByte = IsLE ? 8 : 4; 2072 return true; 2073 } 2074 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2075 InsertAtByte = IsLE ? 4 : 8; 2076 return true; 2077 } 2078 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2079 InsertAtByte = IsLE ? 0 : 12; 2080 return true; 2081 } 2082 } 2083 2084 return false; 2085 } 2086 2087 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2088 bool &Swap, bool IsLE) { 2089 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2090 // Ensure each byte index of the word is consecutive. 2091 if (!isNByteElemShuffleMask(N, 4, 1)) 2092 return false; 2093 2094 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2095 unsigned M0 = N->getMaskElt(0) / 4; 2096 unsigned M1 = N->getMaskElt(4) / 4; 2097 unsigned M2 = N->getMaskElt(8) / 4; 2098 unsigned M3 = N->getMaskElt(12) / 4; 2099 2100 // If both vector operands for the shuffle are the same vector, the mask will 2101 // contain only elements from the first one and the second one will be undef. 2102 if (N->getOperand(1).isUndef()) { 2103 assert(M0 < 4 && "Indexing into an undef vector?"); 2104 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2105 return false; 2106 2107 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2108 Swap = false; 2109 return true; 2110 } 2111 2112 // Ensure each word index of the ShuffleVector Mask is consecutive. 2113 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2114 return false; 2115 2116 if (IsLE) { 2117 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2118 // Input vectors don't need to be swapped if the leading element 2119 // of the result is one of the 3 left elements of the second vector 2120 // (or if there is no shift to be done at all). 2121 Swap = false; 2122 ShiftElts = (8 - M0) % 8; 2123 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2124 // Input vectors need to be swapped if the leading element 2125 // of the result is one of the 3 left elements of the first vector 2126 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2127 Swap = true; 2128 ShiftElts = (4 - M0) % 4; 2129 } 2130 2131 return true; 2132 } else { // BE 2133 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2134 // Input vectors don't need to be swapped if the leading element 2135 // of the result is one of the 4 elements of the first vector. 2136 Swap = false; 2137 ShiftElts = M0; 2138 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2139 // Input vectors need to be swapped if the leading element 2140 // of the result is one of the 4 elements of the right vector. 2141 Swap = true; 2142 ShiftElts = M0 - 4; 2143 } 2144 2145 return true; 2146 } 2147 } 2148 2149 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2150 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2151 2152 if (!isNByteElemShuffleMask(N, Width, -1)) 2153 return false; 2154 2155 for (int i = 0; i < 16; i += Width) 2156 if (N->getMaskElt(i) != i + Width - 1) 2157 return false; 2158 2159 return true; 2160 } 2161 2162 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2163 return isXXBRShuffleMaskHelper(N, 2); 2164 } 2165 2166 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2167 return isXXBRShuffleMaskHelper(N, 4); 2168 } 2169 2170 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2171 return isXXBRShuffleMaskHelper(N, 8); 2172 } 2173 2174 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2175 return isXXBRShuffleMaskHelper(N, 16); 2176 } 2177 2178 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2179 /// if the inputs to the instruction should be swapped and set \p DM to the 2180 /// value for the immediate. 2181 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2182 /// AND element 0 of the result comes from the first input (LE) or second input 2183 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2184 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2185 /// mask. 2186 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2187 bool &Swap, bool IsLE) { 2188 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2189 2190 // Ensure each byte index of the double word is consecutive. 2191 if (!isNByteElemShuffleMask(N, 8, 1)) 2192 return false; 2193 2194 unsigned M0 = N->getMaskElt(0) / 8; 2195 unsigned M1 = N->getMaskElt(8) / 8; 2196 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2197 2198 // If both vector operands for the shuffle are the same vector, the mask will 2199 // contain only elements from the first one and the second one will be undef. 2200 if (N->getOperand(1).isUndef()) { 2201 if ((M0 | M1) < 2) { 2202 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2203 Swap = false; 2204 return true; 2205 } else 2206 return false; 2207 } 2208 2209 if (IsLE) { 2210 if (M0 > 1 && M1 < 2) { 2211 Swap = false; 2212 } else if (M0 < 2 && M1 > 1) { 2213 M0 = (M0 + 2) % 4; 2214 M1 = (M1 + 2) % 4; 2215 Swap = true; 2216 } else 2217 return false; 2218 2219 // Note: if control flow comes here that means Swap is already set above 2220 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2221 return true; 2222 } else { // BE 2223 if (M0 < 2 && M1 > 1) { 2224 Swap = false; 2225 } else if (M0 > 1 && M1 < 2) { 2226 M0 = (M0 + 2) % 4; 2227 M1 = (M1 + 2) % 4; 2228 Swap = true; 2229 } else 2230 return false; 2231 2232 // Note: if control flow comes here that means Swap is already set above 2233 DM = (M0 << 1) + (M1 & 1); 2234 return true; 2235 } 2236 } 2237 2238 2239 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2240 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2241 /// elements are counted from the left of the vector register). 2242 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2243 SelectionDAG &DAG) { 2244 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2245 assert(isSplatShuffleMask(SVOp, EltSize)); 2246 if (DAG.getDataLayout().isLittleEndian()) 2247 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2248 else 2249 return SVOp->getMaskElt(0) / EltSize; 2250 } 2251 2252 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2253 /// by using a vspltis[bhw] instruction of the specified element size, return 2254 /// the constant being splatted. The ByteSize field indicates the number of 2255 /// bytes of each element [124] -> [bhw]. 2256 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2257 SDValue OpVal(nullptr, 0); 2258 2259 // If ByteSize of the splat is bigger than the element size of the 2260 // build_vector, then we have a case where we are checking for a splat where 2261 // multiple elements of the buildvector are folded together into a single 2262 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2263 unsigned EltSize = 16/N->getNumOperands(); 2264 if (EltSize < ByteSize) { 2265 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2266 SDValue UniquedVals[4]; 2267 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2268 2269 // See if all of the elements in the buildvector agree across. 2270 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2271 if (N->getOperand(i).isUndef()) continue; 2272 // If the element isn't a constant, bail fully out. 2273 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2274 2275 if (!UniquedVals[i&(Multiple-1)].getNode()) 2276 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2277 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2278 return SDValue(); // no match. 2279 } 2280 2281 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2282 // either constant or undef values that are identical for each chunk. See 2283 // if these chunks can form into a larger vspltis*. 2284 2285 // Check to see if all of the leading entries are either 0 or -1. If 2286 // neither, then this won't fit into the immediate field. 2287 bool LeadingZero = true; 2288 bool LeadingOnes = true; 2289 for (unsigned i = 0; i != Multiple-1; ++i) { 2290 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2291 2292 LeadingZero &= isNullConstant(UniquedVals[i]); 2293 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2294 } 2295 // Finally, check the least significant entry. 2296 if (LeadingZero) { 2297 if (!UniquedVals[Multiple-1].getNode()) 2298 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2299 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2300 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2301 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2302 } 2303 if (LeadingOnes) { 2304 if (!UniquedVals[Multiple-1].getNode()) 2305 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2306 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2307 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2308 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2309 } 2310 2311 return SDValue(); 2312 } 2313 2314 // Check to see if this buildvec has a single non-undef value in its elements. 2315 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2316 if (N->getOperand(i).isUndef()) continue; 2317 if (!OpVal.getNode()) 2318 OpVal = N->getOperand(i); 2319 else if (OpVal != N->getOperand(i)) 2320 return SDValue(); 2321 } 2322 2323 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2324 2325 unsigned ValSizeInBytes = EltSize; 2326 uint64_t Value = 0; 2327 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2328 Value = CN->getZExtValue(); 2329 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2330 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2331 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2332 } 2333 2334 // If the splat value is larger than the element value, then we can never do 2335 // this splat. The only case that we could fit the replicated bits into our 2336 // immediate field for would be zero, and we prefer to use vxor for it. 2337 if (ValSizeInBytes < ByteSize) return SDValue(); 2338 2339 // If the element value is larger than the splat value, check if it consists 2340 // of a repeated bit pattern of size ByteSize. 2341 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2342 return SDValue(); 2343 2344 // Properly sign extend the value. 2345 int MaskVal = SignExtend32(Value, ByteSize * 8); 2346 2347 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2348 if (MaskVal == 0) return SDValue(); 2349 2350 // Finally, if this value fits in a 5 bit sext field, return it 2351 if (SignExtend32<5>(MaskVal) == MaskVal) 2352 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2353 return SDValue(); 2354 } 2355 2356 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2357 /// amount, otherwise return -1. 2358 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2359 EVT VT = N->getValueType(0); 2360 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2361 return -1; 2362 2363 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2364 2365 // Find the first non-undef value in the shuffle mask. 2366 unsigned i; 2367 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2368 /*search*/; 2369 2370 if (i == 4) return -1; // all undef. 2371 2372 // Otherwise, check to see if the rest of the elements are consecutively 2373 // numbered from this value. 2374 unsigned ShiftAmt = SVOp->getMaskElt(i); 2375 if (ShiftAmt < i) return -1; 2376 ShiftAmt -= i; 2377 2378 // Check the rest of the elements to see if they are consecutive. 2379 for (++i; i != 4; ++i) 2380 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2381 return -1; 2382 2383 return ShiftAmt; 2384 } 2385 2386 //===----------------------------------------------------------------------===// 2387 // Addressing Mode Selection 2388 //===----------------------------------------------------------------------===// 2389 2390 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2391 /// or 64-bit immediate, and if the value can be accurately represented as a 2392 /// sign extension from a 16-bit value. If so, this returns true and the 2393 /// immediate. 2394 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2395 if (!isa<ConstantSDNode>(N)) 2396 return false; 2397 2398 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2399 if (N->getValueType(0) == MVT::i32) 2400 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2401 else 2402 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2403 } 2404 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2405 return isIntS16Immediate(Op.getNode(), Imm); 2406 } 2407 2408 2409 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2410 /// be represented as an indexed [r+r] operation. 2411 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2412 SDValue &Index, 2413 SelectionDAG &DAG) const { 2414 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2415 UI != E; ++UI) { 2416 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2417 if (Memop->getMemoryVT() == MVT::f64) { 2418 Base = N.getOperand(0); 2419 Index = N.getOperand(1); 2420 return true; 2421 } 2422 } 2423 } 2424 return false; 2425 } 2426 2427 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2428 /// can be represented as an indexed [r+r] operation. Returns false if it 2429 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2430 /// non-zero and N can be represented by a base register plus a signed 16-bit 2431 /// displacement, make a more precise judgement by checking (displacement % \p 2432 /// EncodingAlignment). 2433 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2434 SDValue &Index, SelectionDAG &DAG, 2435 unsigned EncodingAlignment) const { 2436 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2437 // a [pc+imm]. 2438 if (SelectAddressPCRel(N, Base)) 2439 return false; 2440 2441 int16_t imm = 0; 2442 if (N.getOpcode() == ISD::ADD) { 2443 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2444 // SPE load/store can only handle 8-bit offsets. 2445 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2446 return true; 2447 if (isIntS16Immediate(N.getOperand(1), imm) && 2448 (!EncodingAlignment || !(imm % EncodingAlignment))) 2449 return false; // r+i 2450 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2451 return false; // r+i 2452 2453 Base = N.getOperand(0); 2454 Index = N.getOperand(1); 2455 return true; 2456 } else if (N.getOpcode() == ISD::OR) { 2457 if (isIntS16Immediate(N.getOperand(1), imm) && 2458 (!EncodingAlignment || !(imm % EncodingAlignment))) 2459 return false; // r+i can fold it if we can. 2460 2461 // If this is an or of disjoint bitfields, we can codegen this as an add 2462 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2463 // disjoint. 2464 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2465 2466 if (LHSKnown.Zero.getBoolValue()) { 2467 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2468 // If all of the bits are known zero on the LHS or RHS, the add won't 2469 // carry. 2470 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2471 Base = N.getOperand(0); 2472 Index = N.getOperand(1); 2473 return true; 2474 } 2475 } 2476 } 2477 2478 return false; 2479 } 2480 2481 // If we happen to be doing an i64 load or store into a stack slot that has 2482 // less than a 4-byte alignment, then the frame-index elimination may need to 2483 // use an indexed load or store instruction (because the offset may not be a 2484 // multiple of 4). The extra register needed to hold the offset comes from the 2485 // register scavenger, and it is possible that the scavenger will need to use 2486 // an emergency spill slot. As a result, we need to make sure that a spill slot 2487 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2488 // stack slot. 2489 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2490 // FIXME: This does not handle the LWA case. 2491 if (VT != MVT::i64) 2492 return; 2493 2494 // NOTE: We'll exclude negative FIs here, which come from argument 2495 // lowering, because there are no known test cases triggering this problem 2496 // using packed structures (or similar). We can remove this exclusion if 2497 // we find such a test case. The reason why this is so test-case driven is 2498 // because this entire 'fixup' is only to prevent crashes (from the 2499 // register scavenger) on not-really-valid inputs. For example, if we have: 2500 // %a = alloca i1 2501 // %b = bitcast i1* %a to i64* 2502 // store i64* a, i64 b 2503 // then the store should really be marked as 'align 1', but is not. If it 2504 // were marked as 'align 1' then the indexed form would have been 2505 // instruction-selected initially, and the problem this 'fixup' is preventing 2506 // won't happen regardless. 2507 if (FrameIdx < 0) 2508 return; 2509 2510 MachineFunction &MF = DAG.getMachineFunction(); 2511 MachineFrameInfo &MFI = MF.getFrameInfo(); 2512 2513 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2514 return; 2515 2516 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2517 FuncInfo->setHasNonRISpills(); 2518 } 2519 2520 /// Returns true if the address N can be represented by a base register plus 2521 /// a signed 16-bit displacement [r+imm], and if it is not better 2522 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2523 /// displacements that are multiples of that value. 2524 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2525 SDValue &Base, 2526 SelectionDAG &DAG, 2527 unsigned EncodingAlignment) const { 2528 // FIXME dl should come from parent load or store, not from address 2529 SDLoc dl(N); 2530 2531 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2532 // a [pc+imm]. 2533 if (SelectAddressPCRel(N, Base)) 2534 return false; 2535 2536 // If this can be more profitably realized as r+r, fail. 2537 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2538 return false; 2539 2540 if (N.getOpcode() == ISD::ADD) { 2541 int16_t imm = 0; 2542 if (isIntS16Immediate(N.getOperand(1), imm) && 2543 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2544 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2545 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2546 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2547 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2548 } else { 2549 Base = N.getOperand(0); 2550 } 2551 return true; // [r+i] 2552 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2553 // Match LOAD (ADD (X, Lo(G))). 2554 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2555 && "Cannot handle constant offsets yet!"); 2556 Disp = N.getOperand(1).getOperand(0); // The global address. 2557 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2558 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2559 Disp.getOpcode() == ISD::TargetConstantPool || 2560 Disp.getOpcode() == ISD::TargetJumpTable); 2561 Base = N.getOperand(0); 2562 return true; // [&g+r] 2563 } 2564 } else if (N.getOpcode() == ISD::OR) { 2565 int16_t imm = 0; 2566 if (isIntS16Immediate(N.getOperand(1), imm) && 2567 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2568 // If this is an or of disjoint bitfields, we can codegen this as an add 2569 // (for better address arithmetic) if the LHS and RHS of the OR are 2570 // provably disjoint. 2571 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2572 2573 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2574 // If all of the bits are known zero on the LHS or RHS, the add won't 2575 // carry. 2576 if (FrameIndexSDNode *FI = 2577 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2578 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2579 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2580 } else { 2581 Base = N.getOperand(0); 2582 } 2583 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2584 return true; 2585 } 2586 } 2587 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2588 // Loading from a constant address. 2589 2590 // If this address fits entirely in a 16-bit sext immediate field, codegen 2591 // this as "d, 0" 2592 int16_t Imm; 2593 if (isIntS16Immediate(CN, Imm) && 2594 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2595 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2596 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2597 CN->getValueType(0)); 2598 return true; 2599 } 2600 2601 // Handle 32-bit sext immediates with LIS + addr mode. 2602 if ((CN->getValueType(0) == MVT::i32 || 2603 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2604 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2605 int Addr = (int)CN->getZExtValue(); 2606 2607 // Otherwise, break this down into an LIS + disp. 2608 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2609 2610 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2611 MVT::i32); 2612 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2613 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2614 return true; 2615 } 2616 } 2617 2618 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2619 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2620 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2621 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2622 } else 2623 Base = N; 2624 return true; // [r+0] 2625 } 2626 2627 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2628 /// represented as an indexed [r+r] operation. 2629 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2630 SDValue &Index, 2631 SelectionDAG &DAG) const { 2632 // Check to see if we can easily represent this as an [r+r] address. This 2633 // will fail if it thinks that the address is more profitably represented as 2634 // reg+imm, e.g. where imm = 0. 2635 if (SelectAddressRegReg(N, Base, Index, DAG)) 2636 return true; 2637 2638 // If the address is the result of an add, we will utilize the fact that the 2639 // address calculation includes an implicit add. However, we can reduce 2640 // register pressure if we do not materialize a constant just for use as the 2641 // index register. We only get rid of the add if it is not an add of a 2642 // value and a 16-bit signed constant and both have a single use. 2643 int16_t imm = 0; 2644 if (N.getOpcode() == ISD::ADD && 2645 (!isIntS16Immediate(N.getOperand(1), imm) || 2646 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2647 Base = N.getOperand(0); 2648 Index = N.getOperand(1); 2649 return true; 2650 } 2651 2652 // Otherwise, do it the hard way, using R0 as the base register. 2653 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2654 N.getValueType()); 2655 Index = N; 2656 return true; 2657 } 2658 2659 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2660 Ty *PCRelCand = dyn_cast<Ty>(N); 2661 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2662 } 2663 2664 /// Returns true if this address is a PC Relative address. 2665 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2666 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2667 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2668 // This is a materialize PC Relative node. Always select this as PC Relative. 2669 Base = N; 2670 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2671 return true; 2672 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2673 isValidPCRelNode<GlobalAddressSDNode>(N) || 2674 isValidPCRelNode<JumpTableSDNode>(N) || 2675 isValidPCRelNode<BlockAddressSDNode>(N)) 2676 return true; 2677 return false; 2678 } 2679 2680 /// Returns true if we should use a direct load into vector instruction 2681 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2682 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2683 2684 // If there are any other uses other than scalar to vector, then we should 2685 // keep it as a scalar load -> direct move pattern to prevent multiple 2686 // loads. 2687 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2688 if (!LD) 2689 return false; 2690 2691 EVT MemVT = LD->getMemoryVT(); 2692 if (!MemVT.isSimple()) 2693 return false; 2694 switch(MemVT.getSimpleVT().SimpleTy) { 2695 case MVT::i64: 2696 break; 2697 case MVT::i32: 2698 if (!ST.hasP8Vector()) 2699 return false; 2700 break; 2701 case MVT::i16: 2702 case MVT::i8: 2703 if (!ST.hasP9Vector()) 2704 return false; 2705 break; 2706 default: 2707 return false; 2708 } 2709 2710 SDValue LoadedVal(N, 0); 2711 if (!LoadedVal.hasOneUse()) 2712 return false; 2713 2714 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2715 UI != UE; ++UI) 2716 if (UI.getUse().get().getResNo() == 0 && 2717 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2718 return false; 2719 2720 return true; 2721 } 2722 2723 /// getPreIndexedAddressParts - returns true by value, base pointer and 2724 /// offset pointer and addressing mode by reference if the node's address 2725 /// can be legally represented as pre-indexed load / store address. 2726 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2727 SDValue &Offset, 2728 ISD::MemIndexedMode &AM, 2729 SelectionDAG &DAG) const { 2730 if (DisablePPCPreinc) return false; 2731 2732 bool isLoad = true; 2733 SDValue Ptr; 2734 EVT VT; 2735 unsigned Alignment; 2736 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2737 Ptr = LD->getBasePtr(); 2738 VT = LD->getMemoryVT(); 2739 Alignment = LD->getAlignment(); 2740 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2741 Ptr = ST->getBasePtr(); 2742 VT = ST->getMemoryVT(); 2743 Alignment = ST->getAlignment(); 2744 isLoad = false; 2745 } else 2746 return false; 2747 2748 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2749 // instructions because we can fold these into a more efficient instruction 2750 // instead, (such as LXSD). 2751 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2752 return false; 2753 } 2754 2755 // PowerPC doesn't have preinc load/store instructions for vectors (except 2756 // for QPX, which does have preinc r+r forms). 2757 if (VT.isVector()) { 2758 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2759 return false; 2760 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2761 AM = ISD::PRE_INC; 2762 return true; 2763 } 2764 } 2765 2766 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2767 // Common code will reject creating a pre-inc form if the base pointer 2768 // is a frame index, or if N is a store and the base pointer is either 2769 // the same as or a predecessor of the value being stored. Check for 2770 // those situations here, and try with swapped Base/Offset instead. 2771 bool Swap = false; 2772 2773 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2774 Swap = true; 2775 else if (!isLoad) { 2776 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2777 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2778 Swap = true; 2779 } 2780 2781 if (Swap) 2782 std::swap(Base, Offset); 2783 2784 AM = ISD::PRE_INC; 2785 return true; 2786 } 2787 2788 // LDU/STU can only handle immediates that are a multiple of 4. 2789 if (VT != MVT::i64) { 2790 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2791 return false; 2792 } else { 2793 // LDU/STU need an address with at least 4-byte alignment. 2794 if (Alignment < 4) 2795 return false; 2796 2797 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2798 return false; 2799 } 2800 2801 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2802 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2803 // sext i32 to i64 when addr mode is r+i. 2804 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2805 LD->getExtensionType() == ISD::SEXTLOAD && 2806 isa<ConstantSDNode>(Offset)) 2807 return false; 2808 } 2809 2810 AM = ISD::PRE_INC; 2811 return true; 2812 } 2813 2814 //===----------------------------------------------------------------------===// 2815 // LowerOperation implementation 2816 //===----------------------------------------------------------------------===// 2817 2818 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2819 /// and LoOpFlags to the target MO flags. 2820 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2821 unsigned &HiOpFlags, unsigned &LoOpFlags, 2822 const GlobalValue *GV = nullptr) { 2823 HiOpFlags = PPCII::MO_HA; 2824 LoOpFlags = PPCII::MO_LO; 2825 2826 // Don't use the pic base if not in PIC relocation model. 2827 if (IsPIC) { 2828 HiOpFlags |= PPCII::MO_PIC_FLAG; 2829 LoOpFlags |= PPCII::MO_PIC_FLAG; 2830 } 2831 } 2832 2833 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2834 SelectionDAG &DAG) { 2835 SDLoc DL(HiPart); 2836 EVT PtrVT = HiPart.getValueType(); 2837 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2838 2839 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2840 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2841 2842 // With PIC, the first instruction is actually "GR+hi(&G)". 2843 if (isPIC) 2844 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2845 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2846 2847 // Generate non-pic code that has direct accesses to the constant pool. 2848 // The address of the global is just (hi(&g)+lo(&g)). 2849 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2850 } 2851 2852 static void setUsesTOCBasePtr(MachineFunction &MF) { 2853 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2854 FuncInfo->setUsesTOCBasePtr(); 2855 } 2856 2857 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2858 setUsesTOCBasePtr(DAG.getMachineFunction()); 2859 } 2860 2861 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2862 SDValue GA) const { 2863 const bool Is64Bit = Subtarget.isPPC64(); 2864 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2865 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2866 : Subtarget.isAIXABI() 2867 ? DAG.getRegister(PPC::R2, VT) 2868 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2869 SDValue Ops[] = { GA, Reg }; 2870 return DAG.getMemIntrinsicNode( 2871 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2872 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2873 MachineMemOperand::MOLoad); 2874 } 2875 2876 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2877 SelectionDAG &DAG) const { 2878 EVT PtrVT = Op.getValueType(); 2879 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2880 const Constant *C = CP->getConstVal(); 2881 2882 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2883 // The actual address of the GlobalValue is stored in the TOC. 2884 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2885 if (Subtarget.isUsingPCRelativeCalls()) { 2886 SDLoc DL(CP); 2887 EVT Ty = getPointerTy(DAG.getDataLayout()); 2888 SDValue ConstPool = DAG.getTargetConstantPool( 2889 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2890 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2891 } 2892 setUsesTOCBasePtr(DAG); 2893 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2894 return getTOCEntry(DAG, SDLoc(CP), GA); 2895 } 2896 2897 unsigned MOHiFlag, MOLoFlag; 2898 bool IsPIC = isPositionIndependent(); 2899 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2900 2901 if (IsPIC && Subtarget.isSVR4ABI()) { 2902 SDValue GA = 2903 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2904 return getTOCEntry(DAG, SDLoc(CP), GA); 2905 } 2906 2907 SDValue CPIHi = 2908 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2909 SDValue CPILo = 2910 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2911 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2912 } 2913 2914 // For 64-bit PowerPC, prefer the more compact relative encodings. 2915 // This trades 32 bits per jump table entry for one or two instructions 2916 // on the jump site. 2917 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2918 if (isJumpTableRelative()) 2919 return MachineJumpTableInfo::EK_LabelDifference32; 2920 2921 return TargetLowering::getJumpTableEncoding(); 2922 } 2923 2924 bool PPCTargetLowering::isJumpTableRelative() const { 2925 if (UseAbsoluteJumpTables) 2926 return false; 2927 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2928 return true; 2929 return TargetLowering::isJumpTableRelative(); 2930 } 2931 2932 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2933 SelectionDAG &DAG) const { 2934 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2935 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2936 2937 switch (getTargetMachine().getCodeModel()) { 2938 case CodeModel::Small: 2939 case CodeModel::Medium: 2940 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2941 default: 2942 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2943 getPointerTy(DAG.getDataLayout())); 2944 } 2945 } 2946 2947 const MCExpr * 2948 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2949 unsigned JTI, 2950 MCContext &Ctx) const { 2951 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2952 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2953 2954 switch (getTargetMachine().getCodeModel()) { 2955 case CodeModel::Small: 2956 case CodeModel::Medium: 2957 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2958 default: 2959 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2960 } 2961 } 2962 2963 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2964 EVT PtrVT = Op.getValueType(); 2965 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2966 2967 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2968 if (Subtarget.isUsingPCRelativeCalls()) { 2969 SDLoc DL(JT); 2970 EVT Ty = getPointerTy(DAG.getDataLayout()); 2971 SDValue GA = 2972 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2973 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2974 return MatAddr; 2975 } 2976 2977 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2978 // The actual address of the GlobalValue is stored in the TOC. 2979 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2980 setUsesTOCBasePtr(DAG); 2981 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2982 return getTOCEntry(DAG, SDLoc(JT), GA); 2983 } 2984 2985 unsigned MOHiFlag, MOLoFlag; 2986 bool IsPIC = isPositionIndependent(); 2987 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2988 2989 if (IsPIC && Subtarget.isSVR4ABI()) { 2990 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2991 PPCII::MO_PIC_FLAG); 2992 return getTOCEntry(DAG, SDLoc(GA), GA); 2993 } 2994 2995 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2996 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2997 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2998 } 2999 3000 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3001 SelectionDAG &DAG) const { 3002 EVT PtrVT = Op.getValueType(); 3003 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3004 const BlockAddress *BA = BASDN->getBlockAddress(); 3005 3006 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3007 if (Subtarget.isUsingPCRelativeCalls()) { 3008 SDLoc DL(BASDN); 3009 EVT Ty = getPointerTy(DAG.getDataLayout()); 3010 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3011 PPCII::MO_PCREL_FLAG); 3012 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3013 return MatAddr; 3014 } 3015 3016 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3017 // The actual BlockAddress is stored in the TOC. 3018 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3019 setUsesTOCBasePtr(DAG); 3020 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3021 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3022 } 3023 3024 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3025 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3026 return getTOCEntry( 3027 DAG, SDLoc(BASDN), 3028 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3029 3030 unsigned MOHiFlag, MOLoFlag; 3031 bool IsPIC = isPositionIndependent(); 3032 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3033 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3034 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3035 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3036 } 3037 3038 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3039 SelectionDAG &DAG) const { 3040 // FIXME: TLS addresses currently use medium model code sequences, 3041 // which is the most useful form. Eventually support for small and 3042 // large models could be added if users need it, at the cost of 3043 // additional complexity. 3044 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3045 if (DAG.getTarget().useEmulatedTLS()) 3046 return LowerToTLSEmulatedModel(GA, DAG); 3047 3048 SDLoc dl(GA); 3049 const GlobalValue *GV = GA->getGlobal(); 3050 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3051 bool is64bit = Subtarget.isPPC64(); 3052 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3053 PICLevel::Level picLevel = M->getPICLevel(); 3054 3055 const TargetMachine &TM = getTargetMachine(); 3056 TLSModel::Model Model = TM.getTLSModel(GV); 3057 3058 if (Model == TLSModel::LocalExec) { 3059 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3060 PPCII::MO_TPREL_HA); 3061 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3062 PPCII::MO_TPREL_LO); 3063 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3064 : DAG.getRegister(PPC::R2, MVT::i32); 3065 3066 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3067 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3068 } 3069 3070 if (Model == TLSModel::InitialExec) { 3071 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3072 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3073 PPCII::MO_TLS); 3074 SDValue GOTPtr; 3075 if (is64bit) { 3076 setUsesTOCBasePtr(DAG); 3077 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3078 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3079 PtrVT, GOTReg, TGA); 3080 } else { 3081 if (!TM.isPositionIndependent()) 3082 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3083 else if (picLevel == PICLevel::SmallPIC) 3084 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3085 else 3086 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3087 } 3088 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3089 PtrVT, TGA, GOTPtr); 3090 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3091 } 3092 3093 if (Model == TLSModel::GeneralDynamic) { 3094 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3095 SDValue GOTPtr; 3096 if (is64bit) { 3097 setUsesTOCBasePtr(DAG); 3098 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3099 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3100 GOTReg, TGA); 3101 } else { 3102 if (picLevel == PICLevel::SmallPIC) 3103 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3104 else 3105 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3106 } 3107 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3108 GOTPtr, TGA, TGA); 3109 } 3110 3111 if (Model == TLSModel::LocalDynamic) { 3112 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3113 SDValue GOTPtr; 3114 if (is64bit) { 3115 setUsesTOCBasePtr(DAG); 3116 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3117 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3118 GOTReg, TGA); 3119 } else { 3120 if (picLevel == PICLevel::SmallPIC) 3121 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3122 else 3123 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3124 } 3125 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3126 PtrVT, GOTPtr, TGA, TGA); 3127 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3128 PtrVT, TLSAddr, TGA); 3129 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3130 } 3131 3132 llvm_unreachable("Unknown TLS model!"); 3133 } 3134 3135 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3136 SelectionDAG &DAG) const { 3137 EVT PtrVT = Op.getValueType(); 3138 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3139 SDLoc DL(GSDN); 3140 const GlobalValue *GV = GSDN->getGlobal(); 3141 3142 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3143 // The actual address of the GlobalValue is stored in the TOC. 3144 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3145 if (Subtarget.isUsingPCRelativeCalls()) { 3146 EVT Ty = getPointerTy(DAG.getDataLayout()); 3147 if (isAccessedAsGotIndirect(Op)) { 3148 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3149 PPCII::MO_PCREL_FLAG | 3150 PPCII::MO_GOT_FLAG); 3151 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3152 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3153 MachinePointerInfo()); 3154 return Load; 3155 } else { 3156 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3157 PPCII::MO_PCREL_FLAG); 3158 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3159 } 3160 } 3161 setUsesTOCBasePtr(DAG); 3162 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3163 return getTOCEntry(DAG, DL, GA); 3164 } 3165 3166 unsigned MOHiFlag, MOLoFlag; 3167 bool IsPIC = isPositionIndependent(); 3168 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3169 3170 if (IsPIC && Subtarget.isSVR4ABI()) { 3171 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3172 GSDN->getOffset(), 3173 PPCII::MO_PIC_FLAG); 3174 return getTOCEntry(DAG, DL, GA); 3175 } 3176 3177 SDValue GAHi = 3178 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3179 SDValue GALo = 3180 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3181 3182 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3183 } 3184 3185 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3186 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3187 SDLoc dl(Op); 3188 3189 if (Op.getValueType() == MVT::v2i64) { 3190 // When the operands themselves are v2i64 values, we need to do something 3191 // special because VSX has no underlying comparison operations for these. 3192 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3193 // Equality can be handled by casting to the legal type for Altivec 3194 // comparisons, everything else needs to be expanded. 3195 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3196 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3197 DAG.getSetCC(dl, MVT::v4i32, 3198 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3199 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3200 CC)); 3201 } 3202 3203 return SDValue(); 3204 } 3205 3206 // We handle most of these in the usual way. 3207 return Op; 3208 } 3209 3210 // If we're comparing for equality to zero, expose the fact that this is 3211 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3212 // fold the new nodes. 3213 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3214 return V; 3215 3216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3217 // Leave comparisons against 0 and -1 alone for now, since they're usually 3218 // optimized. FIXME: revisit this when we can custom lower all setcc 3219 // optimizations. 3220 if (C->isAllOnesValue() || C->isNullValue()) 3221 return SDValue(); 3222 } 3223 3224 // If we have an integer seteq/setne, turn it into a compare against zero 3225 // by xor'ing the rhs with the lhs, which is faster than setting a 3226 // condition register, reading it back out, and masking the correct bit. The 3227 // normal approach here uses sub to do this instead of xor. Using xor exposes 3228 // the result to other bit-twiddling opportunities. 3229 EVT LHSVT = Op.getOperand(0).getValueType(); 3230 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3231 EVT VT = Op.getValueType(); 3232 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3233 Op.getOperand(1)); 3234 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3235 } 3236 return SDValue(); 3237 } 3238 3239 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3240 SDNode *Node = Op.getNode(); 3241 EVT VT = Node->getValueType(0); 3242 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3243 SDValue InChain = Node->getOperand(0); 3244 SDValue VAListPtr = Node->getOperand(1); 3245 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3246 SDLoc dl(Node); 3247 3248 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3249 3250 // gpr_index 3251 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3252 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3253 InChain = GprIndex.getValue(1); 3254 3255 if (VT == MVT::i64) { 3256 // Check if GprIndex is even 3257 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3258 DAG.getConstant(1, dl, MVT::i32)); 3259 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3260 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3261 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3262 DAG.getConstant(1, dl, MVT::i32)); 3263 // Align GprIndex to be even if it isn't 3264 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3265 GprIndex); 3266 } 3267 3268 // fpr index is 1 byte after gpr 3269 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3270 DAG.getConstant(1, dl, MVT::i32)); 3271 3272 // fpr 3273 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3274 FprPtr, MachinePointerInfo(SV), MVT::i8); 3275 InChain = FprIndex.getValue(1); 3276 3277 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3278 DAG.getConstant(8, dl, MVT::i32)); 3279 3280 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3281 DAG.getConstant(4, dl, MVT::i32)); 3282 3283 // areas 3284 SDValue OverflowArea = 3285 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3286 InChain = OverflowArea.getValue(1); 3287 3288 SDValue RegSaveArea = 3289 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3290 InChain = RegSaveArea.getValue(1); 3291 3292 // select overflow_area if index > 8 3293 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3294 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3295 3296 // adjustment constant gpr_index * 4/8 3297 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3298 VT.isInteger() ? GprIndex : FprIndex, 3299 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3300 MVT::i32)); 3301 3302 // OurReg = RegSaveArea + RegConstant 3303 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3304 RegConstant); 3305 3306 // Floating types are 32 bytes into RegSaveArea 3307 if (VT.isFloatingPoint()) 3308 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3309 DAG.getConstant(32, dl, MVT::i32)); 3310 3311 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3312 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3313 VT.isInteger() ? GprIndex : FprIndex, 3314 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3315 MVT::i32)); 3316 3317 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3318 VT.isInteger() ? VAListPtr : FprPtr, 3319 MachinePointerInfo(SV), MVT::i8); 3320 3321 // determine if we should load from reg_save_area or overflow_area 3322 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3323 3324 // increase overflow_area by 4/8 if gpr/fpr > 8 3325 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3326 DAG.getConstant(VT.isInteger() ? 4 : 8, 3327 dl, MVT::i32)); 3328 3329 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3330 OverflowAreaPlusN); 3331 3332 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3333 MachinePointerInfo(), MVT::i32); 3334 3335 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3336 } 3337 3338 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3339 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3340 3341 // We have to copy the entire va_list struct: 3342 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3343 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3344 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3345 false, true, false, MachinePointerInfo(), 3346 MachinePointerInfo()); 3347 } 3348 3349 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3350 SelectionDAG &DAG) const { 3351 if (Subtarget.isAIXABI()) 3352 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3353 3354 return Op.getOperand(0); 3355 } 3356 3357 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3358 SelectionDAG &DAG) const { 3359 if (Subtarget.isAIXABI()) 3360 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3361 3362 SDValue Chain = Op.getOperand(0); 3363 SDValue Trmp = Op.getOperand(1); // trampoline 3364 SDValue FPtr = Op.getOperand(2); // nested function 3365 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3366 SDLoc dl(Op); 3367 3368 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3369 bool isPPC64 = (PtrVT == MVT::i64); 3370 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3371 3372 TargetLowering::ArgListTy Args; 3373 TargetLowering::ArgListEntry Entry; 3374 3375 Entry.Ty = IntPtrTy; 3376 Entry.Node = Trmp; Args.push_back(Entry); 3377 3378 // TrampSize == (isPPC64 ? 48 : 40); 3379 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3380 isPPC64 ? MVT::i64 : MVT::i32); 3381 Args.push_back(Entry); 3382 3383 Entry.Node = FPtr; Args.push_back(Entry); 3384 Entry.Node = Nest; Args.push_back(Entry); 3385 3386 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3387 TargetLowering::CallLoweringInfo CLI(DAG); 3388 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3389 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3390 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3391 3392 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3393 return CallResult.second; 3394 } 3395 3396 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3397 MachineFunction &MF = DAG.getMachineFunction(); 3398 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3399 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3400 3401 SDLoc dl(Op); 3402 3403 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3404 // vastart just stores the address of the VarArgsFrameIndex slot into the 3405 // memory location argument. 3406 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3407 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3408 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3409 MachinePointerInfo(SV)); 3410 } 3411 3412 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3413 // We suppose the given va_list is already allocated. 3414 // 3415 // typedef struct { 3416 // char gpr; /* index into the array of 8 GPRs 3417 // * stored in the register save area 3418 // * gpr=0 corresponds to r3, 3419 // * gpr=1 to r4, etc. 3420 // */ 3421 // char fpr; /* index into the array of 8 FPRs 3422 // * stored in the register save area 3423 // * fpr=0 corresponds to f1, 3424 // * fpr=1 to f2, etc. 3425 // */ 3426 // char *overflow_arg_area; 3427 // /* location on stack that holds 3428 // * the next overflow argument 3429 // */ 3430 // char *reg_save_area; 3431 // /* where r3:r10 and f1:f8 (if saved) 3432 // * are stored 3433 // */ 3434 // } va_list[1]; 3435 3436 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3437 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3438 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3439 PtrVT); 3440 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3441 PtrVT); 3442 3443 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3444 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3445 3446 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3447 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3448 3449 uint64_t FPROffset = 1; 3450 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3451 3452 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3453 3454 // Store first byte : number of int regs 3455 SDValue firstStore = 3456 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3457 MachinePointerInfo(SV), MVT::i8); 3458 uint64_t nextOffset = FPROffset; 3459 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3460 ConstFPROffset); 3461 3462 // Store second byte : number of float regs 3463 SDValue secondStore = 3464 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3465 MachinePointerInfo(SV, nextOffset), MVT::i8); 3466 nextOffset += StackOffset; 3467 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3468 3469 // Store second word : arguments given on stack 3470 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3471 MachinePointerInfo(SV, nextOffset)); 3472 nextOffset += FrameOffset; 3473 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3474 3475 // Store third word : arguments given in registers 3476 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3477 MachinePointerInfo(SV, nextOffset)); 3478 } 3479 3480 /// FPR - The set of FP registers that should be allocated for arguments 3481 /// on Darwin and AIX. 3482 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3483 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3484 PPC::F11, PPC::F12, PPC::F13}; 3485 3486 /// QFPR - The set of QPX registers that should be allocated for arguments. 3487 static const MCPhysReg QFPR[] = { 3488 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3489 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3490 3491 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3492 /// the stack. 3493 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3494 unsigned PtrByteSize) { 3495 unsigned ArgSize = ArgVT.getStoreSize(); 3496 if (Flags.isByVal()) 3497 ArgSize = Flags.getByValSize(); 3498 3499 // Round up to multiples of the pointer size, except for array members, 3500 // which are always packed. 3501 if (!Flags.isInConsecutiveRegs()) 3502 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3503 3504 return ArgSize; 3505 } 3506 3507 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3508 /// on the stack. 3509 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3510 ISD::ArgFlagsTy Flags, 3511 unsigned PtrByteSize) { 3512 Align Alignment(PtrByteSize); 3513 3514 // Altivec parameters are padded to a 16 byte boundary. 3515 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3516 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3517 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3518 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3519 Alignment = Align(16); 3520 // QPX vector types stored in double-precision are padded to a 32 byte 3521 // boundary. 3522 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3523 Alignment = Align(32); 3524 3525 // ByVal parameters are aligned as requested. 3526 if (Flags.isByVal()) { 3527 auto BVAlign = Flags.getNonZeroByValAlign(); 3528 if (BVAlign > PtrByteSize) { 3529 if (BVAlign.value() % PtrByteSize != 0) 3530 llvm_unreachable( 3531 "ByVal alignment is not a multiple of the pointer size"); 3532 3533 Alignment = BVAlign; 3534 } 3535 } 3536 3537 // Array members are always packed to their original alignment. 3538 if (Flags.isInConsecutiveRegs()) { 3539 // If the array member was split into multiple registers, the first 3540 // needs to be aligned to the size of the full type. (Except for 3541 // ppcf128, which is only aligned as its f64 components.) 3542 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3543 Alignment = Align(OrigVT.getStoreSize()); 3544 else 3545 Alignment = Align(ArgVT.getStoreSize()); 3546 } 3547 3548 return Alignment; 3549 } 3550 3551 /// CalculateStackSlotUsed - Return whether this argument will use its 3552 /// stack slot (instead of being passed in registers). ArgOffset, 3553 /// AvailableFPRs, and AvailableVRs must hold the current argument 3554 /// position, and will be updated to account for this argument. 3555 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3556 ISD::ArgFlagsTy Flags, 3557 unsigned PtrByteSize, 3558 unsigned LinkageSize, 3559 unsigned ParamAreaSize, 3560 unsigned &ArgOffset, 3561 unsigned &AvailableFPRs, 3562 unsigned &AvailableVRs, bool HasQPX) { 3563 bool UseMemory = false; 3564 3565 // Respect alignment of argument on the stack. 3566 Align Alignment = 3567 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3568 ArgOffset = alignTo(ArgOffset, Alignment); 3569 // If there's no space left in the argument save area, we must 3570 // use memory (this check also catches zero-sized arguments). 3571 if (ArgOffset >= LinkageSize + ParamAreaSize) 3572 UseMemory = true; 3573 3574 // Allocate argument on the stack. 3575 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3576 if (Flags.isInConsecutiveRegsLast()) 3577 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3578 // If we overran the argument save area, we must use memory 3579 // (this check catches arguments passed partially in memory) 3580 if (ArgOffset > LinkageSize + ParamAreaSize) 3581 UseMemory = true; 3582 3583 // However, if the argument is actually passed in an FPR or a VR, 3584 // we don't use memory after all. 3585 if (!Flags.isByVal()) { 3586 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3587 // QPX registers overlap with the scalar FP registers. 3588 (HasQPX && (ArgVT == MVT::v4f32 || 3589 ArgVT == MVT::v4f64 || 3590 ArgVT == MVT::v4i1))) 3591 if (AvailableFPRs > 0) { 3592 --AvailableFPRs; 3593 return false; 3594 } 3595 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3596 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3597 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3598 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3599 if (AvailableVRs > 0) { 3600 --AvailableVRs; 3601 return false; 3602 } 3603 } 3604 3605 return UseMemory; 3606 } 3607 3608 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3609 /// ensure minimum alignment required for target. 3610 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3611 unsigned NumBytes) { 3612 return alignTo(NumBytes, Lowering->getStackAlign()); 3613 } 3614 3615 SDValue PPCTargetLowering::LowerFormalArguments( 3616 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3617 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3618 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3619 if (Subtarget.isAIXABI()) 3620 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3621 InVals); 3622 if (Subtarget.is64BitELFABI()) 3623 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3624 InVals); 3625 if (Subtarget.is32BitELFABI()) 3626 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3627 InVals); 3628 3629 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3630 InVals); 3631 } 3632 3633 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3634 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3635 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3636 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3637 3638 // 32-bit SVR4 ABI Stack Frame Layout: 3639 // +-----------------------------------+ 3640 // +--> | Back chain | 3641 // | +-----------------------------------+ 3642 // | | Floating-point register save area | 3643 // | +-----------------------------------+ 3644 // | | General register save area | 3645 // | +-----------------------------------+ 3646 // | | CR save word | 3647 // | +-----------------------------------+ 3648 // | | VRSAVE save word | 3649 // | +-----------------------------------+ 3650 // | | Alignment padding | 3651 // | +-----------------------------------+ 3652 // | | Vector register save area | 3653 // | +-----------------------------------+ 3654 // | | Local variable space | 3655 // | +-----------------------------------+ 3656 // | | Parameter list area | 3657 // | +-----------------------------------+ 3658 // | | LR save word | 3659 // | +-----------------------------------+ 3660 // SP--> +--- | Back chain | 3661 // +-----------------------------------+ 3662 // 3663 // Specifications: 3664 // System V Application Binary Interface PowerPC Processor Supplement 3665 // AltiVec Technology Programming Interface Manual 3666 3667 MachineFunction &MF = DAG.getMachineFunction(); 3668 MachineFrameInfo &MFI = MF.getFrameInfo(); 3669 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3670 3671 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3672 // Potential tail calls could cause overwriting of argument stack slots. 3673 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3674 (CallConv == CallingConv::Fast)); 3675 const Align PtrAlign(4); 3676 3677 // Assign locations to all of the incoming arguments. 3678 SmallVector<CCValAssign, 16> ArgLocs; 3679 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3680 *DAG.getContext()); 3681 3682 // Reserve space for the linkage area on the stack. 3683 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3684 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3685 if (useSoftFloat()) 3686 CCInfo.PreAnalyzeFormalArguments(Ins); 3687 3688 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3689 CCInfo.clearWasPPCF128(); 3690 3691 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3692 CCValAssign &VA = ArgLocs[i]; 3693 3694 // Arguments stored in registers. 3695 if (VA.isRegLoc()) { 3696 const TargetRegisterClass *RC; 3697 EVT ValVT = VA.getValVT(); 3698 3699 switch (ValVT.getSimpleVT().SimpleTy) { 3700 default: 3701 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3702 case MVT::i1: 3703 case MVT::i32: 3704 RC = &PPC::GPRCRegClass; 3705 break; 3706 case MVT::f32: 3707 if (Subtarget.hasP8Vector()) 3708 RC = &PPC::VSSRCRegClass; 3709 else if (Subtarget.hasSPE()) 3710 RC = &PPC::GPRCRegClass; 3711 else 3712 RC = &PPC::F4RCRegClass; 3713 break; 3714 case MVT::f64: 3715 if (Subtarget.hasVSX()) 3716 RC = &PPC::VSFRCRegClass; 3717 else if (Subtarget.hasSPE()) 3718 // SPE passes doubles in GPR pairs. 3719 RC = &PPC::GPRCRegClass; 3720 else 3721 RC = &PPC::F8RCRegClass; 3722 break; 3723 case MVT::v16i8: 3724 case MVT::v8i16: 3725 case MVT::v4i32: 3726 RC = &PPC::VRRCRegClass; 3727 break; 3728 case MVT::v4f32: 3729 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3730 break; 3731 case MVT::v2f64: 3732 case MVT::v2i64: 3733 RC = &PPC::VRRCRegClass; 3734 break; 3735 case MVT::v4f64: 3736 RC = &PPC::QFRCRegClass; 3737 break; 3738 case MVT::v4i1: 3739 RC = &PPC::QBRCRegClass; 3740 break; 3741 } 3742 3743 SDValue ArgValue; 3744 // Transform the arguments stored in physical registers into 3745 // virtual ones. 3746 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3747 assert(i + 1 < e && "No second half of double precision argument"); 3748 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3749 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3750 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3751 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3752 if (!Subtarget.isLittleEndian()) 3753 std::swap (ArgValueLo, ArgValueHi); 3754 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3755 ArgValueHi); 3756 } else { 3757 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3758 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3759 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3760 if (ValVT == MVT::i1) 3761 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3762 } 3763 3764 InVals.push_back(ArgValue); 3765 } else { 3766 // Argument stored in memory. 3767 assert(VA.isMemLoc()); 3768 3769 // Get the extended size of the argument type in stack 3770 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3771 // Get the actual size of the argument type 3772 unsigned ObjSize = VA.getValVT().getStoreSize(); 3773 unsigned ArgOffset = VA.getLocMemOffset(); 3774 // Stack objects in PPC32 are right justified. 3775 ArgOffset += ArgSize - ObjSize; 3776 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3777 3778 // Create load nodes to retrieve arguments from the stack. 3779 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3780 InVals.push_back( 3781 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3782 } 3783 } 3784 3785 // Assign locations to all of the incoming aggregate by value arguments. 3786 // Aggregates passed by value are stored in the local variable space of the 3787 // caller's stack frame, right above the parameter list area. 3788 SmallVector<CCValAssign, 16> ByValArgLocs; 3789 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3790 ByValArgLocs, *DAG.getContext()); 3791 3792 // Reserve stack space for the allocations in CCInfo. 3793 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3794 3795 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3796 3797 // Area that is at least reserved in the caller of this function. 3798 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3799 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3800 3801 // Set the size that is at least reserved in caller of this function. Tail 3802 // call optimized function's reserved stack space needs to be aligned so that 3803 // taking the difference between two stack areas will result in an aligned 3804 // stack. 3805 MinReservedArea = 3806 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3807 FuncInfo->setMinReservedArea(MinReservedArea); 3808 3809 SmallVector<SDValue, 8> MemOps; 3810 3811 // If the function takes variable number of arguments, make a frame index for 3812 // the start of the first vararg value... for expansion of llvm.va_start. 3813 if (isVarArg) { 3814 static const MCPhysReg GPArgRegs[] = { 3815 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3816 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3817 }; 3818 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3819 3820 static const MCPhysReg FPArgRegs[] = { 3821 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3822 PPC::F8 3823 }; 3824 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3825 3826 if (useSoftFloat() || hasSPE()) 3827 NumFPArgRegs = 0; 3828 3829 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3830 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3831 3832 // Make room for NumGPArgRegs and NumFPArgRegs. 3833 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3834 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3835 3836 FuncInfo->setVarArgsStackOffset( 3837 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3838 CCInfo.getNextStackOffset(), true)); 3839 3840 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3841 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3842 3843 // The fixed integer arguments of a variadic function are stored to the 3844 // VarArgsFrameIndex on the stack so that they may be loaded by 3845 // dereferencing the result of va_next. 3846 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3847 // Get an existing live-in vreg, or add a new one. 3848 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3849 if (!VReg) 3850 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3851 3852 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3853 SDValue Store = 3854 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3855 MemOps.push_back(Store); 3856 // Increment the address by four for the next argument to store 3857 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3858 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3859 } 3860 3861 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3862 // is set. 3863 // The double arguments are stored to the VarArgsFrameIndex 3864 // on the stack. 3865 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3866 // Get an existing live-in vreg, or add a new one. 3867 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3868 if (!VReg) 3869 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3870 3871 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3872 SDValue Store = 3873 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3874 MemOps.push_back(Store); 3875 // Increment the address by eight for the next argument to store 3876 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3877 PtrVT); 3878 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3879 } 3880 } 3881 3882 if (!MemOps.empty()) 3883 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3884 3885 return Chain; 3886 } 3887 3888 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3889 // value to MVT::i64 and then truncate to the correct register size. 3890 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3891 EVT ObjectVT, SelectionDAG &DAG, 3892 SDValue ArgVal, 3893 const SDLoc &dl) const { 3894 if (Flags.isSExt()) 3895 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3896 DAG.getValueType(ObjectVT)); 3897 else if (Flags.isZExt()) 3898 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3899 DAG.getValueType(ObjectVT)); 3900 3901 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3902 } 3903 3904 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3905 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3906 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3907 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3908 // TODO: add description of PPC stack frame format, or at least some docs. 3909 // 3910 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3911 bool isLittleEndian = Subtarget.isLittleEndian(); 3912 MachineFunction &MF = DAG.getMachineFunction(); 3913 MachineFrameInfo &MFI = MF.getFrameInfo(); 3914 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3915 3916 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3917 "fastcc not supported on varargs functions"); 3918 3919 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3920 // Potential tail calls could cause overwriting of argument stack slots. 3921 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3922 (CallConv == CallingConv::Fast)); 3923 unsigned PtrByteSize = 8; 3924 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3925 3926 static const MCPhysReg GPR[] = { 3927 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3928 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3929 }; 3930 static const MCPhysReg VR[] = { 3931 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3932 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3933 }; 3934 3935 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3936 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3937 const unsigned Num_VR_Regs = array_lengthof(VR); 3938 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3939 3940 // Do a first pass over the arguments to determine whether the ABI 3941 // guarantees that our caller has allocated the parameter save area 3942 // on its stack frame. In the ELFv1 ABI, this is always the case; 3943 // in the ELFv2 ABI, it is true if this is a vararg function or if 3944 // any parameter is located in a stack slot. 3945 3946 bool HasParameterArea = !isELFv2ABI || isVarArg; 3947 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3948 unsigned NumBytes = LinkageSize; 3949 unsigned AvailableFPRs = Num_FPR_Regs; 3950 unsigned AvailableVRs = Num_VR_Regs; 3951 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3952 if (Ins[i].Flags.isNest()) 3953 continue; 3954 3955 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3956 PtrByteSize, LinkageSize, ParamAreaSize, 3957 NumBytes, AvailableFPRs, AvailableVRs, 3958 Subtarget.hasQPX())) 3959 HasParameterArea = true; 3960 } 3961 3962 // Add DAG nodes to load the arguments or copy them out of registers. On 3963 // entry to a function on PPC, the arguments start after the linkage area, 3964 // although the first ones are often in registers. 3965 3966 unsigned ArgOffset = LinkageSize; 3967 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3968 unsigned &QFPR_idx = FPR_idx; 3969 SmallVector<SDValue, 8> MemOps; 3970 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3971 unsigned CurArgIdx = 0; 3972 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3973 SDValue ArgVal; 3974 bool needsLoad = false; 3975 EVT ObjectVT = Ins[ArgNo].VT; 3976 EVT OrigVT = Ins[ArgNo].ArgVT; 3977 unsigned ObjSize = ObjectVT.getStoreSize(); 3978 unsigned ArgSize = ObjSize; 3979 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3980 if (Ins[ArgNo].isOrigArg()) { 3981 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3982 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3983 } 3984 // We re-align the argument offset for each argument, except when using the 3985 // fast calling convention, when we need to make sure we do that only when 3986 // we'll actually use a stack slot. 3987 unsigned CurArgOffset; 3988 Align Alignment; 3989 auto ComputeArgOffset = [&]() { 3990 /* Respect alignment of argument on the stack. */ 3991 Alignment = 3992 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3993 ArgOffset = alignTo(ArgOffset, Alignment); 3994 CurArgOffset = ArgOffset; 3995 }; 3996 3997 if (CallConv != CallingConv::Fast) { 3998 ComputeArgOffset(); 3999 4000 /* Compute GPR index associated with argument offset. */ 4001 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4002 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4003 } 4004 4005 // FIXME the codegen can be much improved in some cases. 4006 // We do not have to keep everything in memory. 4007 if (Flags.isByVal()) { 4008 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4009 4010 if (CallConv == CallingConv::Fast) 4011 ComputeArgOffset(); 4012 4013 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4014 ObjSize = Flags.getByValSize(); 4015 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4016 // Empty aggregate parameters do not take up registers. Examples: 4017 // struct { } a; 4018 // union { } b; 4019 // int c[0]; 4020 // etc. However, we have to provide a place-holder in InVals, so 4021 // pretend we have an 8-byte item at the current address for that 4022 // purpose. 4023 if (!ObjSize) { 4024 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4025 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4026 InVals.push_back(FIN); 4027 continue; 4028 } 4029 4030 // Create a stack object covering all stack doublewords occupied 4031 // by the argument. If the argument is (fully or partially) on 4032 // the stack, or if the argument is fully in registers but the 4033 // caller has allocated the parameter save anyway, we can refer 4034 // directly to the caller's stack frame. Otherwise, create a 4035 // local copy in our own frame. 4036 int FI; 4037 if (HasParameterArea || 4038 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4039 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4040 else 4041 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4042 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4043 4044 // Handle aggregates smaller than 8 bytes. 4045 if (ObjSize < PtrByteSize) { 4046 // The value of the object is its address, which differs from the 4047 // address of the enclosing doubleword on big-endian systems. 4048 SDValue Arg = FIN; 4049 if (!isLittleEndian) { 4050 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4051 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4052 } 4053 InVals.push_back(Arg); 4054 4055 if (GPR_idx != Num_GPR_Regs) { 4056 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4057 FuncInfo->addLiveInAttr(VReg, Flags); 4058 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4059 SDValue Store; 4060 4061 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4062 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4063 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4064 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4065 MachinePointerInfo(&*FuncArg), ObjType); 4066 } else { 4067 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4068 // store the whole register as-is to the parameter save area 4069 // slot. 4070 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4071 MachinePointerInfo(&*FuncArg)); 4072 } 4073 4074 MemOps.push_back(Store); 4075 } 4076 // Whether we copied from a register or not, advance the offset 4077 // into the parameter save area by a full doubleword. 4078 ArgOffset += PtrByteSize; 4079 continue; 4080 } 4081 4082 // The value of the object is its address, which is the address of 4083 // its first stack doubleword. 4084 InVals.push_back(FIN); 4085 4086 // Store whatever pieces of the object are in registers to memory. 4087 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4088 if (GPR_idx == Num_GPR_Regs) 4089 break; 4090 4091 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4092 FuncInfo->addLiveInAttr(VReg, Flags); 4093 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4094 SDValue Addr = FIN; 4095 if (j) { 4096 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4097 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4098 } 4099 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4100 MachinePointerInfo(&*FuncArg, j)); 4101 MemOps.push_back(Store); 4102 ++GPR_idx; 4103 } 4104 ArgOffset += ArgSize; 4105 continue; 4106 } 4107 4108 switch (ObjectVT.getSimpleVT().SimpleTy) { 4109 default: llvm_unreachable("Unhandled argument type!"); 4110 case MVT::i1: 4111 case MVT::i32: 4112 case MVT::i64: 4113 if (Flags.isNest()) { 4114 // The 'nest' parameter, if any, is passed in R11. 4115 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4116 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4117 4118 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4119 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4120 4121 break; 4122 } 4123 4124 // These can be scalar arguments or elements of an integer array type 4125 // passed directly. Clang may use those instead of "byval" aggregate 4126 // types to avoid forcing arguments to memory unnecessarily. 4127 if (GPR_idx != Num_GPR_Regs) { 4128 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4129 FuncInfo->addLiveInAttr(VReg, Flags); 4130 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4131 4132 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4133 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4134 // value to MVT::i64 and then truncate to the correct register size. 4135 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4136 } else { 4137 if (CallConv == CallingConv::Fast) 4138 ComputeArgOffset(); 4139 4140 needsLoad = true; 4141 ArgSize = PtrByteSize; 4142 } 4143 if (CallConv != CallingConv::Fast || needsLoad) 4144 ArgOffset += 8; 4145 break; 4146 4147 case MVT::f32: 4148 case MVT::f64: 4149 // These can be scalar arguments or elements of a float array type 4150 // passed directly. The latter are used to implement ELFv2 homogenous 4151 // float aggregates. 4152 if (FPR_idx != Num_FPR_Regs) { 4153 unsigned VReg; 4154 4155 if (ObjectVT == MVT::f32) 4156 VReg = MF.addLiveIn(FPR[FPR_idx], 4157 Subtarget.hasP8Vector() 4158 ? &PPC::VSSRCRegClass 4159 : &PPC::F4RCRegClass); 4160 else 4161 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4162 ? &PPC::VSFRCRegClass 4163 : &PPC::F8RCRegClass); 4164 4165 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4166 ++FPR_idx; 4167 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4168 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4169 // once we support fp <-> gpr moves. 4170 4171 // This can only ever happen in the presence of f32 array types, 4172 // since otherwise we never run out of FPRs before running out 4173 // of GPRs. 4174 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4175 FuncInfo->addLiveInAttr(VReg, Flags); 4176 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4177 4178 if (ObjectVT == MVT::f32) { 4179 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4180 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4181 DAG.getConstant(32, dl, MVT::i32)); 4182 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4183 } 4184 4185 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4186 } else { 4187 if (CallConv == CallingConv::Fast) 4188 ComputeArgOffset(); 4189 4190 needsLoad = true; 4191 } 4192 4193 // When passing an array of floats, the array occupies consecutive 4194 // space in the argument area; only round up to the next doubleword 4195 // at the end of the array. Otherwise, each float takes 8 bytes. 4196 if (CallConv != CallingConv::Fast || needsLoad) { 4197 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4198 ArgOffset += ArgSize; 4199 if (Flags.isInConsecutiveRegsLast()) 4200 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4201 } 4202 break; 4203 case MVT::v4f32: 4204 case MVT::v4i32: 4205 case MVT::v8i16: 4206 case MVT::v16i8: 4207 case MVT::v2f64: 4208 case MVT::v2i64: 4209 case MVT::v1i128: 4210 case MVT::f128: 4211 if (!Subtarget.hasQPX()) { 4212 // These can be scalar arguments or elements of a vector array type 4213 // passed directly. The latter are used to implement ELFv2 homogenous 4214 // vector aggregates. 4215 if (VR_idx != Num_VR_Regs) { 4216 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4217 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4218 ++VR_idx; 4219 } else { 4220 if (CallConv == CallingConv::Fast) 4221 ComputeArgOffset(); 4222 needsLoad = true; 4223 } 4224 if (CallConv != CallingConv::Fast || needsLoad) 4225 ArgOffset += 16; 4226 break; 4227 } // not QPX 4228 4229 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4230 "Invalid QPX parameter type"); 4231 LLVM_FALLTHROUGH; 4232 4233 case MVT::v4f64: 4234 case MVT::v4i1: 4235 // QPX vectors are treated like their scalar floating-point subregisters 4236 // (except that they're larger). 4237 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4238 if (QFPR_idx != Num_QFPR_Regs) { 4239 const TargetRegisterClass *RC; 4240 switch (ObjectVT.getSimpleVT().SimpleTy) { 4241 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4242 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4243 default: RC = &PPC::QBRCRegClass; break; 4244 } 4245 4246 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4247 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4248 ++QFPR_idx; 4249 } else { 4250 if (CallConv == CallingConv::Fast) 4251 ComputeArgOffset(); 4252 needsLoad = true; 4253 } 4254 if (CallConv != CallingConv::Fast || needsLoad) 4255 ArgOffset += Sz; 4256 break; 4257 } 4258 4259 // We need to load the argument to a virtual register if we determined 4260 // above that we ran out of physical registers of the appropriate type. 4261 if (needsLoad) { 4262 if (ObjSize < ArgSize && !isLittleEndian) 4263 CurArgOffset += ArgSize - ObjSize; 4264 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4265 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4266 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4267 } 4268 4269 InVals.push_back(ArgVal); 4270 } 4271 4272 // Area that is at least reserved in the caller of this function. 4273 unsigned MinReservedArea; 4274 if (HasParameterArea) 4275 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4276 else 4277 MinReservedArea = LinkageSize; 4278 4279 // Set the size that is at least reserved in caller of this function. Tail 4280 // call optimized functions' reserved stack space needs to be aligned so that 4281 // taking the difference between two stack areas will result in an aligned 4282 // stack. 4283 MinReservedArea = 4284 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4285 FuncInfo->setMinReservedArea(MinReservedArea); 4286 4287 // If the function takes variable number of arguments, make a frame index for 4288 // the start of the first vararg value... for expansion of llvm.va_start. 4289 if (isVarArg) { 4290 int Depth = ArgOffset; 4291 4292 FuncInfo->setVarArgsFrameIndex( 4293 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4294 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4295 4296 // If this function is vararg, store any remaining integer argument regs 4297 // to their spots on the stack so that they may be loaded by dereferencing 4298 // the result of va_next. 4299 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4300 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4301 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4302 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4303 SDValue Store = 4304 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4305 MemOps.push_back(Store); 4306 // Increment the address by four for the next argument to store 4307 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4308 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4309 } 4310 } 4311 4312 if (!MemOps.empty()) 4313 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4314 4315 return Chain; 4316 } 4317 4318 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4319 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4320 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4321 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4322 // TODO: add description of PPC stack frame format, or at least some docs. 4323 // 4324 MachineFunction &MF = DAG.getMachineFunction(); 4325 MachineFrameInfo &MFI = MF.getFrameInfo(); 4326 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4327 4328 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4329 bool isPPC64 = PtrVT == MVT::i64; 4330 // Potential tail calls could cause overwriting of argument stack slots. 4331 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4332 (CallConv == CallingConv::Fast)); 4333 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4334 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4335 unsigned ArgOffset = LinkageSize; 4336 // Area that is at least reserved in caller of this function. 4337 unsigned MinReservedArea = ArgOffset; 4338 4339 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4340 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4341 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4342 }; 4343 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4344 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4345 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4346 }; 4347 static const MCPhysReg VR[] = { 4348 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4349 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4350 }; 4351 4352 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4353 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4354 const unsigned Num_VR_Regs = array_lengthof( VR); 4355 4356 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4357 4358 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4359 4360 // In 32-bit non-varargs functions, the stack space for vectors is after the 4361 // stack space for non-vectors. We do not use this space unless we have 4362 // too many vectors to fit in registers, something that only occurs in 4363 // constructed examples:), but we have to walk the arglist to figure 4364 // that out...for the pathological case, compute VecArgOffset as the 4365 // start of the vector parameter area. Computing VecArgOffset is the 4366 // entire point of the following loop. 4367 unsigned VecArgOffset = ArgOffset; 4368 if (!isVarArg && !isPPC64) { 4369 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4370 ++ArgNo) { 4371 EVT ObjectVT = Ins[ArgNo].VT; 4372 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4373 4374 if (Flags.isByVal()) { 4375 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4376 unsigned ObjSize = Flags.getByValSize(); 4377 unsigned ArgSize = 4378 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4379 VecArgOffset += ArgSize; 4380 continue; 4381 } 4382 4383 switch(ObjectVT.getSimpleVT().SimpleTy) { 4384 default: llvm_unreachable("Unhandled argument type!"); 4385 case MVT::i1: 4386 case MVT::i32: 4387 case MVT::f32: 4388 VecArgOffset += 4; 4389 break; 4390 case MVT::i64: // PPC64 4391 case MVT::f64: 4392 // FIXME: We are guaranteed to be !isPPC64 at this point. 4393 // Does MVT::i64 apply? 4394 VecArgOffset += 8; 4395 break; 4396 case MVT::v4f32: 4397 case MVT::v4i32: 4398 case MVT::v8i16: 4399 case MVT::v16i8: 4400 // Nothing to do, we're only looking at Nonvector args here. 4401 break; 4402 } 4403 } 4404 } 4405 // We've found where the vector parameter area in memory is. Skip the 4406 // first 12 parameters; these don't use that memory. 4407 VecArgOffset = ((VecArgOffset+15)/16)*16; 4408 VecArgOffset += 12*16; 4409 4410 // Add DAG nodes to load the arguments or copy them out of registers. On 4411 // entry to a function on PPC, the arguments start after the linkage area, 4412 // although the first ones are often in registers. 4413 4414 SmallVector<SDValue, 8> MemOps; 4415 unsigned nAltivecParamsAtEnd = 0; 4416 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4417 unsigned CurArgIdx = 0; 4418 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4419 SDValue ArgVal; 4420 bool needsLoad = false; 4421 EVT ObjectVT = Ins[ArgNo].VT; 4422 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4423 unsigned ArgSize = ObjSize; 4424 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4425 if (Ins[ArgNo].isOrigArg()) { 4426 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4427 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4428 } 4429 unsigned CurArgOffset = ArgOffset; 4430 4431 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4432 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4433 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4434 if (isVarArg || isPPC64) { 4435 MinReservedArea = ((MinReservedArea+15)/16)*16; 4436 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4437 Flags, 4438 PtrByteSize); 4439 } else nAltivecParamsAtEnd++; 4440 } else 4441 // Calculate min reserved area. 4442 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4443 Flags, 4444 PtrByteSize); 4445 4446 // FIXME the codegen can be much improved in some cases. 4447 // We do not have to keep everything in memory. 4448 if (Flags.isByVal()) { 4449 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4450 4451 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4452 ObjSize = Flags.getByValSize(); 4453 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4454 // Objects of size 1 and 2 are right justified, everything else is 4455 // left justified. This means the memory address is adjusted forwards. 4456 if (ObjSize==1 || ObjSize==2) { 4457 CurArgOffset = CurArgOffset + (4 - ObjSize); 4458 } 4459 // The value of the object is its address. 4460 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4461 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4462 InVals.push_back(FIN); 4463 if (ObjSize==1 || ObjSize==2) { 4464 if (GPR_idx != Num_GPR_Regs) { 4465 unsigned VReg; 4466 if (isPPC64) 4467 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4468 else 4469 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4470 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4471 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4472 SDValue Store = 4473 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4474 MachinePointerInfo(&*FuncArg), ObjType); 4475 MemOps.push_back(Store); 4476 ++GPR_idx; 4477 } 4478 4479 ArgOffset += PtrByteSize; 4480 4481 continue; 4482 } 4483 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4484 // Store whatever pieces of the object are in registers 4485 // to memory. ArgOffset will be the address of the beginning 4486 // of the object. 4487 if (GPR_idx != Num_GPR_Regs) { 4488 unsigned VReg; 4489 if (isPPC64) 4490 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4491 else 4492 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4493 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4494 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4495 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4496 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4497 MachinePointerInfo(&*FuncArg, j)); 4498 MemOps.push_back(Store); 4499 ++GPR_idx; 4500 ArgOffset += PtrByteSize; 4501 } else { 4502 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4503 break; 4504 } 4505 } 4506 continue; 4507 } 4508 4509 switch (ObjectVT.getSimpleVT().SimpleTy) { 4510 default: llvm_unreachable("Unhandled argument type!"); 4511 case MVT::i1: 4512 case MVT::i32: 4513 if (!isPPC64) { 4514 if (GPR_idx != Num_GPR_Regs) { 4515 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4516 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4517 4518 if (ObjectVT == MVT::i1) 4519 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4520 4521 ++GPR_idx; 4522 } else { 4523 needsLoad = true; 4524 ArgSize = PtrByteSize; 4525 } 4526 // All int arguments reserve stack space in the Darwin ABI. 4527 ArgOffset += PtrByteSize; 4528 break; 4529 } 4530 LLVM_FALLTHROUGH; 4531 case MVT::i64: // PPC64 4532 if (GPR_idx != Num_GPR_Regs) { 4533 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4534 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4535 4536 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4537 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4538 // value to MVT::i64 and then truncate to the correct register size. 4539 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4540 4541 ++GPR_idx; 4542 } else { 4543 needsLoad = true; 4544 ArgSize = PtrByteSize; 4545 } 4546 // All int arguments reserve stack space in the Darwin ABI. 4547 ArgOffset += 8; 4548 break; 4549 4550 case MVT::f32: 4551 case MVT::f64: 4552 // Every 4 bytes of argument space consumes one of the GPRs available for 4553 // argument passing. 4554 if (GPR_idx != Num_GPR_Regs) { 4555 ++GPR_idx; 4556 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4557 ++GPR_idx; 4558 } 4559 if (FPR_idx != Num_FPR_Regs) { 4560 unsigned VReg; 4561 4562 if (ObjectVT == MVT::f32) 4563 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4564 else 4565 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4566 4567 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4568 ++FPR_idx; 4569 } else { 4570 needsLoad = true; 4571 } 4572 4573 // All FP arguments reserve stack space in the Darwin ABI. 4574 ArgOffset += isPPC64 ? 8 : ObjSize; 4575 break; 4576 case MVT::v4f32: 4577 case MVT::v4i32: 4578 case MVT::v8i16: 4579 case MVT::v16i8: 4580 // Note that vector arguments in registers don't reserve stack space, 4581 // except in varargs functions. 4582 if (VR_idx != Num_VR_Regs) { 4583 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4584 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4585 if (isVarArg) { 4586 while ((ArgOffset % 16) != 0) { 4587 ArgOffset += PtrByteSize; 4588 if (GPR_idx != Num_GPR_Regs) 4589 GPR_idx++; 4590 } 4591 ArgOffset += 16; 4592 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4593 } 4594 ++VR_idx; 4595 } else { 4596 if (!isVarArg && !isPPC64) { 4597 // Vectors go after all the nonvectors. 4598 CurArgOffset = VecArgOffset; 4599 VecArgOffset += 16; 4600 } else { 4601 // Vectors are aligned. 4602 ArgOffset = ((ArgOffset+15)/16)*16; 4603 CurArgOffset = ArgOffset; 4604 ArgOffset += 16; 4605 } 4606 needsLoad = true; 4607 } 4608 break; 4609 } 4610 4611 // We need to load the argument to a virtual register if we determined above 4612 // that we ran out of physical registers of the appropriate type. 4613 if (needsLoad) { 4614 int FI = MFI.CreateFixedObject(ObjSize, 4615 CurArgOffset + (ArgSize - ObjSize), 4616 isImmutable); 4617 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4618 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4619 } 4620 4621 InVals.push_back(ArgVal); 4622 } 4623 4624 // Allow for Altivec parameters at the end, if needed. 4625 if (nAltivecParamsAtEnd) { 4626 MinReservedArea = ((MinReservedArea+15)/16)*16; 4627 MinReservedArea += 16*nAltivecParamsAtEnd; 4628 } 4629 4630 // Area that is at least reserved in the caller of this function. 4631 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4632 4633 // Set the size that is at least reserved in caller of this function. Tail 4634 // call optimized functions' reserved stack space needs to be aligned so that 4635 // taking the difference between two stack areas will result in an aligned 4636 // stack. 4637 MinReservedArea = 4638 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4639 FuncInfo->setMinReservedArea(MinReservedArea); 4640 4641 // If the function takes variable number of arguments, make a frame index for 4642 // the start of the first vararg value... for expansion of llvm.va_start. 4643 if (isVarArg) { 4644 int Depth = ArgOffset; 4645 4646 FuncInfo->setVarArgsFrameIndex( 4647 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4648 Depth, true)); 4649 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4650 4651 // If this function is vararg, store any remaining integer argument regs 4652 // to their spots on the stack so that they may be loaded by dereferencing 4653 // the result of va_next. 4654 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4655 unsigned VReg; 4656 4657 if (isPPC64) 4658 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4659 else 4660 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4661 4662 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4663 SDValue Store = 4664 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4665 MemOps.push_back(Store); 4666 // Increment the address by four for the next argument to store 4667 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4668 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4669 } 4670 } 4671 4672 if (!MemOps.empty()) 4673 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4674 4675 return Chain; 4676 } 4677 4678 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4679 /// adjusted to accommodate the arguments for the tailcall. 4680 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4681 unsigned ParamSize) { 4682 4683 if (!isTailCall) return 0; 4684 4685 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4686 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4687 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4688 // Remember only if the new adjustment is bigger. 4689 if (SPDiff < FI->getTailCallSPDelta()) 4690 FI->setTailCallSPDelta(SPDiff); 4691 4692 return SPDiff; 4693 } 4694 4695 static bool isFunctionGlobalAddress(SDValue Callee); 4696 4697 static bool 4698 callsShareTOCBase(const Function *Caller, SDValue Callee, 4699 const TargetMachine &TM) { 4700 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4701 // don't have enough information to determine if the caller and calle share 4702 // the same TOC base, so we have to pessimistically assume they don't for 4703 // correctness. 4704 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4705 if (!G) 4706 return false; 4707 4708 const GlobalValue *GV = G->getGlobal(); 4709 // The medium and large code models are expected to provide a sufficiently 4710 // large TOC to provide all data addressing needs of a module with a 4711 // single TOC. Since each module will be addressed with a single TOC then we 4712 // only need to check that caller and callee don't cross dso boundaries. 4713 if (CodeModel::Medium == TM.getCodeModel() || 4714 CodeModel::Large == TM.getCodeModel()) 4715 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4716 4717 // Otherwise we need to ensure callee and caller are in the same section, 4718 // since the linker may allocate multiple TOCs, and we don't know which 4719 // sections will belong to the same TOC base. 4720 4721 if (!GV->isStrongDefinitionForLinker()) 4722 return false; 4723 4724 // Any explicitly-specified sections and section prefixes must also match. 4725 // Also, if we're using -ffunction-sections, then each function is always in 4726 // a different section (the same is true for COMDAT functions). 4727 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4728 GV->getSection() != Caller->getSection()) 4729 return false; 4730 if (const auto *F = dyn_cast<Function>(GV)) { 4731 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4732 return false; 4733 } 4734 4735 // If the callee might be interposed, then we can't assume the ultimate call 4736 // target will be in the same section. Even in cases where we can assume that 4737 // interposition won't happen, in any case where the linker might insert a 4738 // stub to allow for interposition, we must generate code as though 4739 // interposition might occur. To understand why this matters, consider a 4740 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4741 // in the same section, but a is in a different module (i.e. has a different 4742 // TOC base pointer). If the linker allows for interposition between b and c, 4743 // then it will generate a stub for the call edge between b and c which will 4744 // save the TOC pointer into the designated stack slot allocated by b. If we 4745 // return true here, and therefore allow a tail call between b and c, that 4746 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4747 // pointer into the stack slot allocated by a (where the a -> b stub saved 4748 // a's TOC base pointer). If we're not considering a tail call, but rather, 4749 // whether a nop is needed after the call instruction in b, because the linker 4750 // will insert a stub, it might complain about a missing nop if we omit it 4751 // (although many don't complain in this case). 4752 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4753 return false; 4754 4755 return true; 4756 } 4757 4758 static bool 4759 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4760 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4761 assert(Subtarget.is64BitELFABI()); 4762 4763 const unsigned PtrByteSize = 8; 4764 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4765 4766 static const MCPhysReg GPR[] = { 4767 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4768 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4769 }; 4770 static const MCPhysReg VR[] = { 4771 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4772 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4773 }; 4774 4775 const unsigned NumGPRs = array_lengthof(GPR); 4776 const unsigned NumFPRs = 13; 4777 const unsigned NumVRs = array_lengthof(VR); 4778 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4779 4780 unsigned NumBytes = LinkageSize; 4781 unsigned AvailableFPRs = NumFPRs; 4782 unsigned AvailableVRs = NumVRs; 4783 4784 for (const ISD::OutputArg& Param : Outs) { 4785 if (Param.Flags.isNest()) continue; 4786 4787 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4788 PtrByteSize, LinkageSize, ParamAreaSize, 4789 NumBytes, AvailableFPRs, AvailableVRs, 4790 Subtarget.hasQPX())) 4791 return true; 4792 } 4793 return false; 4794 } 4795 4796 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4797 if (CB.arg_size() != CallerFn->arg_size()) 4798 return false; 4799 4800 auto CalleeArgIter = CB.arg_begin(); 4801 auto CalleeArgEnd = CB.arg_end(); 4802 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4803 4804 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4805 const Value* CalleeArg = *CalleeArgIter; 4806 const Value* CallerArg = &(*CallerArgIter); 4807 if (CalleeArg == CallerArg) 4808 continue; 4809 4810 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4811 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4812 // } 4813 // 1st argument of callee is undef and has the same type as caller. 4814 if (CalleeArg->getType() == CallerArg->getType() && 4815 isa<UndefValue>(CalleeArg)) 4816 continue; 4817 4818 return false; 4819 } 4820 4821 return true; 4822 } 4823 4824 // Returns true if TCO is possible between the callers and callees 4825 // calling conventions. 4826 static bool 4827 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4828 CallingConv::ID CalleeCC) { 4829 // Tail calls are possible with fastcc and ccc. 4830 auto isTailCallableCC = [] (CallingConv::ID CC){ 4831 return CC == CallingConv::C || CC == CallingConv::Fast; 4832 }; 4833 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4834 return false; 4835 4836 // We can safely tail call both fastcc and ccc callees from a c calling 4837 // convention caller. If the caller is fastcc, we may have less stack space 4838 // than a non-fastcc caller with the same signature so disable tail-calls in 4839 // that case. 4840 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4841 } 4842 4843 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4844 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4845 const SmallVectorImpl<ISD::OutputArg> &Outs, 4846 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4847 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4848 4849 if (DisableSCO && !TailCallOpt) return false; 4850 4851 // Variadic argument functions are not supported. 4852 if (isVarArg) return false; 4853 4854 auto &Caller = DAG.getMachineFunction().getFunction(); 4855 // Check that the calling conventions are compatible for tco. 4856 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4857 return false; 4858 4859 // Caller contains any byval parameter is not supported. 4860 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4861 return false; 4862 4863 // Callee contains any byval parameter is not supported, too. 4864 // Note: This is a quick work around, because in some cases, e.g. 4865 // caller's stack size > callee's stack size, we are still able to apply 4866 // sibling call optimization. For example, gcc is able to do SCO for caller1 4867 // in the following example, but not for caller2. 4868 // struct test { 4869 // long int a; 4870 // char ary[56]; 4871 // } gTest; 4872 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4873 // b->a = v.a; 4874 // return 0; 4875 // } 4876 // void caller1(struct test a, struct test c, struct test *b) { 4877 // callee(gTest, b); } 4878 // void caller2(struct test *b) { callee(gTest, b); } 4879 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4880 return false; 4881 4882 // If callee and caller use different calling conventions, we cannot pass 4883 // parameters on stack since offsets for the parameter area may be different. 4884 if (Caller.getCallingConv() != CalleeCC && 4885 needStackSlotPassParameters(Subtarget, Outs)) 4886 return false; 4887 4888 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4889 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4890 // callee potentially have different TOC bases then we cannot tail call since 4891 // we need to restore the TOC pointer after the call. 4892 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4893 // We cannot guarantee this for indirect calls or calls to external functions. 4894 // When PC-Relative addressing is used, the concept of the TOC is no longer 4895 // applicable so this check is not required. 4896 // Check first for indirect calls. 4897 if (!Subtarget.isUsingPCRelativeCalls() && 4898 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4899 return false; 4900 4901 // Check if we share the TOC base. 4902 if (!Subtarget.isUsingPCRelativeCalls() && 4903 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4904 return false; 4905 4906 // TCO allows altering callee ABI, so we don't have to check further. 4907 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4908 return true; 4909 4910 if (DisableSCO) return false; 4911 4912 // If callee use the same argument list that caller is using, then we can 4913 // apply SCO on this case. If it is not, then we need to check if callee needs 4914 // stack for passing arguments. 4915 // PC Relative tail calls may not have a CallBase. 4916 // If there is no CallBase we cannot verify if we have the same argument 4917 // list so assume that we don't have the same argument list. 4918 if (CB && !hasSameArgumentList(&Caller, *CB) && 4919 needStackSlotPassParameters(Subtarget, Outs)) 4920 return false; 4921 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4922 return false; 4923 4924 return true; 4925 } 4926 4927 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4928 /// for tail call optimization. Targets which want to do tail call 4929 /// optimization should implement this function. 4930 bool 4931 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4932 CallingConv::ID CalleeCC, 4933 bool isVarArg, 4934 const SmallVectorImpl<ISD::InputArg> &Ins, 4935 SelectionDAG& DAG) const { 4936 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4937 return false; 4938 4939 // Variable argument functions are not supported. 4940 if (isVarArg) 4941 return false; 4942 4943 MachineFunction &MF = DAG.getMachineFunction(); 4944 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4945 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4946 // Functions containing by val parameters are not supported. 4947 for (unsigned i = 0; i != Ins.size(); i++) { 4948 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4949 if (Flags.isByVal()) return false; 4950 } 4951 4952 // Non-PIC/GOT tail calls are supported. 4953 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4954 return true; 4955 4956 // At the moment we can only do local tail calls (in same module, hidden 4957 // or protected) if we are generating PIC. 4958 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4959 return G->getGlobal()->hasHiddenVisibility() 4960 || G->getGlobal()->hasProtectedVisibility(); 4961 } 4962 4963 return false; 4964 } 4965 4966 /// isCallCompatibleAddress - Return the immediate to use if the specified 4967 /// 32-bit value is representable in the immediate field of a BxA instruction. 4968 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4969 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4970 if (!C) return nullptr; 4971 4972 int Addr = C->getZExtValue(); 4973 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4974 SignExtend32<26>(Addr) != Addr) 4975 return nullptr; // Top 6 bits have to be sext of immediate. 4976 4977 return DAG 4978 .getConstant( 4979 (int)C->getZExtValue() >> 2, SDLoc(Op), 4980 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4981 .getNode(); 4982 } 4983 4984 namespace { 4985 4986 struct TailCallArgumentInfo { 4987 SDValue Arg; 4988 SDValue FrameIdxOp; 4989 int FrameIdx = 0; 4990 4991 TailCallArgumentInfo() = default; 4992 }; 4993 4994 } // end anonymous namespace 4995 4996 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4997 static void StoreTailCallArgumentsToStackSlot( 4998 SelectionDAG &DAG, SDValue Chain, 4999 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5000 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5001 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5002 SDValue Arg = TailCallArgs[i].Arg; 5003 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5004 int FI = TailCallArgs[i].FrameIdx; 5005 // Store relative to framepointer. 5006 MemOpChains.push_back(DAG.getStore( 5007 Chain, dl, Arg, FIN, 5008 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5009 } 5010 } 5011 5012 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5013 /// the appropriate stack slot for the tail call optimized function call. 5014 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5015 SDValue OldRetAddr, SDValue OldFP, 5016 int SPDiff, const SDLoc &dl) { 5017 if (SPDiff) { 5018 // Calculate the new stack slot for the return address. 5019 MachineFunction &MF = DAG.getMachineFunction(); 5020 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5021 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5022 bool isPPC64 = Subtarget.isPPC64(); 5023 int SlotSize = isPPC64 ? 8 : 4; 5024 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5025 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5026 NewRetAddrLoc, true); 5027 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5028 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5029 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5030 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5031 } 5032 return Chain; 5033 } 5034 5035 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5036 /// the position of the argument. 5037 static void 5038 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5039 SDValue Arg, int SPDiff, unsigned ArgOffset, 5040 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5041 int Offset = ArgOffset + SPDiff; 5042 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5043 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5044 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5045 SDValue FIN = DAG.getFrameIndex(FI, VT); 5046 TailCallArgumentInfo Info; 5047 Info.Arg = Arg; 5048 Info.FrameIdxOp = FIN; 5049 Info.FrameIdx = FI; 5050 TailCallArguments.push_back(Info); 5051 } 5052 5053 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5054 /// stack slot. Returns the chain as result and the loaded frame pointers in 5055 /// LROpOut/FPOpout. Used when tail calling. 5056 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5057 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5058 SDValue &FPOpOut, const SDLoc &dl) const { 5059 if (SPDiff) { 5060 // Load the LR and FP stack slot for later adjusting. 5061 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5062 LROpOut = getReturnAddrFrameIndex(DAG); 5063 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5064 Chain = SDValue(LROpOut.getNode(), 1); 5065 } 5066 return Chain; 5067 } 5068 5069 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5070 /// by "Src" to address "Dst" of size "Size". Alignment information is 5071 /// specified by the specific parameter attribute. The copy will be passed as 5072 /// a byval function parameter. 5073 /// Sometimes what we are copying is the end of a larger object, the part that 5074 /// does not fit in registers. 5075 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5076 SDValue Chain, ISD::ArgFlagsTy Flags, 5077 SelectionDAG &DAG, const SDLoc &dl) { 5078 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5079 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5080 Flags.getNonZeroByValAlign(), false, false, false, 5081 MachinePointerInfo(), MachinePointerInfo()); 5082 } 5083 5084 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5085 /// tail calls. 5086 static void LowerMemOpCallTo( 5087 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5088 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5089 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5090 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5091 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5092 if (!isTailCall) { 5093 if (isVector) { 5094 SDValue StackPtr; 5095 if (isPPC64) 5096 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5097 else 5098 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5099 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5100 DAG.getConstant(ArgOffset, dl, PtrVT)); 5101 } 5102 MemOpChains.push_back( 5103 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5104 // Calculate and remember argument location. 5105 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5106 TailCallArguments); 5107 } 5108 5109 static void 5110 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5111 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5112 SDValue FPOp, 5113 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5114 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5115 // might overwrite each other in case of tail call optimization. 5116 SmallVector<SDValue, 8> MemOpChains2; 5117 // Do not flag preceding copytoreg stuff together with the following stuff. 5118 InFlag = SDValue(); 5119 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5120 MemOpChains2, dl); 5121 if (!MemOpChains2.empty()) 5122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5123 5124 // Store the return address to the appropriate stack slot. 5125 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5126 5127 // Emit callseq_end just before tailcall node. 5128 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5129 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5130 InFlag = Chain.getValue(1); 5131 } 5132 5133 // Is this global address that of a function that can be called by name? (as 5134 // opposed to something that must hold a descriptor for an indirect call). 5135 static bool isFunctionGlobalAddress(SDValue Callee) { 5136 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5137 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5138 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5139 return false; 5140 5141 return G->getGlobal()->getValueType()->isFunctionTy(); 5142 } 5143 5144 return false; 5145 } 5146 5147 SDValue PPCTargetLowering::LowerCallResult( 5148 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5149 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5150 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5151 SmallVector<CCValAssign, 16> RVLocs; 5152 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5153 *DAG.getContext()); 5154 5155 CCRetInfo.AnalyzeCallResult( 5156 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5157 ? RetCC_PPC_Cold 5158 : RetCC_PPC); 5159 5160 // Copy all of the result registers out of their specified physreg. 5161 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5162 CCValAssign &VA = RVLocs[i]; 5163 assert(VA.isRegLoc() && "Can only return in registers!"); 5164 5165 SDValue Val; 5166 5167 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5168 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5169 InFlag); 5170 Chain = Lo.getValue(1); 5171 InFlag = Lo.getValue(2); 5172 VA = RVLocs[++i]; // skip ahead to next loc 5173 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5174 InFlag); 5175 Chain = Hi.getValue(1); 5176 InFlag = Hi.getValue(2); 5177 if (!Subtarget.isLittleEndian()) 5178 std::swap (Lo, Hi); 5179 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5180 } else { 5181 Val = DAG.getCopyFromReg(Chain, dl, 5182 VA.getLocReg(), VA.getLocVT(), InFlag); 5183 Chain = Val.getValue(1); 5184 InFlag = Val.getValue(2); 5185 } 5186 5187 switch (VA.getLocInfo()) { 5188 default: llvm_unreachable("Unknown loc info!"); 5189 case CCValAssign::Full: break; 5190 case CCValAssign::AExt: 5191 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5192 break; 5193 case CCValAssign::ZExt: 5194 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5195 DAG.getValueType(VA.getValVT())); 5196 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5197 break; 5198 case CCValAssign::SExt: 5199 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5200 DAG.getValueType(VA.getValVT())); 5201 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5202 break; 5203 } 5204 5205 InVals.push_back(Val); 5206 } 5207 5208 return Chain; 5209 } 5210 5211 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5212 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5213 // PatchPoint calls are not indirect. 5214 if (isPatchPoint) 5215 return false; 5216 5217 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5218 return false; 5219 5220 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5221 // becuase the immediate function pointer points to a descriptor instead of 5222 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5223 // pointer immediate points to the global entry point, while the BLA would 5224 // need to jump to the local entry point (see rL211174). 5225 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5226 isBLACompatibleAddress(Callee, DAG)) 5227 return false; 5228 5229 return true; 5230 } 5231 5232 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5233 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5234 return Subtarget.isAIXABI() || 5235 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5236 } 5237 5238 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5239 const Function &Caller, 5240 const SDValue &Callee, 5241 const PPCSubtarget &Subtarget, 5242 const TargetMachine &TM) { 5243 if (CFlags.IsTailCall) 5244 return PPCISD::TC_RETURN; 5245 5246 // This is a call through a function pointer. 5247 if (CFlags.IsIndirect) { 5248 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5249 // indirect calls. The save of the caller's TOC pointer to the stack will be 5250 // inserted into the DAG as part of call lowering. The restore of the TOC 5251 // pointer is modeled by using a pseudo instruction for the call opcode that 5252 // represents the 2 instruction sequence of an indirect branch and link, 5253 // immediately followed by a load of the TOC pointer from the the stack save 5254 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5255 // as it is not saved or used. 5256 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5257 : PPCISD::BCTRL; 5258 } 5259 5260 if (Subtarget.isUsingPCRelativeCalls()) { 5261 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5262 return PPCISD::CALL_NOTOC; 5263 } 5264 5265 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5266 // immediately following the call instruction if the caller and callee may 5267 // have different TOC bases. At link time if the linker determines the calls 5268 // may not share a TOC base, the call is redirected to a trampoline inserted 5269 // by the linker. The trampoline will (among other things) save the callers 5270 // TOC pointer at an ABI designated offset in the linkage area and the linker 5271 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5272 // into gpr2. 5273 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5274 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5275 : PPCISD::CALL_NOP; 5276 5277 return PPCISD::CALL; 5278 } 5279 5280 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5281 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5282 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5283 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5284 return SDValue(Dest, 0); 5285 5286 // Returns true if the callee is local, and false otherwise. 5287 auto isLocalCallee = [&]() { 5288 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5289 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5290 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5291 5292 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5293 !dyn_cast_or_null<GlobalIFunc>(GV); 5294 }; 5295 5296 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5297 // a static relocation model causes some versions of GNU LD (2.17.50, at 5298 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5299 // built with secure-PLT. 5300 bool UsePlt = 5301 Subtarget.is32BitELFABI() && !isLocalCallee() && 5302 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5303 5304 // On AIX, direct function calls reference the symbol for the function's 5305 // entry point, which is named by prepending a "." before the function's 5306 // C-linkage name. 5307 const auto getAIXFuncEntryPointSymbolSDNode = 5308 [&](StringRef FuncName, bool IsDeclaration, 5309 const XCOFF::StorageClass &SC) { 5310 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5311 5312 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5313 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5314 5315 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5316 // On AIX, an undefined symbol needs to be associated with a 5317 // MCSectionXCOFF to get the correct storage mapping class. 5318 // In this case, XCOFF::XMC_PR. 5319 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5320 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5321 SectionKind::getMetadata()); 5322 S->setRepresentedCsect(Sec); 5323 } 5324 5325 MVT PtrVT = 5326 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5327 return DAG.getMCSymbol(S, PtrVT); 5328 }; 5329 5330 if (isFunctionGlobalAddress(Callee)) { 5331 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5332 const GlobalValue *GV = G->getGlobal(); 5333 5334 if (!Subtarget.isAIXABI()) 5335 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5336 UsePlt ? PPCII::MO_PLT : 0); 5337 5338 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5339 const GlobalObject *GO = cast<GlobalObject>(GV); 5340 const XCOFF::StorageClass SC = 5341 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5342 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5343 SC); 5344 } 5345 5346 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5347 const char *SymName = S->getSymbol(); 5348 if (!Subtarget.isAIXABI()) 5349 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5350 UsePlt ? PPCII::MO_PLT : 0); 5351 5352 // If there exists a user-declared function whose name is the same as the 5353 // ExternalSymbol's, then we pick up the user-declared version. 5354 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5355 if (const Function *F = 5356 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5357 const XCOFF::StorageClass SC = 5358 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5359 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5360 SC); 5361 } 5362 5363 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5364 } 5365 5366 // No transformation needed. 5367 assert(Callee.getNode() && "What no callee?"); 5368 return Callee; 5369 } 5370 5371 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5372 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5373 "Expected a CALLSEQ_STARTSDNode."); 5374 5375 // The last operand is the chain, except when the node has glue. If the node 5376 // has glue, then the last operand is the glue, and the chain is the second 5377 // last operand. 5378 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5379 if (LastValue.getValueType() != MVT::Glue) 5380 return LastValue; 5381 5382 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5383 } 5384 5385 // Creates the node that moves a functions address into the count register 5386 // to prepare for an indirect call instruction. 5387 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5388 SDValue &Glue, SDValue &Chain, 5389 const SDLoc &dl) { 5390 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5391 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5392 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5393 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5394 // The glue is the second value produced. 5395 Glue = Chain.getValue(1); 5396 } 5397 5398 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5399 SDValue &Glue, SDValue &Chain, 5400 SDValue CallSeqStart, 5401 const CallBase *CB, const SDLoc &dl, 5402 bool hasNest, 5403 const PPCSubtarget &Subtarget) { 5404 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5405 // entry point, but to the function descriptor (the function entry point 5406 // address is part of the function descriptor though). 5407 // The function descriptor is a three doubleword structure with the 5408 // following fields: function entry point, TOC base address and 5409 // environment pointer. 5410 // Thus for a call through a function pointer, the following actions need 5411 // to be performed: 5412 // 1. Save the TOC of the caller in the TOC save area of its stack 5413 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5414 // 2. Load the address of the function entry point from the function 5415 // descriptor. 5416 // 3. Load the TOC of the callee from the function descriptor into r2. 5417 // 4. Load the environment pointer from the function descriptor into 5418 // r11. 5419 // 5. Branch to the function entry point address. 5420 // 6. On return of the callee, the TOC of the caller needs to be 5421 // restored (this is done in FinishCall()). 5422 // 5423 // The loads are scheduled at the beginning of the call sequence, and the 5424 // register copies are flagged together to ensure that no other 5425 // operations can be scheduled in between. E.g. without flagging the 5426 // copies together, a TOC access in the caller could be scheduled between 5427 // the assignment of the callee TOC and the branch to the callee, which leads 5428 // to incorrect code. 5429 5430 // Start by loading the function address from the descriptor. 5431 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5432 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5433 ? (MachineMemOperand::MODereferenceable | 5434 MachineMemOperand::MOInvariant) 5435 : MachineMemOperand::MONone; 5436 5437 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5438 5439 // Registers used in building the DAG. 5440 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5441 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5442 5443 // Offsets of descriptor members. 5444 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5445 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5446 5447 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5448 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5449 5450 // One load for the functions entry point address. 5451 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5452 Alignment, MMOFlags); 5453 5454 // One for loading the TOC anchor for the module that contains the called 5455 // function. 5456 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5457 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5458 SDValue TOCPtr = 5459 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5460 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5461 5462 // One for loading the environment pointer. 5463 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5464 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5465 SDValue LoadEnvPtr = 5466 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5467 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5468 5469 5470 // Then copy the newly loaded TOC anchor to the TOC pointer. 5471 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5472 Chain = TOCVal.getValue(0); 5473 Glue = TOCVal.getValue(1); 5474 5475 // If the function call has an explicit 'nest' parameter, it takes the 5476 // place of the environment pointer. 5477 assert((!hasNest || !Subtarget.isAIXABI()) && 5478 "Nest parameter is not supported on AIX."); 5479 if (!hasNest) { 5480 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5481 Chain = EnvVal.getValue(0); 5482 Glue = EnvVal.getValue(1); 5483 } 5484 5485 // The rest of the indirect call sequence is the same as the non-descriptor 5486 // DAG. 5487 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5488 } 5489 5490 static void 5491 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5492 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5493 SelectionDAG &DAG, 5494 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5495 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5496 const PPCSubtarget &Subtarget) { 5497 const bool IsPPC64 = Subtarget.isPPC64(); 5498 // MVT for a general purpose register. 5499 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5500 5501 // First operand is always the chain. 5502 Ops.push_back(Chain); 5503 5504 // If it's a direct call pass the callee as the second operand. 5505 if (!CFlags.IsIndirect) 5506 Ops.push_back(Callee); 5507 else { 5508 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5509 5510 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5511 // on the stack (this would have been done in `LowerCall_64SVR4` or 5512 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5513 // represents both the indirect branch and a load that restores the TOC 5514 // pointer from the linkage area. The operand for the TOC restore is an add 5515 // of the TOC save offset to the stack pointer. This must be the second 5516 // operand: after the chain input but before any other variadic arguments. 5517 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5518 // saved or used. 5519 if (isTOCSaveRestoreRequired(Subtarget)) { 5520 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5521 5522 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5523 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5524 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5525 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5526 Ops.push_back(AddTOC); 5527 } 5528 5529 // Add the register used for the environment pointer. 5530 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5531 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5532 RegVT)); 5533 5534 5535 // Add CTR register as callee so a bctr can be emitted later. 5536 if (CFlags.IsTailCall) 5537 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5538 } 5539 5540 // If this is a tail call add stack pointer delta. 5541 if (CFlags.IsTailCall) 5542 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5543 5544 // Add argument registers to the end of the list so that they are known live 5545 // into the call. 5546 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5547 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5548 RegsToPass[i].second.getValueType())); 5549 5550 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5551 // no way to mark dependencies as implicit here. 5552 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5553 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5554 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5555 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5556 5557 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5558 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5559 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5560 5561 // Add a register mask operand representing the call-preserved registers. 5562 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5563 const uint32_t *Mask = 5564 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5565 assert(Mask && "Missing call preserved mask for calling convention"); 5566 Ops.push_back(DAG.getRegisterMask(Mask)); 5567 5568 // If the glue is valid, it is the last operand. 5569 if (Glue.getNode()) 5570 Ops.push_back(Glue); 5571 } 5572 5573 SDValue PPCTargetLowering::FinishCall( 5574 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5575 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5576 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5577 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5578 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5579 5580 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5581 Subtarget.isAIXABI()) 5582 setUsesTOCBasePtr(DAG); 5583 5584 unsigned CallOpc = 5585 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5586 Subtarget, DAG.getTarget()); 5587 5588 if (!CFlags.IsIndirect) 5589 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5590 else if (Subtarget.usesFunctionDescriptors()) 5591 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5592 dl, CFlags.HasNest, Subtarget); 5593 else 5594 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5595 5596 // Build the operand list for the call instruction. 5597 SmallVector<SDValue, 8> Ops; 5598 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5599 SPDiff, Subtarget); 5600 5601 // Emit tail call. 5602 if (CFlags.IsTailCall) { 5603 // Indirect tail call when using PC Relative calls do not have the same 5604 // constraints. 5605 assert(((Callee.getOpcode() == ISD::Register && 5606 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5607 Callee.getOpcode() == ISD::TargetExternalSymbol || 5608 Callee.getOpcode() == ISD::TargetGlobalAddress || 5609 isa<ConstantSDNode>(Callee) || 5610 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5611 "Expecting a global address, external symbol, absolute value, " 5612 "register or an indirect tail call when PC Relative calls are " 5613 "used."); 5614 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5615 assert(CallOpc == PPCISD::TC_RETURN && 5616 "Unexpected call opcode for a tail call."); 5617 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5618 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5619 } 5620 5621 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5622 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5623 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5624 Glue = Chain.getValue(1); 5625 5626 // When performing tail call optimization the callee pops its arguments off 5627 // the stack. Account for this here so these bytes can be pushed back on in 5628 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5629 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5630 getTargetMachine().Options.GuaranteedTailCallOpt) 5631 ? NumBytes 5632 : 0; 5633 5634 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5635 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5636 Glue, dl); 5637 Glue = Chain.getValue(1); 5638 5639 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5640 DAG, InVals); 5641 } 5642 5643 SDValue 5644 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5645 SmallVectorImpl<SDValue> &InVals) const { 5646 SelectionDAG &DAG = CLI.DAG; 5647 SDLoc &dl = CLI.DL; 5648 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5649 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5650 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5651 SDValue Chain = CLI.Chain; 5652 SDValue Callee = CLI.Callee; 5653 bool &isTailCall = CLI.IsTailCall; 5654 CallingConv::ID CallConv = CLI.CallConv; 5655 bool isVarArg = CLI.IsVarArg; 5656 bool isPatchPoint = CLI.IsPatchPoint; 5657 const CallBase *CB = CLI.CB; 5658 5659 if (isTailCall) { 5660 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5661 isTailCall = false; 5662 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5663 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5664 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5665 else 5666 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5667 Ins, DAG); 5668 if (isTailCall) { 5669 ++NumTailCalls; 5670 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5671 ++NumSiblingCalls; 5672 5673 // PC Relative calls no longer guarantee that the callee is a Global 5674 // Address Node. The callee could be an indirect tail call in which 5675 // case the SDValue for the callee could be a load (to load the address 5676 // of a function pointer) or it may be a register copy (to move the 5677 // address of the callee from a function parameter into a virtual 5678 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5679 assert((Subtarget.isUsingPCRelativeCalls() || 5680 isa<GlobalAddressSDNode>(Callee)) && 5681 "Callee should be an llvm::Function object."); 5682 5683 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5684 << "\nTCO callee: "); 5685 LLVM_DEBUG(Callee.dump()); 5686 } 5687 } 5688 5689 if (!isTailCall && CB && CB->isMustTailCall()) 5690 report_fatal_error("failed to perform tail call elimination on a call " 5691 "site marked musttail"); 5692 5693 // When long calls (i.e. indirect calls) are always used, calls are always 5694 // made via function pointer. If we have a function name, first translate it 5695 // into a pointer. 5696 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5697 !isTailCall) 5698 Callee = LowerGlobalAddress(Callee, DAG); 5699 5700 CallFlags CFlags( 5701 CallConv, isTailCall, isVarArg, isPatchPoint, 5702 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5703 // hasNest 5704 Subtarget.is64BitELFABI() && 5705 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5706 CLI.NoMerge); 5707 5708 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5709 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5710 InVals, CB); 5711 5712 if (Subtarget.isSVR4ABI()) 5713 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5714 InVals, CB); 5715 5716 if (Subtarget.isAIXABI()) 5717 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5718 InVals, CB); 5719 5720 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5721 InVals, CB); 5722 } 5723 5724 SDValue PPCTargetLowering::LowerCall_32SVR4( 5725 SDValue Chain, SDValue Callee, CallFlags CFlags, 5726 const SmallVectorImpl<ISD::OutputArg> &Outs, 5727 const SmallVectorImpl<SDValue> &OutVals, 5728 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5729 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5730 const CallBase *CB) const { 5731 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5732 // of the 32-bit SVR4 ABI stack frame layout. 5733 5734 const CallingConv::ID CallConv = CFlags.CallConv; 5735 const bool IsVarArg = CFlags.IsVarArg; 5736 const bool IsTailCall = CFlags.IsTailCall; 5737 5738 assert((CallConv == CallingConv::C || 5739 CallConv == CallingConv::Cold || 5740 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5741 5742 const Align PtrAlign(4); 5743 5744 MachineFunction &MF = DAG.getMachineFunction(); 5745 5746 // Mark this function as potentially containing a function that contains a 5747 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5748 // and restoring the callers stack pointer in this functions epilog. This is 5749 // done because by tail calling the called function might overwrite the value 5750 // in this function's (MF) stack pointer stack slot 0(SP). 5751 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5752 CallConv == CallingConv::Fast) 5753 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5754 5755 // Count how many bytes are to be pushed on the stack, including the linkage 5756 // area, parameter list area and the part of the local variable space which 5757 // contains copies of aggregates which are passed by value. 5758 5759 // Assign locations to all of the outgoing arguments. 5760 SmallVector<CCValAssign, 16> ArgLocs; 5761 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5762 5763 // Reserve space for the linkage area on the stack. 5764 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5765 PtrAlign); 5766 if (useSoftFloat()) 5767 CCInfo.PreAnalyzeCallOperands(Outs); 5768 5769 if (IsVarArg) { 5770 // Handle fixed and variable vector arguments differently. 5771 // Fixed vector arguments go into registers as long as registers are 5772 // available. Variable vector arguments always go into memory. 5773 unsigned NumArgs = Outs.size(); 5774 5775 for (unsigned i = 0; i != NumArgs; ++i) { 5776 MVT ArgVT = Outs[i].VT; 5777 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5778 bool Result; 5779 5780 if (Outs[i].IsFixed) { 5781 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5782 CCInfo); 5783 } else { 5784 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5785 ArgFlags, CCInfo); 5786 } 5787 5788 if (Result) { 5789 #ifndef NDEBUG 5790 errs() << "Call operand #" << i << " has unhandled type " 5791 << EVT(ArgVT).getEVTString() << "\n"; 5792 #endif 5793 llvm_unreachable(nullptr); 5794 } 5795 } 5796 } else { 5797 // All arguments are treated the same. 5798 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5799 } 5800 CCInfo.clearWasPPCF128(); 5801 5802 // Assign locations to all of the outgoing aggregate by value arguments. 5803 SmallVector<CCValAssign, 16> ByValArgLocs; 5804 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5805 5806 // Reserve stack space for the allocations in CCInfo. 5807 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5808 5809 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5810 5811 // Size of the linkage area, parameter list area and the part of the local 5812 // space variable where copies of aggregates which are passed by value are 5813 // stored. 5814 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5815 5816 // Calculate by how many bytes the stack has to be adjusted in case of tail 5817 // call optimization. 5818 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5819 5820 // Adjust the stack pointer for the new arguments... 5821 // These operations are automatically eliminated by the prolog/epilog pass 5822 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5823 SDValue CallSeqStart = Chain; 5824 5825 // Load the return address and frame pointer so it can be moved somewhere else 5826 // later. 5827 SDValue LROp, FPOp; 5828 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5829 5830 // Set up a copy of the stack pointer for use loading and storing any 5831 // arguments that may not fit in the registers available for argument 5832 // passing. 5833 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5834 5835 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5836 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5837 SmallVector<SDValue, 8> MemOpChains; 5838 5839 bool seenFloatArg = false; 5840 // Walk the register/memloc assignments, inserting copies/loads. 5841 // i - Tracks the index into the list of registers allocated for the call 5842 // RealArgIdx - Tracks the index into the list of actual function arguments 5843 // j - Tracks the index into the list of byval arguments 5844 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5845 i != e; 5846 ++i, ++RealArgIdx) { 5847 CCValAssign &VA = ArgLocs[i]; 5848 SDValue Arg = OutVals[RealArgIdx]; 5849 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5850 5851 if (Flags.isByVal()) { 5852 // Argument is an aggregate which is passed by value, thus we need to 5853 // create a copy of it in the local variable space of the current stack 5854 // frame (which is the stack frame of the caller) and pass the address of 5855 // this copy to the callee. 5856 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5857 CCValAssign &ByValVA = ByValArgLocs[j++]; 5858 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5859 5860 // Memory reserved in the local variable space of the callers stack frame. 5861 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5862 5863 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5864 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5865 StackPtr, PtrOff); 5866 5867 // Create a copy of the argument in the local area of the current 5868 // stack frame. 5869 SDValue MemcpyCall = 5870 CreateCopyOfByValArgument(Arg, PtrOff, 5871 CallSeqStart.getNode()->getOperand(0), 5872 Flags, DAG, dl); 5873 5874 // This must go outside the CALLSEQ_START..END. 5875 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5876 SDLoc(MemcpyCall)); 5877 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5878 NewCallSeqStart.getNode()); 5879 Chain = CallSeqStart = NewCallSeqStart; 5880 5881 // Pass the address of the aggregate copy on the stack either in a 5882 // physical register or in the parameter list area of the current stack 5883 // frame to the callee. 5884 Arg = PtrOff; 5885 } 5886 5887 // When useCRBits() is true, there can be i1 arguments. 5888 // It is because getRegisterType(MVT::i1) => MVT::i1, 5889 // and for other integer types getRegisterType() => MVT::i32. 5890 // Extend i1 and ensure callee will get i32. 5891 if (Arg.getValueType() == MVT::i1) 5892 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5893 dl, MVT::i32, Arg); 5894 5895 if (VA.isRegLoc()) { 5896 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5897 // Put argument in a physical register. 5898 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5899 bool IsLE = Subtarget.isLittleEndian(); 5900 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5901 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5902 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5903 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5904 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5905 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5906 SVal.getValue(0))); 5907 } else 5908 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5909 } else { 5910 // Put argument in the parameter list area of the current stack frame. 5911 assert(VA.isMemLoc()); 5912 unsigned LocMemOffset = VA.getLocMemOffset(); 5913 5914 if (!IsTailCall) { 5915 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5916 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5917 StackPtr, PtrOff); 5918 5919 MemOpChains.push_back( 5920 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5921 } else { 5922 // Calculate and remember argument location. 5923 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5924 TailCallArguments); 5925 } 5926 } 5927 } 5928 5929 if (!MemOpChains.empty()) 5930 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5931 5932 // Build a sequence of copy-to-reg nodes chained together with token chain 5933 // and flag operands which copy the outgoing args into the appropriate regs. 5934 SDValue InFlag; 5935 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5936 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5937 RegsToPass[i].second, InFlag); 5938 InFlag = Chain.getValue(1); 5939 } 5940 5941 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5942 // registers. 5943 if (IsVarArg) { 5944 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5945 SDValue Ops[] = { Chain, InFlag }; 5946 5947 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5948 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5949 5950 InFlag = Chain.getValue(1); 5951 } 5952 5953 if (IsTailCall) 5954 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5955 TailCallArguments); 5956 5957 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5958 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5959 } 5960 5961 // Copy an argument into memory, being careful to do this outside the 5962 // call sequence for the call to which the argument belongs. 5963 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5964 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5965 SelectionDAG &DAG, const SDLoc &dl) const { 5966 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5967 CallSeqStart.getNode()->getOperand(0), 5968 Flags, DAG, dl); 5969 // The MEMCPY must go outside the CALLSEQ_START..END. 5970 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5971 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5972 SDLoc(MemcpyCall)); 5973 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5974 NewCallSeqStart.getNode()); 5975 return NewCallSeqStart; 5976 } 5977 5978 SDValue PPCTargetLowering::LowerCall_64SVR4( 5979 SDValue Chain, SDValue Callee, CallFlags CFlags, 5980 const SmallVectorImpl<ISD::OutputArg> &Outs, 5981 const SmallVectorImpl<SDValue> &OutVals, 5982 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5983 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5984 const CallBase *CB) const { 5985 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5986 bool isLittleEndian = Subtarget.isLittleEndian(); 5987 unsigned NumOps = Outs.size(); 5988 bool IsSibCall = false; 5989 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5990 5991 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5992 unsigned PtrByteSize = 8; 5993 5994 MachineFunction &MF = DAG.getMachineFunction(); 5995 5996 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5997 IsSibCall = true; 5998 5999 // Mark this function as potentially containing a function that contains a 6000 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6001 // and restoring the callers stack pointer in this functions epilog. This is 6002 // done because by tail calling the called function might overwrite the value 6003 // in this function's (MF) stack pointer stack slot 0(SP). 6004 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6005 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6006 6007 assert(!(IsFastCall && CFlags.IsVarArg) && 6008 "fastcc not supported on varargs functions"); 6009 6010 // Count how many bytes are to be pushed on the stack, including the linkage 6011 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6012 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6013 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6014 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6015 unsigned NumBytes = LinkageSize; 6016 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6017 unsigned &QFPR_idx = FPR_idx; 6018 6019 static const MCPhysReg GPR[] = { 6020 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6021 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6022 }; 6023 static const MCPhysReg VR[] = { 6024 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6025 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6026 }; 6027 6028 const unsigned NumGPRs = array_lengthof(GPR); 6029 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6030 const unsigned NumVRs = array_lengthof(VR); 6031 const unsigned NumQFPRs = NumFPRs; 6032 6033 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6034 // can be passed to the callee in registers. 6035 // For the fast calling convention, there is another check below. 6036 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6037 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6038 if (!HasParameterArea) { 6039 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6040 unsigned AvailableFPRs = NumFPRs; 6041 unsigned AvailableVRs = NumVRs; 6042 unsigned NumBytesTmp = NumBytes; 6043 for (unsigned i = 0; i != NumOps; ++i) { 6044 if (Outs[i].Flags.isNest()) continue; 6045 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6046 PtrByteSize, LinkageSize, ParamAreaSize, 6047 NumBytesTmp, AvailableFPRs, AvailableVRs, 6048 Subtarget.hasQPX())) 6049 HasParameterArea = true; 6050 } 6051 } 6052 6053 // When using the fast calling convention, we don't provide backing for 6054 // arguments that will be in registers. 6055 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6056 6057 // Avoid allocating parameter area for fastcc functions if all the arguments 6058 // can be passed in the registers. 6059 if (IsFastCall) 6060 HasParameterArea = false; 6061 6062 // Add up all the space actually used. 6063 for (unsigned i = 0; i != NumOps; ++i) { 6064 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6065 EVT ArgVT = Outs[i].VT; 6066 EVT OrigVT = Outs[i].ArgVT; 6067 6068 if (Flags.isNest()) 6069 continue; 6070 6071 if (IsFastCall) { 6072 if (Flags.isByVal()) { 6073 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6074 if (NumGPRsUsed > NumGPRs) 6075 HasParameterArea = true; 6076 } else { 6077 switch (ArgVT.getSimpleVT().SimpleTy) { 6078 default: llvm_unreachable("Unexpected ValueType for argument!"); 6079 case MVT::i1: 6080 case MVT::i32: 6081 case MVT::i64: 6082 if (++NumGPRsUsed <= NumGPRs) 6083 continue; 6084 break; 6085 case MVT::v4i32: 6086 case MVT::v8i16: 6087 case MVT::v16i8: 6088 case MVT::v2f64: 6089 case MVT::v2i64: 6090 case MVT::v1i128: 6091 case MVT::f128: 6092 if (++NumVRsUsed <= NumVRs) 6093 continue; 6094 break; 6095 case MVT::v4f32: 6096 // When using QPX, this is handled like a FP register, otherwise, it 6097 // is an Altivec register. 6098 if (Subtarget.hasQPX()) { 6099 if (++NumFPRsUsed <= NumFPRs) 6100 continue; 6101 } else { 6102 if (++NumVRsUsed <= NumVRs) 6103 continue; 6104 } 6105 break; 6106 case MVT::f32: 6107 case MVT::f64: 6108 case MVT::v4f64: // QPX 6109 case MVT::v4i1: // QPX 6110 if (++NumFPRsUsed <= NumFPRs) 6111 continue; 6112 break; 6113 } 6114 HasParameterArea = true; 6115 } 6116 } 6117 6118 /* Respect alignment of argument on the stack. */ 6119 auto Alignement = 6120 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6121 NumBytes = alignTo(NumBytes, Alignement); 6122 6123 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6124 if (Flags.isInConsecutiveRegsLast()) 6125 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6126 } 6127 6128 unsigned NumBytesActuallyUsed = NumBytes; 6129 6130 // In the old ELFv1 ABI, 6131 // the prolog code of the callee may store up to 8 GPR argument registers to 6132 // the stack, allowing va_start to index over them in memory if its varargs. 6133 // Because we cannot tell if this is needed on the caller side, we have to 6134 // conservatively assume that it is needed. As such, make sure we have at 6135 // least enough stack space for the caller to store the 8 GPRs. 6136 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6137 // really requires memory operands, e.g. a vararg function. 6138 if (HasParameterArea) 6139 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6140 else 6141 NumBytes = LinkageSize; 6142 6143 // Tail call needs the stack to be aligned. 6144 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6145 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6146 6147 int SPDiff = 0; 6148 6149 // Calculate by how many bytes the stack has to be adjusted in case of tail 6150 // call optimization. 6151 if (!IsSibCall) 6152 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6153 6154 // To protect arguments on the stack from being clobbered in a tail call, 6155 // force all the loads to happen before doing any other lowering. 6156 if (CFlags.IsTailCall) 6157 Chain = DAG.getStackArgumentTokenFactor(Chain); 6158 6159 // Adjust the stack pointer for the new arguments... 6160 // These operations are automatically eliminated by the prolog/epilog pass 6161 if (!IsSibCall) 6162 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6163 SDValue CallSeqStart = Chain; 6164 6165 // Load the return address and frame pointer so it can be move somewhere else 6166 // later. 6167 SDValue LROp, FPOp; 6168 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6169 6170 // Set up a copy of the stack pointer for use loading and storing any 6171 // arguments that may not fit in the registers available for argument 6172 // passing. 6173 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6174 6175 // Figure out which arguments are going to go in registers, and which in 6176 // memory. Also, if this is a vararg function, floating point operations 6177 // must be stored to our stack, and loaded into integer regs as well, if 6178 // any integer regs are available for argument passing. 6179 unsigned ArgOffset = LinkageSize; 6180 6181 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6182 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6183 6184 SmallVector<SDValue, 8> MemOpChains; 6185 for (unsigned i = 0; i != NumOps; ++i) { 6186 SDValue Arg = OutVals[i]; 6187 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6188 EVT ArgVT = Outs[i].VT; 6189 EVT OrigVT = Outs[i].ArgVT; 6190 6191 // PtrOff will be used to store the current argument to the stack if a 6192 // register cannot be found for it. 6193 SDValue PtrOff; 6194 6195 // We re-align the argument offset for each argument, except when using the 6196 // fast calling convention, when we need to make sure we do that only when 6197 // we'll actually use a stack slot. 6198 auto ComputePtrOff = [&]() { 6199 /* Respect alignment of argument on the stack. */ 6200 auto Alignment = 6201 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6202 ArgOffset = alignTo(ArgOffset, Alignment); 6203 6204 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6205 6206 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6207 }; 6208 6209 if (!IsFastCall) { 6210 ComputePtrOff(); 6211 6212 /* Compute GPR index associated with argument offset. */ 6213 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6214 GPR_idx = std::min(GPR_idx, NumGPRs); 6215 } 6216 6217 // Promote integers to 64-bit values. 6218 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6219 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6220 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6221 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6222 } 6223 6224 // FIXME memcpy is used way more than necessary. Correctness first. 6225 // Note: "by value" is code for passing a structure by value, not 6226 // basic types. 6227 if (Flags.isByVal()) { 6228 // Note: Size includes alignment padding, so 6229 // struct x { short a; char b; } 6230 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6231 // These are the proper values we need for right-justifying the 6232 // aggregate in a parameter register. 6233 unsigned Size = Flags.getByValSize(); 6234 6235 // An empty aggregate parameter takes up no storage and no 6236 // registers. 6237 if (Size == 0) 6238 continue; 6239 6240 if (IsFastCall) 6241 ComputePtrOff(); 6242 6243 // All aggregates smaller than 8 bytes must be passed right-justified. 6244 if (Size==1 || Size==2 || Size==4) { 6245 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6246 if (GPR_idx != NumGPRs) { 6247 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6248 MachinePointerInfo(), VT); 6249 MemOpChains.push_back(Load.getValue(1)); 6250 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6251 6252 ArgOffset += PtrByteSize; 6253 continue; 6254 } 6255 } 6256 6257 if (GPR_idx == NumGPRs && Size < 8) { 6258 SDValue AddPtr = PtrOff; 6259 if (!isLittleEndian) { 6260 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6261 PtrOff.getValueType()); 6262 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6263 } 6264 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6265 CallSeqStart, 6266 Flags, DAG, dl); 6267 ArgOffset += PtrByteSize; 6268 continue; 6269 } 6270 // Copy entire object into memory. There are cases where gcc-generated 6271 // code assumes it is there, even if it could be put entirely into 6272 // registers. (This is not what the doc says.) 6273 6274 // FIXME: The above statement is likely due to a misunderstanding of the 6275 // documents. All arguments must be copied into the parameter area BY 6276 // THE CALLEE in the event that the callee takes the address of any 6277 // formal argument. That has not yet been implemented. However, it is 6278 // reasonable to use the stack area as a staging area for the register 6279 // load. 6280 6281 // Skip this for small aggregates, as we will use the same slot for a 6282 // right-justified copy, below. 6283 if (Size >= 8) 6284 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6285 CallSeqStart, 6286 Flags, DAG, dl); 6287 6288 // When a register is available, pass a small aggregate right-justified. 6289 if (Size < 8 && GPR_idx != NumGPRs) { 6290 // The easiest way to get this right-justified in a register 6291 // is to copy the structure into the rightmost portion of a 6292 // local variable slot, then load the whole slot into the 6293 // register. 6294 // FIXME: The memcpy seems to produce pretty awful code for 6295 // small aggregates, particularly for packed ones. 6296 // FIXME: It would be preferable to use the slot in the 6297 // parameter save area instead of a new local variable. 6298 SDValue AddPtr = PtrOff; 6299 if (!isLittleEndian) { 6300 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6301 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6302 } 6303 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6304 CallSeqStart, 6305 Flags, DAG, dl); 6306 6307 // Load the slot into the register. 6308 SDValue Load = 6309 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6310 MemOpChains.push_back(Load.getValue(1)); 6311 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6312 6313 // Done with this argument. 6314 ArgOffset += PtrByteSize; 6315 continue; 6316 } 6317 6318 // For aggregates larger than PtrByteSize, copy the pieces of the 6319 // object that fit into registers from the parameter save area. 6320 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6321 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6322 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6323 if (GPR_idx != NumGPRs) { 6324 SDValue Load = 6325 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6326 MemOpChains.push_back(Load.getValue(1)); 6327 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6328 ArgOffset += PtrByteSize; 6329 } else { 6330 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6331 break; 6332 } 6333 } 6334 continue; 6335 } 6336 6337 switch (Arg.getSimpleValueType().SimpleTy) { 6338 default: llvm_unreachable("Unexpected ValueType for argument!"); 6339 case MVT::i1: 6340 case MVT::i32: 6341 case MVT::i64: 6342 if (Flags.isNest()) { 6343 // The 'nest' parameter, if any, is passed in R11. 6344 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6345 break; 6346 } 6347 6348 // These can be scalar arguments or elements of an integer array type 6349 // passed directly. Clang may use those instead of "byval" aggregate 6350 // types to avoid forcing arguments to memory unnecessarily. 6351 if (GPR_idx != NumGPRs) { 6352 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6353 } else { 6354 if (IsFastCall) 6355 ComputePtrOff(); 6356 6357 assert(HasParameterArea && 6358 "Parameter area must exist to pass an argument in memory."); 6359 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6360 true, CFlags.IsTailCall, false, MemOpChains, 6361 TailCallArguments, dl); 6362 if (IsFastCall) 6363 ArgOffset += PtrByteSize; 6364 } 6365 if (!IsFastCall) 6366 ArgOffset += PtrByteSize; 6367 break; 6368 case MVT::f32: 6369 case MVT::f64: { 6370 // These can be scalar arguments or elements of a float array type 6371 // passed directly. The latter are used to implement ELFv2 homogenous 6372 // float aggregates. 6373 6374 // Named arguments go into FPRs first, and once they overflow, the 6375 // remaining arguments go into GPRs and then the parameter save area. 6376 // Unnamed arguments for vararg functions always go to GPRs and 6377 // then the parameter save area. For now, put all arguments to vararg 6378 // routines always in both locations (FPR *and* GPR or stack slot). 6379 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6380 bool NeededLoad = false; 6381 6382 // First load the argument into the next available FPR. 6383 if (FPR_idx != NumFPRs) 6384 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6385 6386 // Next, load the argument into GPR or stack slot if needed. 6387 if (!NeedGPROrStack) 6388 ; 6389 else if (GPR_idx != NumGPRs && !IsFastCall) { 6390 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6391 // once we support fp <-> gpr moves. 6392 6393 // In the non-vararg case, this can only ever happen in the 6394 // presence of f32 array types, since otherwise we never run 6395 // out of FPRs before running out of GPRs. 6396 SDValue ArgVal; 6397 6398 // Double values are always passed in a single GPR. 6399 if (Arg.getValueType() != MVT::f32) { 6400 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6401 6402 // Non-array float values are extended and passed in a GPR. 6403 } else if (!Flags.isInConsecutiveRegs()) { 6404 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6405 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6406 6407 // If we have an array of floats, we collect every odd element 6408 // together with its predecessor into one GPR. 6409 } else if (ArgOffset % PtrByteSize != 0) { 6410 SDValue Lo, Hi; 6411 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6412 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6413 if (!isLittleEndian) 6414 std::swap(Lo, Hi); 6415 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6416 6417 // The final element, if even, goes into the first half of a GPR. 6418 } else if (Flags.isInConsecutiveRegsLast()) { 6419 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6420 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6421 if (!isLittleEndian) 6422 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6423 DAG.getConstant(32, dl, MVT::i32)); 6424 6425 // Non-final even elements are skipped; they will be handled 6426 // together the with subsequent argument on the next go-around. 6427 } else 6428 ArgVal = SDValue(); 6429 6430 if (ArgVal.getNode()) 6431 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6432 } else { 6433 if (IsFastCall) 6434 ComputePtrOff(); 6435 6436 // Single-precision floating-point values are mapped to the 6437 // second (rightmost) word of the stack doubleword. 6438 if (Arg.getValueType() == MVT::f32 && 6439 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6440 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6441 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6442 } 6443 6444 assert(HasParameterArea && 6445 "Parameter area must exist to pass an argument in memory."); 6446 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6447 true, CFlags.IsTailCall, false, MemOpChains, 6448 TailCallArguments, dl); 6449 6450 NeededLoad = true; 6451 } 6452 // When passing an array of floats, the array occupies consecutive 6453 // space in the argument area; only round up to the next doubleword 6454 // at the end of the array. Otherwise, each float takes 8 bytes. 6455 if (!IsFastCall || NeededLoad) { 6456 ArgOffset += (Arg.getValueType() == MVT::f32 && 6457 Flags.isInConsecutiveRegs()) ? 4 : 8; 6458 if (Flags.isInConsecutiveRegsLast()) 6459 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6460 } 6461 break; 6462 } 6463 case MVT::v4f32: 6464 case MVT::v4i32: 6465 case MVT::v8i16: 6466 case MVT::v16i8: 6467 case MVT::v2f64: 6468 case MVT::v2i64: 6469 case MVT::v1i128: 6470 case MVT::f128: 6471 if (!Subtarget.hasQPX()) { 6472 // These can be scalar arguments or elements of a vector array type 6473 // passed directly. The latter are used to implement ELFv2 homogenous 6474 // vector aggregates. 6475 6476 // For a varargs call, named arguments go into VRs or on the stack as 6477 // usual; unnamed arguments always go to the stack or the corresponding 6478 // GPRs when within range. For now, we always put the value in both 6479 // locations (or even all three). 6480 if (CFlags.IsVarArg) { 6481 assert(HasParameterArea && 6482 "Parameter area must exist if we have a varargs call."); 6483 // We could elide this store in the case where the object fits 6484 // entirely in R registers. Maybe later. 6485 SDValue Store = 6486 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6487 MemOpChains.push_back(Store); 6488 if (VR_idx != NumVRs) { 6489 SDValue Load = 6490 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6491 MemOpChains.push_back(Load.getValue(1)); 6492 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6493 } 6494 ArgOffset += 16; 6495 for (unsigned i=0; i<16; i+=PtrByteSize) { 6496 if (GPR_idx == NumGPRs) 6497 break; 6498 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6499 DAG.getConstant(i, dl, PtrVT)); 6500 SDValue Load = 6501 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6502 MemOpChains.push_back(Load.getValue(1)); 6503 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6504 } 6505 break; 6506 } 6507 6508 // Non-varargs Altivec params go into VRs or on the stack. 6509 if (VR_idx != NumVRs) { 6510 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6511 } else { 6512 if (IsFastCall) 6513 ComputePtrOff(); 6514 6515 assert(HasParameterArea && 6516 "Parameter area must exist to pass an argument in memory."); 6517 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6518 true, CFlags.IsTailCall, true, MemOpChains, 6519 TailCallArguments, dl); 6520 if (IsFastCall) 6521 ArgOffset += 16; 6522 } 6523 6524 if (!IsFastCall) 6525 ArgOffset += 16; 6526 break; 6527 } // not QPX 6528 6529 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6530 "Invalid QPX parameter type"); 6531 6532 LLVM_FALLTHROUGH; 6533 case MVT::v4f64: 6534 case MVT::v4i1: { 6535 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6536 if (CFlags.IsVarArg) { 6537 assert(HasParameterArea && 6538 "Parameter area must exist if we have a varargs call."); 6539 // We could elide this store in the case where the object fits 6540 // entirely in R registers. Maybe later. 6541 SDValue Store = 6542 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6543 MemOpChains.push_back(Store); 6544 if (QFPR_idx != NumQFPRs) { 6545 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6546 PtrOff, MachinePointerInfo()); 6547 MemOpChains.push_back(Load.getValue(1)); 6548 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6549 } 6550 ArgOffset += (IsF32 ? 16 : 32); 6551 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6552 if (GPR_idx == NumGPRs) 6553 break; 6554 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6555 DAG.getConstant(i, dl, PtrVT)); 6556 SDValue Load = 6557 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6558 MemOpChains.push_back(Load.getValue(1)); 6559 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6560 } 6561 break; 6562 } 6563 6564 // Non-varargs QPX params go into registers or on the stack. 6565 if (QFPR_idx != NumQFPRs) { 6566 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6567 } else { 6568 if (IsFastCall) 6569 ComputePtrOff(); 6570 6571 assert(HasParameterArea && 6572 "Parameter area must exist to pass an argument in memory."); 6573 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6574 true, CFlags.IsTailCall, true, MemOpChains, 6575 TailCallArguments, dl); 6576 if (IsFastCall) 6577 ArgOffset += (IsF32 ? 16 : 32); 6578 } 6579 6580 if (!IsFastCall) 6581 ArgOffset += (IsF32 ? 16 : 32); 6582 break; 6583 } 6584 } 6585 } 6586 6587 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6588 "mismatch in size of parameter area"); 6589 (void)NumBytesActuallyUsed; 6590 6591 if (!MemOpChains.empty()) 6592 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6593 6594 // Check if this is an indirect call (MTCTR/BCTRL). 6595 // See prepareDescriptorIndirectCall and buildCallOperands for more 6596 // information about calls through function pointers in the 64-bit SVR4 ABI. 6597 if (CFlags.IsIndirect) { 6598 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6599 // caller in the TOC save area. 6600 if (isTOCSaveRestoreRequired(Subtarget)) { 6601 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6602 // Load r2 into a virtual register and store it to the TOC save area. 6603 setUsesTOCBasePtr(DAG); 6604 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6605 // TOC save area offset. 6606 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6607 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6608 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6609 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6610 MachinePointerInfo::getStack( 6611 DAG.getMachineFunction(), TOCSaveOffset)); 6612 } 6613 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6614 // This does not mean the MTCTR instruction must use R12; it's easier 6615 // to model this as an extra parameter, so do that. 6616 if (isELFv2ABI && !CFlags.IsPatchPoint) 6617 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6618 } 6619 6620 // Build a sequence of copy-to-reg nodes chained together with token chain 6621 // and flag operands which copy the outgoing args into the appropriate regs. 6622 SDValue InFlag; 6623 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6624 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6625 RegsToPass[i].second, InFlag); 6626 InFlag = Chain.getValue(1); 6627 } 6628 6629 if (CFlags.IsTailCall && !IsSibCall) 6630 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6631 TailCallArguments); 6632 6633 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6634 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6635 } 6636 6637 SDValue PPCTargetLowering::LowerCall_Darwin( 6638 SDValue Chain, SDValue Callee, CallFlags CFlags, 6639 const SmallVectorImpl<ISD::OutputArg> &Outs, 6640 const SmallVectorImpl<SDValue> &OutVals, 6641 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6642 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6643 const CallBase *CB) const { 6644 unsigned NumOps = Outs.size(); 6645 6646 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6647 bool isPPC64 = PtrVT == MVT::i64; 6648 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6649 6650 MachineFunction &MF = DAG.getMachineFunction(); 6651 6652 // Mark this function as potentially containing a function that contains a 6653 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6654 // and restoring the callers stack pointer in this functions epilog. This is 6655 // done because by tail calling the called function might overwrite the value 6656 // in this function's (MF) stack pointer stack slot 0(SP). 6657 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6658 CFlags.CallConv == CallingConv::Fast) 6659 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6660 6661 // Count how many bytes are to be pushed on the stack, including the linkage 6662 // area, and parameter passing area. We start with 24/48 bytes, which is 6663 // prereserved space for [SP][CR][LR][3 x unused]. 6664 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6665 unsigned NumBytes = LinkageSize; 6666 6667 // Add up all the space actually used. 6668 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6669 // they all go in registers, but we must reserve stack space for them for 6670 // possible use by the caller. In varargs or 64-bit calls, parameters are 6671 // assigned stack space in order, with padding so Altivec parameters are 6672 // 16-byte aligned. 6673 unsigned nAltivecParamsAtEnd = 0; 6674 for (unsigned i = 0; i != NumOps; ++i) { 6675 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6676 EVT ArgVT = Outs[i].VT; 6677 // Varargs Altivec parameters are padded to a 16 byte boundary. 6678 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6679 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6680 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6681 if (!CFlags.IsVarArg && !isPPC64) { 6682 // Non-varargs Altivec parameters go after all the non-Altivec 6683 // parameters; handle those later so we know how much padding we need. 6684 nAltivecParamsAtEnd++; 6685 continue; 6686 } 6687 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6688 NumBytes = ((NumBytes+15)/16)*16; 6689 } 6690 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6691 } 6692 6693 // Allow for Altivec parameters at the end, if needed. 6694 if (nAltivecParamsAtEnd) { 6695 NumBytes = ((NumBytes+15)/16)*16; 6696 NumBytes += 16*nAltivecParamsAtEnd; 6697 } 6698 6699 // The prolog code of the callee may store up to 8 GPR argument registers to 6700 // the stack, allowing va_start to index over them in memory if its varargs. 6701 // Because we cannot tell if this is needed on the caller side, we have to 6702 // conservatively assume that it is needed. As such, make sure we have at 6703 // least enough stack space for the caller to store the 8 GPRs. 6704 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6705 6706 // Tail call needs the stack to be aligned. 6707 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6708 CFlags.CallConv == CallingConv::Fast) 6709 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6710 6711 // Calculate by how many bytes the stack has to be adjusted in case of tail 6712 // call optimization. 6713 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6714 6715 // To protect arguments on the stack from being clobbered in a tail call, 6716 // force all the loads to happen before doing any other lowering. 6717 if (CFlags.IsTailCall) 6718 Chain = DAG.getStackArgumentTokenFactor(Chain); 6719 6720 // Adjust the stack pointer for the new arguments... 6721 // These operations are automatically eliminated by the prolog/epilog pass 6722 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6723 SDValue CallSeqStart = Chain; 6724 6725 // Load the return address and frame pointer so it can be move somewhere else 6726 // later. 6727 SDValue LROp, FPOp; 6728 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6729 6730 // Set up a copy of the stack pointer for use loading and storing any 6731 // arguments that may not fit in the registers available for argument 6732 // passing. 6733 SDValue StackPtr; 6734 if (isPPC64) 6735 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6736 else 6737 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6738 6739 // Figure out which arguments are going to go in registers, and which in 6740 // memory. Also, if this is a vararg function, floating point operations 6741 // must be stored to our stack, and loaded into integer regs as well, if 6742 // any integer regs are available for argument passing. 6743 unsigned ArgOffset = LinkageSize; 6744 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6745 6746 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6747 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6748 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6749 }; 6750 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6751 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6752 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6753 }; 6754 static const MCPhysReg VR[] = { 6755 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6756 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6757 }; 6758 const unsigned NumGPRs = array_lengthof(GPR_32); 6759 const unsigned NumFPRs = 13; 6760 const unsigned NumVRs = array_lengthof(VR); 6761 6762 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6763 6764 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6765 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6766 6767 SmallVector<SDValue, 8> MemOpChains; 6768 for (unsigned i = 0; i != NumOps; ++i) { 6769 SDValue Arg = OutVals[i]; 6770 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6771 6772 // PtrOff will be used to store the current argument to the stack if a 6773 // register cannot be found for it. 6774 SDValue PtrOff; 6775 6776 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6777 6778 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6779 6780 // On PPC64, promote integers to 64-bit values. 6781 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6782 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6783 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6784 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6785 } 6786 6787 // FIXME memcpy is used way more than necessary. Correctness first. 6788 // Note: "by value" is code for passing a structure by value, not 6789 // basic types. 6790 if (Flags.isByVal()) { 6791 unsigned Size = Flags.getByValSize(); 6792 // Very small objects are passed right-justified. Everything else is 6793 // passed left-justified. 6794 if (Size==1 || Size==2) { 6795 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6796 if (GPR_idx != NumGPRs) { 6797 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6798 MachinePointerInfo(), VT); 6799 MemOpChains.push_back(Load.getValue(1)); 6800 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6801 6802 ArgOffset += PtrByteSize; 6803 } else { 6804 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6805 PtrOff.getValueType()); 6806 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6807 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6808 CallSeqStart, 6809 Flags, DAG, dl); 6810 ArgOffset += PtrByteSize; 6811 } 6812 continue; 6813 } 6814 // Copy entire object into memory. There are cases where gcc-generated 6815 // code assumes it is there, even if it could be put entirely into 6816 // registers. (This is not what the doc says.) 6817 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6818 CallSeqStart, 6819 Flags, DAG, dl); 6820 6821 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6822 // copy the pieces of the object that fit into registers from the 6823 // parameter save area. 6824 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6825 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6826 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6827 if (GPR_idx != NumGPRs) { 6828 SDValue Load = 6829 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6830 MemOpChains.push_back(Load.getValue(1)); 6831 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6832 ArgOffset += PtrByteSize; 6833 } else { 6834 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6835 break; 6836 } 6837 } 6838 continue; 6839 } 6840 6841 switch (Arg.getSimpleValueType().SimpleTy) { 6842 default: llvm_unreachable("Unexpected ValueType for argument!"); 6843 case MVT::i1: 6844 case MVT::i32: 6845 case MVT::i64: 6846 if (GPR_idx != NumGPRs) { 6847 if (Arg.getValueType() == MVT::i1) 6848 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6849 6850 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6851 } else { 6852 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6853 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6854 TailCallArguments, dl); 6855 } 6856 ArgOffset += PtrByteSize; 6857 break; 6858 case MVT::f32: 6859 case MVT::f64: 6860 if (FPR_idx != NumFPRs) { 6861 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6862 6863 if (CFlags.IsVarArg) { 6864 SDValue Store = 6865 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6866 MemOpChains.push_back(Store); 6867 6868 // Float varargs are always shadowed in available integer registers 6869 if (GPR_idx != NumGPRs) { 6870 SDValue Load = 6871 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6872 MemOpChains.push_back(Load.getValue(1)); 6873 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6874 } 6875 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6876 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6877 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6878 SDValue Load = 6879 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6880 MemOpChains.push_back(Load.getValue(1)); 6881 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6882 } 6883 } else { 6884 // If we have any FPRs remaining, we may also have GPRs remaining. 6885 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6886 // GPRs. 6887 if (GPR_idx != NumGPRs) 6888 ++GPR_idx; 6889 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6890 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6891 ++GPR_idx; 6892 } 6893 } else 6894 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6895 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6896 TailCallArguments, dl); 6897 if (isPPC64) 6898 ArgOffset += 8; 6899 else 6900 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6901 break; 6902 case MVT::v4f32: 6903 case MVT::v4i32: 6904 case MVT::v8i16: 6905 case MVT::v16i8: 6906 if (CFlags.IsVarArg) { 6907 // These go aligned on the stack, or in the corresponding R registers 6908 // when within range. The Darwin PPC ABI doc claims they also go in 6909 // V registers; in fact gcc does this only for arguments that are 6910 // prototyped, not for those that match the ... We do it for all 6911 // arguments, seems to work. 6912 while (ArgOffset % 16 !=0) { 6913 ArgOffset += PtrByteSize; 6914 if (GPR_idx != NumGPRs) 6915 GPR_idx++; 6916 } 6917 // We could elide this store in the case where the object fits 6918 // entirely in R registers. Maybe later. 6919 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6920 DAG.getConstant(ArgOffset, dl, PtrVT)); 6921 SDValue Store = 6922 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6923 MemOpChains.push_back(Store); 6924 if (VR_idx != NumVRs) { 6925 SDValue Load = 6926 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6927 MemOpChains.push_back(Load.getValue(1)); 6928 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6929 } 6930 ArgOffset += 16; 6931 for (unsigned i=0; i<16; i+=PtrByteSize) { 6932 if (GPR_idx == NumGPRs) 6933 break; 6934 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6935 DAG.getConstant(i, dl, PtrVT)); 6936 SDValue Load = 6937 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6938 MemOpChains.push_back(Load.getValue(1)); 6939 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6940 } 6941 break; 6942 } 6943 6944 // Non-varargs Altivec params generally go in registers, but have 6945 // stack space allocated at the end. 6946 if (VR_idx != NumVRs) { 6947 // Doesn't have GPR space allocated. 6948 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6949 } else if (nAltivecParamsAtEnd==0) { 6950 // We are emitting Altivec params in order. 6951 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6952 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6953 TailCallArguments, dl); 6954 ArgOffset += 16; 6955 } 6956 break; 6957 } 6958 } 6959 // If all Altivec parameters fit in registers, as they usually do, 6960 // they get stack space following the non-Altivec parameters. We 6961 // don't track this here because nobody below needs it. 6962 // If there are more Altivec parameters than fit in registers emit 6963 // the stores here. 6964 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6965 unsigned j = 0; 6966 // Offset is aligned; skip 1st 12 params which go in V registers. 6967 ArgOffset = ((ArgOffset+15)/16)*16; 6968 ArgOffset += 12*16; 6969 for (unsigned i = 0; i != NumOps; ++i) { 6970 SDValue Arg = OutVals[i]; 6971 EVT ArgType = Outs[i].VT; 6972 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6973 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6974 if (++j > NumVRs) { 6975 SDValue PtrOff; 6976 // We are emitting Altivec params in order. 6977 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6978 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6979 TailCallArguments, dl); 6980 ArgOffset += 16; 6981 } 6982 } 6983 } 6984 } 6985 6986 if (!MemOpChains.empty()) 6987 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6988 6989 // On Darwin, R12 must contain the address of an indirect callee. This does 6990 // not mean the MTCTR instruction must use R12; it's easier to model this as 6991 // an extra parameter, so do that. 6992 if (CFlags.IsIndirect) { 6993 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6994 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6995 PPC::R12), Callee)); 6996 } 6997 6998 // Build a sequence of copy-to-reg nodes chained together with token chain 6999 // and flag operands which copy the outgoing args into the appropriate regs. 7000 SDValue InFlag; 7001 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 7002 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 7003 RegsToPass[i].second, InFlag); 7004 InFlag = Chain.getValue(1); 7005 } 7006 7007 if (CFlags.IsTailCall) 7008 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 7009 TailCallArguments); 7010 7011 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7012 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7013 } 7014 7015 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 7016 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 7017 CCState &State) { 7018 7019 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 7020 State.getMachineFunction().getSubtarget()); 7021 const bool IsPPC64 = Subtarget.isPPC64(); 7022 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 7023 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 7024 7025 assert((!ValVT.isInteger() || 7026 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 7027 "Integer argument exceeds register size: should have been legalized"); 7028 7029 if (ValVT == MVT::f128) 7030 report_fatal_error("f128 is unimplemented on AIX."); 7031 7032 if (ArgFlags.isNest()) 7033 report_fatal_error("Nest arguments are unimplemented."); 7034 7035 if (ValVT.isVector() || LocVT.isVector()) 7036 report_fatal_error("Vector arguments are unimplemented on AIX."); 7037 7038 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7039 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7040 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7041 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7042 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7043 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7044 7045 if (ArgFlags.isByVal()) { 7046 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 7047 report_fatal_error("Pass-by-value arguments with alignment greater than " 7048 "register width are not supported."); 7049 7050 const unsigned ByValSize = ArgFlags.getByValSize(); 7051 7052 // An empty aggregate parameter takes up no storage and no registers, 7053 // but needs a MemLoc for a stack slot for the formal arguments side. 7054 if (ByValSize == 0) { 7055 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7056 State.getNextStackOffset(), RegVT, 7057 LocInfo)); 7058 return false; 7059 } 7060 7061 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 7062 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 7063 for (const unsigned E = Offset + StackSize; Offset < E; 7064 Offset += PtrAlign.value()) { 7065 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7066 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7067 else { 7068 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7069 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7070 LocInfo)); 7071 break; 7072 } 7073 } 7074 return false; 7075 } 7076 7077 // Arguments always reserve parameter save area. 7078 switch (ValVT.SimpleTy) { 7079 default: 7080 report_fatal_error("Unhandled value type for argument."); 7081 case MVT::i64: 7082 // i64 arguments should have been split to i32 for PPC32. 7083 assert(IsPPC64 && "PPC32 should have split i64 values."); 7084 LLVM_FALLTHROUGH; 7085 case MVT::i1: 7086 case MVT::i32: { 7087 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 7088 // AIX integer arguments are always passed in register width. 7089 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7090 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7091 : CCValAssign::LocInfo::ZExt; 7092 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7093 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7094 else 7095 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7096 7097 return false; 7098 } 7099 case MVT::f32: 7100 case MVT::f64: { 7101 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7102 const unsigned StoreSize = LocVT.getStoreSize(); 7103 // Floats are always 4-byte aligned in the PSA on AIX. 7104 // This includes f64 in 64-bit mode for ABI compatibility. 7105 const unsigned Offset = 7106 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 7107 unsigned FReg = State.AllocateReg(FPR); 7108 if (FReg) 7109 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7110 7111 // Reserve and initialize GPRs or initialize the PSA as required. 7112 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 7113 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7114 assert(FReg && "An FPR should be available when a GPR is reserved."); 7115 if (State.isVarArg()) { 7116 // Successfully reserved GPRs are only initialized for vararg calls. 7117 // Custom handling is required for: 7118 // f64 in PPC32 needs to be split into 2 GPRs. 7119 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7120 State.addLoc( 7121 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7122 } 7123 } else { 7124 // If there are insufficient GPRs, the PSA needs to be initialized. 7125 // Initialization occurs even if an FPR was initialized for 7126 // compatibility with the AIX XL compiler. The full memory for the 7127 // argument will be initialized even if a prior word is saved in GPR. 7128 // A custom memLoc is used when the argument also passes in FPR so 7129 // that the callee handling can skip over it easily. 7130 State.addLoc( 7131 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7132 LocInfo) 7133 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7134 break; 7135 } 7136 } 7137 7138 return false; 7139 } 7140 } 7141 return true; 7142 } 7143 7144 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7145 bool IsPPC64) { 7146 assert((IsPPC64 || SVT != MVT::i64) && 7147 "i64 should have been split for 32-bit codegen."); 7148 7149 switch (SVT) { 7150 default: 7151 report_fatal_error("Unexpected value type for formal argument"); 7152 case MVT::i1: 7153 case MVT::i32: 7154 case MVT::i64: 7155 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7156 case MVT::f32: 7157 return &PPC::F4RCRegClass; 7158 case MVT::f64: 7159 return &PPC::F8RCRegClass; 7160 } 7161 } 7162 7163 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7164 SelectionDAG &DAG, SDValue ArgValue, 7165 MVT LocVT, const SDLoc &dl) { 7166 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7167 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7168 7169 if (Flags.isSExt()) 7170 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7171 DAG.getValueType(ValVT)); 7172 else if (Flags.isZExt()) 7173 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7174 DAG.getValueType(ValVT)); 7175 7176 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7177 } 7178 7179 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7180 const unsigned LASize = FL->getLinkageSize(); 7181 7182 if (PPC::GPRCRegClass.contains(Reg)) { 7183 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7184 "Reg must be a valid argument register!"); 7185 return LASize + 4 * (Reg - PPC::R3); 7186 } 7187 7188 if (PPC::G8RCRegClass.contains(Reg)) { 7189 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7190 "Reg must be a valid argument register!"); 7191 return LASize + 8 * (Reg - PPC::X3); 7192 } 7193 7194 llvm_unreachable("Only general purpose registers expected."); 7195 } 7196 7197 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7198 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7199 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7200 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7201 7202 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7203 CallConv == CallingConv::Fast) && 7204 "Unexpected calling convention!"); 7205 7206 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7207 report_fatal_error("Tail call support is unimplemented on AIX."); 7208 7209 if (useSoftFloat()) 7210 report_fatal_error("Soft float support is unimplemented on AIX."); 7211 7212 const PPCSubtarget &Subtarget = 7213 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7214 if (Subtarget.hasQPX()) 7215 report_fatal_error("QPX support is not supported on AIX."); 7216 7217 const bool IsPPC64 = Subtarget.isPPC64(); 7218 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7219 7220 // Assign locations to all of the incoming arguments. 7221 SmallVector<CCValAssign, 16> ArgLocs; 7222 MachineFunction &MF = DAG.getMachineFunction(); 7223 MachineFrameInfo &MFI = MF.getFrameInfo(); 7224 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7225 7226 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7227 // Reserve space for the linkage area on the stack. 7228 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7229 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7230 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7231 7232 SmallVector<SDValue, 8> MemOps; 7233 7234 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7235 CCValAssign &VA = ArgLocs[I++]; 7236 MVT LocVT = VA.getLocVT(); 7237 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7238 7239 // For compatibility with the AIX XL compiler, the float args in the 7240 // parameter save area are initialized even if the argument is available 7241 // in register. The caller is required to initialize both the register 7242 // and memory, however, the callee can choose to expect it in either. 7243 // The memloc is dismissed here because the argument is retrieved from 7244 // the register. 7245 if (VA.isMemLoc() && VA.needsCustom()) 7246 continue; 7247 7248 if (Flags.isByVal() && VA.isMemLoc()) { 7249 const unsigned Size = 7250 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7251 PtrByteSize); 7252 const int FI = MF.getFrameInfo().CreateFixedObject( 7253 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7254 /* IsAliased */ true); 7255 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7256 InVals.push_back(FIN); 7257 7258 continue; 7259 } 7260 7261 if (Flags.isByVal()) { 7262 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7263 7264 const MCPhysReg ArgReg = VA.getLocReg(); 7265 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7266 7267 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7268 report_fatal_error("Over aligned byvals not supported yet."); 7269 7270 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7271 const int FI = MF.getFrameInfo().CreateFixedObject( 7272 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7273 /* IsAliased */ true); 7274 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7275 InVals.push_back(FIN); 7276 7277 // Add live ins for all the RegLocs for the same ByVal. 7278 const TargetRegisterClass *RegClass = 7279 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7280 7281 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7282 unsigned Offset) { 7283 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7284 // Since the callers side has left justified the aggregate in the 7285 // register, we can simply store the entire register into the stack 7286 // slot. 7287 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7288 // The store to the fixedstack object is needed becuase accessing a 7289 // field of the ByVal will use a gep and load. Ideally we will optimize 7290 // to extracting the value from the register directly, and elide the 7291 // stores when the arguments address is not taken, but that will need to 7292 // be future work. 7293 SDValue Store = 7294 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7295 DAG.getObjectPtrOffset(dl, FIN, Offset), 7296 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7297 7298 MemOps.push_back(Store); 7299 }; 7300 7301 unsigned Offset = 0; 7302 HandleRegLoc(VA.getLocReg(), Offset); 7303 Offset += PtrByteSize; 7304 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7305 Offset += PtrByteSize) { 7306 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7307 "RegLocs should be for ByVal argument."); 7308 7309 const CCValAssign RL = ArgLocs[I++]; 7310 HandleRegLoc(RL.getLocReg(), Offset); 7311 } 7312 7313 if (Offset != StackSize) { 7314 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7315 "Expected MemLoc for remaining bytes."); 7316 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7317 // Consume the MemLoc.The InVal has already been emitted, so nothing 7318 // more needs to be done. 7319 ++I; 7320 } 7321 7322 continue; 7323 } 7324 7325 EVT ValVT = VA.getValVT(); 7326 if (VA.isRegLoc() && !VA.needsCustom()) { 7327 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7328 unsigned VReg = 7329 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7330 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7331 if (ValVT.isScalarInteger() && 7332 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7333 ArgValue = 7334 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7335 } 7336 InVals.push_back(ArgValue); 7337 continue; 7338 } 7339 if (VA.isMemLoc()) { 7340 const unsigned LocSize = LocVT.getStoreSize(); 7341 const unsigned ValSize = ValVT.getStoreSize(); 7342 assert((ValSize <= LocSize) && 7343 "Object size is larger than size of MemLoc"); 7344 int CurArgOffset = VA.getLocMemOffset(); 7345 // Objects are right-justified because AIX is big-endian. 7346 if (LocSize > ValSize) 7347 CurArgOffset += LocSize - ValSize; 7348 // Potential tail calls could cause overwriting of argument stack slots. 7349 const bool IsImmutable = 7350 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7351 (CallConv == CallingConv::Fast)); 7352 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7353 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7354 SDValue ArgValue = 7355 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7356 InVals.push_back(ArgValue); 7357 continue; 7358 } 7359 } 7360 7361 // On AIX a minimum of 8 words is saved to the parameter save area. 7362 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7363 // Area that is at least reserved in the caller of this function. 7364 unsigned CallerReservedArea = 7365 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7366 7367 // Set the size that is at least reserved in caller of this function. Tail 7368 // call optimized function's reserved stack space needs to be aligned so 7369 // that taking the difference between two stack areas will result in an 7370 // aligned stack. 7371 CallerReservedArea = 7372 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7373 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7374 FuncInfo->setMinReservedArea(CallerReservedArea); 7375 7376 if (isVarArg) { 7377 FuncInfo->setVarArgsFrameIndex( 7378 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7379 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7380 7381 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7382 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7383 7384 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7385 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7386 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7387 7388 // The fixed integer arguments of a variadic function are stored to the 7389 // VarArgsFrameIndex on the stack so that they may be loaded by 7390 // dereferencing the result of va_next. 7391 for (unsigned GPRIndex = 7392 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7393 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7394 7395 const unsigned VReg = 7396 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7397 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7398 7399 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7400 SDValue Store = 7401 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7402 MemOps.push_back(Store); 7403 // Increment the address for the next argument to store. 7404 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7405 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7406 } 7407 } 7408 7409 if (!MemOps.empty()) 7410 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7411 7412 return Chain; 7413 } 7414 7415 SDValue PPCTargetLowering::LowerCall_AIX( 7416 SDValue Chain, SDValue Callee, CallFlags CFlags, 7417 const SmallVectorImpl<ISD::OutputArg> &Outs, 7418 const SmallVectorImpl<SDValue> &OutVals, 7419 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7420 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7421 const CallBase *CB) const { 7422 7423 assert((CFlags.CallConv == CallingConv::C || 7424 CFlags.CallConv == CallingConv::Cold || 7425 CFlags.CallConv == CallingConv::Fast) && 7426 "Unexpected calling convention!"); 7427 7428 if (CFlags.IsPatchPoint) 7429 report_fatal_error("This call type is unimplemented on AIX."); 7430 7431 const PPCSubtarget& Subtarget = 7432 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7433 if (Subtarget.hasQPX()) 7434 report_fatal_error("QPX is not supported on AIX."); 7435 if (Subtarget.hasAltivec()) 7436 report_fatal_error("Altivec support is unimplemented on AIX."); 7437 7438 MachineFunction &MF = DAG.getMachineFunction(); 7439 SmallVector<CCValAssign, 16> ArgLocs; 7440 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7441 *DAG.getContext()); 7442 7443 // Reserve space for the linkage save area (LSA) on the stack. 7444 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7445 // [SP][CR][LR][2 x reserved][TOC]. 7446 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7447 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7448 const bool IsPPC64 = Subtarget.isPPC64(); 7449 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7450 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7451 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7452 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7453 7454 // The prolog code of the callee may store up to 8 GPR argument registers to 7455 // the stack, allowing va_start to index over them in memory if the callee 7456 // is variadic. 7457 // Because we cannot tell if this is needed on the caller side, we have to 7458 // conservatively assume that it is needed. As such, make sure we have at 7459 // least enough stack space for the caller to store the 8 GPRs. 7460 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7461 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7462 CCInfo.getNextStackOffset()); 7463 7464 // Adjust the stack pointer for the new arguments... 7465 // These operations are automatically eliminated by the prolog/epilog pass. 7466 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7467 SDValue CallSeqStart = Chain; 7468 7469 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7470 SmallVector<SDValue, 8> MemOpChains; 7471 7472 // Set up a copy of the stack pointer for loading and storing any 7473 // arguments that may not fit in the registers available for argument 7474 // passing. 7475 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7476 : DAG.getRegister(PPC::R1, MVT::i32); 7477 7478 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7479 const unsigned ValNo = ArgLocs[I].getValNo(); 7480 SDValue Arg = OutVals[ValNo]; 7481 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7482 7483 if (Flags.isByVal()) { 7484 const unsigned ByValSize = Flags.getByValSize(); 7485 7486 // Nothing to do for zero-sized ByVals on the caller side. 7487 if (!ByValSize) { 7488 ++I; 7489 continue; 7490 } 7491 7492 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7493 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7494 (LoadOffset != 0) 7495 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7496 : Arg, 7497 MachinePointerInfo(), VT); 7498 }; 7499 7500 unsigned LoadOffset = 0; 7501 7502 // Initialize registers, which are fully occupied by the by-val argument. 7503 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7504 SDValue Load = GetLoad(PtrVT, LoadOffset); 7505 MemOpChains.push_back(Load.getValue(1)); 7506 LoadOffset += PtrByteSize; 7507 const CCValAssign &ByValVA = ArgLocs[I++]; 7508 assert(ByValVA.getValNo() == ValNo && 7509 "Unexpected location for pass-by-value argument."); 7510 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7511 } 7512 7513 if (LoadOffset == ByValSize) 7514 continue; 7515 7516 // There must be one more loc to handle the remainder. 7517 assert(ArgLocs[I].getValNo() == ValNo && 7518 "Expected additional location for by-value argument."); 7519 7520 if (ArgLocs[I].isMemLoc()) { 7521 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7522 const CCValAssign &ByValVA = ArgLocs[I++]; 7523 ISD::ArgFlagsTy MemcpyFlags = Flags; 7524 // Only memcpy the bytes that don't pass in register. 7525 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7526 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7527 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7528 : Arg, 7529 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7530 CallSeqStart, MemcpyFlags, DAG, dl); 7531 continue; 7532 } 7533 7534 // Initialize the final register residue. 7535 // Any residue that occupies the final by-val arg register must be 7536 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7537 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7538 // 2 and 1 byte loads. 7539 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7540 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7541 "Unexpected register residue for by-value argument."); 7542 SDValue ResidueVal; 7543 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7544 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7545 const MVT VT = 7546 N == 1 ? MVT::i8 7547 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7548 SDValue Load = GetLoad(VT, LoadOffset); 7549 MemOpChains.push_back(Load.getValue(1)); 7550 LoadOffset += N; 7551 Bytes += N; 7552 7553 // By-val arguments are passed left-justfied in register. 7554 // Every load here needs to be shifted, otherwise a full register load 7555 // should have been used. 7556 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7557 "Unexpected load emitted during handling of pass-by-value " 7558 "argument."); 7559 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7560 EVT ShiftAmountTy = 7561 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7562 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7563 SDValue ShiftedLoad = 7564 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7565 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7566 ShiftedLoad) 7567 : ShiftedLoad; 7568 } 7569 7570 const CCValAssign &ByValVA = ArgLocs[I++]; 7571 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7572 continue; 7573 } 7574 7575 CCValAssign &VA = ArgLocs[I++]; 7576 const MVT LocVT = VA.getLocVT(); 7577 const MVT ValVT = VA.getValVT(); 7578 7579 switch (VA.getLocInfo()) { 7580 default: 7581 report_fatal_error("Unexpected argument extension type."); 7582 case CCValAssign::Full: 7583 break; 7584 case CCValAssign::ZExt: 7585 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7586 break; 7587 case CCValAssign::SExt: 7588 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7589 break; 7590 } 7591 7592 if (VA.isRegLoc() && !VA.needsCustom()) { 7593 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7594 continue; 7595 } 7596 7597 if (VA.isMemLoc()) { 7598 SDValue PtrOff = 7599 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7600 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7601 MemOpChains.push_back( 7602 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7603 7604 continue; 7605 } 7606 7607 // Custom handling is used for GPR initializations for vararg float 7608 // arguments. 7609 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7610 ValVT.isFloatingPoint() && LocVT.isInteger() && 7611 "Unexpected register handling for calling convention."); 7612 7613 SDValue ArgAsInt = 7614 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7615 7616 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7617 // f32 in 32-bit GPR 7618 // f64 in 64-bit GPR 7619 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7620 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7621 // f32 in 64-bit GPR. 7622 RegsToPass.push_back(std::make_pair( 7623 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7624 else { 7625 // f64 in two 32-bit GPRs 7626 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7627 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7628 "Unexpected custom register for argument!"); 7629 CCValAssign &GPR1 = VA; 7630 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7631 DAG.getConstant(32, dl, MVT::i8)); 7632 RegsToPass.push_back(std::make_pair( 7633 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7634 7635 if (I != E) { 7636 // If only 1 GPR was available, there will only be one custom GPR and 7637 // the argument will also pass in memory. 7638 CCValAssign &PeekArg = ArgLocs[I]; 7639 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7640 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7641 CCValAssign &GPR2 = ArgLocs[I++]; 7642 RegsToPass.push_back(std::make_pair( 7643 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7644 } 7645 } 7646 } 7647 } 7648 7649 if (!MemOpChains.empty()) 7650 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7651 7652 // For indirect calls, we need to save the TOC base to the stack for 7653 // restoration after the call. 7654 if (CFlags.IsIndirect) { 7655 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7656 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7657 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7658 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7659 const unsigned TOCSaveOffset = 7660 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7661 7662 setUsesTOCBasePtr(DAG); 7663 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7664 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7665 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7666 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7667 Chain = DAG.getStore( 7668 Val.getValue(1), dl, Val, AddPtr, 7669 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7670 } 7671 7672 // Build a sequence of copy-to-reg nodes chained together with token chain 7673 // and flag operands which copy the outgoing args into the appropriate regs. 7674 SDValue InFlag; 7675 for (auto Reg : RegsToPass) { 7676 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7677 InFlag = Chain.getValue(1); 7678 } 7679 7680 const int SPDiff = 0; 7681 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7682 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7683 } 7684 7685 bool 7686 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7687 MachineFunction &MF, bool isVarArg, 7688 const SmallVectorImpl<ISD::OutputArg> &Outs, 7689 LLVMContext &Context) const { 7690 SmallVector<CCValAssign, 16> RVLocs; 7691 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7692 return CCInfo.CheckReturn( 7693 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7694 ? RetCC_PPC_Cold 7695 : RetCC_PPC); 7696 } 7697 7698 SDValue 7699 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7700 bool isVarArg, 7701 const SmallVectorImpl<ISD::OutputArg> &Outs, 7702 const SmallVectorImpl<SDValue> &OutVals, 7703 const SDLoc &dl, SelectionDAG &DAG) const { 7704 SmallVector<CCValAssign, 16> RVLocs; 7705 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7706 *DAG.getContext()); 7707 CCInfo.AnalyzeReturn(Outs, 7708 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7709 ? RetCC_PPC_Cold 7710 : RetCC_PPC); 7711 7712 SDValue Flag; 7713 SmallVector<SDValue, 4> RetOps(1, Chain); 7714 7715 // Copy the result values into the output registers. 7716 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7717 CCValAssign &VA = RVLocs[i]; 7718 assert(VA.isRegLoc() && "Can only return in registers!"); 7719 7720 SDValue Arg = OutVals[RealResIdx]; 7721 7722 switch (VA.getLocInfo()) { 7723 default: llvm_unreachable("Unknown loc info!"); 7724 case CCValAssign::Full: break; 7725 case CCValAssign::AExt: 7726 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7727 break; 7728 case CCValAssign::ZExt: 7729 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7730 break; 7731 case CCValAssign::SExt: 7732 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7733 break; 7734 } 7735 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7736 bool isLittleEndian = Subtarget.isLittleEndian(); 7737 // Legalize ret f64 -> ret 2 x i32. 7738 SDValue SVal = 7739 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7740 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7741 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7742 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7743 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7744 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7745 Flag = Chain.getValue(1); 7746 VA = RVLocs[++i]; // skip ahead to next loc 7747 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7748 } else 7749 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7750 Flag = Chain.getValue(1); 7751 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7752 } 7753 7754 RetOps[0] = Chain; // Update chain. 7755 7756 // Add the flag if we have it. 7757 if (Flag.getNode()) 7758 RetOps.push_back(Flag); 7759 7760 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7761 } 7762 7763 SDValue 7764 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7765 SelectionDAG &DAG) const { 7766 SDLoc dl(Op); 7767 7768 // Get the correct type for integers. 7769 EVT IntVT = Op.getValueType(); 7770 7771 // Get the inputs. 7772 SDValue Chain = Op.getOperand(0); 7773 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7774 // Build a DYNAREAOFFSET node. 7775 SDValue Ops[2] = {Chain, FPSIdx}; 7776 SDVTList VTs = DAG.getVTList(IntVT); 7777 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7778 } 7779 7780 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7781 SelectionDAG &DAG) const { 7782 // When we pop the dynamic allocation we need to restore the SP link. 7783 SDLoc dl(Op); 7784 7785 // Get the correct type for pointers. 7786 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7787 7788 // Construct the stack pointer operand. 7789 bool isPPC64 = Subtarget.isPPC64(); 7790 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7791 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7792 7793 // Get the operands for the STACKRESTORE. 7794 SDValue Chain = Op.getOperand(0); 7795 SDValue SaveSP = Op.getOperand(1); 7796 7797 // Load the old link SP. 7798 SDValue LoadLinkSP = 7799 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7800 7801 // Restore the stack pointer. 7802 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7803 7804 // Store the old link SP. 7805 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7806 } 7807 7808 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7809 MachineFunction &MF = DAG.getMachineFunction(); 7810 bool isPPC64 = Subtarget.isPPC64(); 7811 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7812 7813 // Get current frame pointer save index. The users of this index will be 7814 // primarily DYNALLOC instructions. 7815 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7816 int RASI = FI->getReturnAddrSaveIndex(); 7817 7818 // If the frame pointer save index hasn't been defined yet. 7819 if (!RASI) { 7820 // Find out what the fix offset of the frame pointer save area. 7821 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7822 // Allocate the frame index for frame pointer save area. 7823 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7824 // Save the result. 7825 FI->setReturnAddrSaveIndex(RASI); 7826 } 7827 return DAG.getFrameIndex(RASI, PtrVT); 7828 } 7829 7830 SDValue 7831 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7832 MachineFunction &MF = DAG.getMachineFunction(); 7833 bool isPPC64 = Subtarget.isPPC64(); 7834 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7835 7836 // Get current frame pointer save index. The users of this index will be 7837 // primarily DYNALLOC instructions. 7838 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7839 int FPSI = FI->getFramePointerSaveIndex(); 7840 7841 // If the frame pointer save index hasn't been defined yet. 7842 if (!FPSI) { 7843 // Find out what the fix offset of the frame pointer save area. 7844 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7845 // Allocate the frame index for frame pointer save area. 7846 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7847 // Save the result. 7848 FI->setFramePointerSaveIndex(FPSI); 7849 } 7850 return DAG.getFrameIndex(FPSI, PtrVT); 7851 } 7852 7853 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7854 SelectionDAG &DAG) const { 7855 // Get the inputs. 7856 SDValue Chain = Op.getOperand(0); 7857 SDValue Size = Op.getOperand(1); 7858 SDLoc dl(Op); 7859 7860 // Get the correct type for pointers. 7861 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7862 // Negate the size. 7863 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7864 DAG.getConstant(0, dl, PtrVT), Size); 7865 // Construct a node for the frame pointer save index. 7866 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7867 // Build a DYNALLOC node. 7868 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7869 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7870 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7871 } 7872 7873 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7874 SelectionDAG &DAG) const { 7875 MachineFunction &MF = DAG.getMachineFunction(); 7876 7877 bool isPPC64 = Subtarget.isPPC64(); 7878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7879 7880 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7881 return DAG.getFrameIndex(FI, PtrVT); 7882 } 7883 7884 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7885 SelectionDAG &DAG) const { 7886 SDLoc DL(Op); 7887 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7888 DAG.getVTList(MVT::i32, MVT::Other), 7889 Op.getOperand(0), Op.getOperand(1)); 7890 } 7891 7892 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7893 SelectionDAG &DAG) const { 7894 SDLoc DL(Op); 7895 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7896 Op.getOperand(0), Op.getOperand(1)); 7897 } 7898 7899 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7900 if (Op.getValueType().isVector()) 7901 return LowerVectorLoad(Op, DAG); 7902 7903 assert(Op.getValueType() == MVT::i1 && 7904 "Custom lowering only for i1 loads"); 7905 7906 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7907 7908 SDLoc dl(Op); 7909 LoadSDNode *LD = cast<LoadSDNode>(Op); 7910 7911 SDValue Chain = LD->getChain(); 7912 SDValue BasePtr = LD->getBasePtr(); 7913 MachineMemOperand *MMO = LD->getMemOperand(); 7914 7915 SDValue NewLD = 7916 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7917 BasePtr, MVT::i8, MMO); 7918 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7919 7920 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7921 return DAG.getMergeValues(Ops, dl); 7922 } 7923 7924 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7925 if (Op.getOperand(1).getValueType().isVector()) 7926 return LowerVectorStore(Op, DAG); 7927 7928 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7929 "Custom lowering only for i1 stores"); 7930 7931 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7932 7933 SDLoc dl(Op); 7934 StoreSDNode *ST = cast<StoreSDNode>(Op); 7935 7936 SDValue Chain = ST->getChain(); 7937 SDValue BasePtr = ST->getBasePtr(); 7938 SDValue Value = ST->getValue(); 7939 MachineMemOperand *MMO = ST->getMemOperand(); 7940 7941 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7942 Value); 7943 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7944 } 7945 7946 // FIXME: Remove this once the ANDI glue bug is fixed: 7947 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7948 assert(Op.getValueType() == MVT::i1 && 7949 "Custom lowering only for i1 results"); 7950 7951 SDLoc DL(Op); 7952 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7953 } 7954 7955 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7956 SelectionDAG &DAG) const { 7957 7958 // Implements a vector truncate that fits in a vector register as a shuffle. 7959 // We want to legalize vector truncates down to where the source fits in 7960 // a vector register (and target is therefore smaller than vector register 7961 // size). At that point legalization will try to custom lower the sub-legal 7962 // result and get here - where we can contain the truncate as a single target 7963 // operation. 7964 7965 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7966 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7967 // 7968 // We will implement it for big-endian ordering as this (where x denotes 7969 // undefined): 7970 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7971 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7972 // 7973 // The same operation in little-endian ordering will be: 7974 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7975 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7976 7977 assert(Op.getValueType().isVector() && "Vector type expected."); 7978 7979 SDLoc DL(Op); 7980 SDValue N1 = Op.getOperand(0); 7981 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7982 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7983 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7984 7985 EVT TrgVT = Op.getValueType(); 7986 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7987 EVT EltVT = TrgVT.getVectorElementType(); 7988 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7989 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7990 7991 // First list the elements we want to keep. 7992 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7993 SmallVector<int, 16> ShuffV; 7994 if (Subtarget.isLittleEndian()) 7995 for (unsigned i = 0; i < TrgNumElts; ++i) 7996 ShuffV.push_back(i * SizeMult); 7997 else 7998 for (unsigned i = 1; i <= TrgNumElts; ++i) 7999 ShuffV.push_back(i * SizeMult - 1); 8000 8001 // Populate the remaining elements with undefs. 8002 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 8003 // ShuffV.push_back(i + WideNumElts); 8004 ShuffV.push_back(WideNumElts + 1); 8005 8006 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 8007 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 8008 } 8009 8010 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 8011 /// possible. 8012 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 8013 // Not FP? Not a fsel. 8014 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 8015 !Op.getOperand(2).getValueType().isFloatingPoint()) 8016 return Op; 8017 8018 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 8019 8020 EVT ResVT = Op.getValueType(); 8021 EVT CmpVT = Op.getOperand(0).getValueType(); 8022 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8023 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 8024 SDLoc dl(Op); 8025 SDNodeFlags Flags = Op.getNode()->getFlags(); 8026 8027 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 8028 // presence of infinities. 8029 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 8030 switch (CC) { 8031 default: 8032 break; 8033 case ISD::SETOGT: 8034 case ISD::SETGT: 8035 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8036 case ISD::SETOLT: 8037 case ISD::SETLT: 8038 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8039 } 8040 } 8041 8042 // We might be able to do better than this under some circumstances, but in 8043 // general, fsel-based lowering of select is a finite-math-only optimization. 8044 // For more information, see section F.3 of the 2.06 ISA specification. 8045 // With ISA 3.0 8046 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8047 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8048 return Op; 8049 8050 // If the RHS of the comparison is a 0.0, we don't need to do the 8051 // subtraction at all. 8052 SDValue Sel1; 8053 if (isFloatingPointZero(RHS)) 8054 switch (CC) { 8055 default: break; // SETUO etc aren't handled by fsel. 8056 case ISD::SETNE: 8057 std::swap(TV, FV); 8058 LLVM_FALLTHROUGH; 8059 case ISD::SETEQ: 8060 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8061 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8062 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8063 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8064 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8065 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8066 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8067 case ISD::SETULT: 8068 case ISD::SETLT: 8069 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8070 LLVM_FALLTHROUGH; 8071 case ISD::SETOGE: 8072 case ISD::SETGE: 8073 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8074 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8075 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8076 case ISD::SETUGT: 8077 case ISD::SETGT: 8078 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8079 LLVM_FALLTHROUGH; 8080 case ISD::SETOLE: 8081 case ISD::SETLE: 8082 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8083 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8084 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8085 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8086 } 8087 8088 SDValue Cmp; 8089 switch (CC) { 8090 default: break; // SETUO etc aren't handled by fsel. 8091 case ISD::SETNE: 8092 std::swap(TV, FV); 8093 LLVM_FALLTHROUGH; 8094 case ISD::SETEQ: 8095 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8096 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8097 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8098 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8099 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8100 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8101 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8102 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8103 case ISD::SETULT: 8104 case ISD::SETLT: 8105 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8106 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8107 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8108 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8109 case ISD::SETOGE: 8110 case ISD::SETGE: 8111 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8112 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8113 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8114 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8115 case ISD::SETUGT: 8116 case ISD::SETGT: 8117 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8118 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8119 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8120 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8121 case ISD::SETOLE: 8122 case ISD::SETLE: 8123 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8124 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8125 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8126 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8127 } 8128 return Op; 8129 } 8130 8131 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8132 SelectionDAG &DAG, 8133 const SDLoc &dl) const { 8134 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8135 SDValue Src = Op.getOperand(0); 8136 if (Src.getValueType() == MVT::f32) 8137 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8138 8139 SDValue Tmp; 8140 switch (Op.getSimpleValueType().SimpleTy) { 8141 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8142 case MVT::i32: 8143 Tmp = DAG.getNode( 8144 Op.getOpcode() == ISD::FP_TO_SINT 8145 ? PPCISD::FCTIWZ 8146 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8147 dl, MVT::f64, Src); 8148 break; 8149 case MVT::i64: 8150 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8151 "i64 FP_TO_UINT is supported only with FPCVT"); 8152 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8153 PPCISD::FCTIDUZ, 8154 dl, MVT::f64, Src); 8155 break; 8156 } 8157 8158 // Convert the FP value to an int value through memory. 8159 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8160 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8161 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8162 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8163 MachinePointerInfo MPI = 8164 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8165 8166 // Emit a store to the stack slot. 8167 SDValue Chain; 8168 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8169 if (i32Stack) { 8170 MachineFunction &MF = DAG.getMachineFunction(); 8171 Alignment = Align(4); 8172 MachineMemOperand *MMO = 8173 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8174 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8175 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8176 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8177 } else 8178 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8179 8180 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8181 // add in a bias on big endian. 8182 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8183 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8184 DAG.getConstant(4, dl, FIPtr.getValueType())); 8185 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8186 } 8187 8188 RLI.Chain = Chain; 8189 RLI.Ptr = FIPtr; 8190 RLI.MPI = MPI; 8191 RLI.Alignment = Alignment; 8192 } 8193 8194 /// Custom lowers floating point to integer conversions to use 8195 /// the direct move instructions available in ISA 2.07 to avoid the 8196 /// need for load/store combinations. 8197 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8198 SelectionDAG &DAG, 8199 const SDLoc &dl) const { 8200 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8201 SDValue Src = Op.getOperand(0); 8202 8203 if (Src.getValueType() == MVT::f32) 8204 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8205 8206 SDValue Tmp; 8207 switch (Op.getSimpleValueType().SimpleTy) { 8208 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8209 case MVT::i32: 8210 Tmp = DAG.getNode( 8211 Op.getOpcode() == ISD::FP_TO_SINT 8212 ? PPCISD::FCTIWZ 8213 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8214 dl, MVT::f64, Src); 8215 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8216 break; 8217 case MVT::i64: 8218 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8219 "i64 FP_TO_UINT is supported only with FPCVT"); 8220 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8221 PPCISD::FCTIDUZ, 8222 dl, MVT::f64, Src); 8223 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8224 break; 8225 } 8226 return Tmp; 8227 } 8228 8229 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8230 const SDLoc &dl) const { 8231 8232 // FP to INT conversions are legal for f128. 8233 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8234 return Op; 8235 8236 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8237 // PPC (the libcall is not available). 8238 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8239 if (Op.getValueType() == MVT::i32) { 8240 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8241 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8242 MVT::f64, Op.getOperand(0), 8243 DAG.getIntPtrConstant(0, dl)); 8244 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8245 MVT::f64, Op.getOperand(0), 8246 DAG.getIntPtrConstant(1, dl)); 8247 8248 // Add the two halves of the long double in round-to-zero mode. 8249 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8250 8251 // Now use a smaller FP_TO_SINT. 8252 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8253 } 8254 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8255 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8256 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8257 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8258 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8259 // FIXME: generated code sucks. 8260 // TODO: Are there fast-math-flags to propagate to this FSUB? 8261 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8262 Op.getOperand(0), Tmp); 8263 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8264 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8265 DAG.getConstant(0x80000000, dl, MVT::i32)); 8266 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8267 Op.getOperand(0)); 8268 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8269 ISD::SETGE); 8270 } 8271 } 8272 8273 return SDValue(); 8274 } 8275 8276 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8277 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8278 8279 ReuseLoadInfo RLI; 8280 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8281 8282 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8283 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8284 } 8285 8286 // We're trying to insert a regular store, S, and then a load, L. If the 8287 // incoming value, O, is a load, we might just be able to have our load use the 8288 // address used by O. However, we don't know if anything else will store to 8289 // that address before we can load from it. To prevent this situation, we need 8290 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8291 // the same chain operand as O, we create a token factor from the chain results 8292 // of O and L, and we replace all uses of O's chain result with that token 8293 // factor (see spliceIntoChain below for this last part). 8294 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8295 ReuseLoadInfo &RLI, 8296 SelectionDAG &DAG, 8297 ISD::LoadExtType ET) const { 8298 SDLoc dl(Op); 8299 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8300 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8301 if (ET == ISD::NON_EXTLOAD && 8302 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8303 isOperationLegalOrCustom(Op.getOpcode(), 8304 Op.getOperand(0).getValueType())) { 8305 8306 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8307 return true; 8308 } 8309 8310 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8311 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8312 LD->isNonTemporal()) 8313 return false; 8314 if (LD->getMemoryVT() != MemVT) 8315 return false; 8316 8317 RLI.Ptr = LD->getBasePtr(); 8318 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8319 assert(LD->getAddressingMode() == ISD::PRE_INC && 8320 "Non-pre-inc AM on PPC?"); 8321 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8322 LD->getOffset()); 8323 } 8324 8325 RLI.Chain = LD->getChain(); 8326 RLI.MPI = LD->getPointerInfo(); 8327 RLI.IsDereferenceable = LD->isDereferenceable(); 8328 RLI.IsInvariant = LD->isInvariant(); 8329 RLI.Alignment = LD->getAlign(); 8330 RLI.AAInfo = LD->getAAInfo(); 8331 RLI.Ranges = LD->getRanges(); 8332 8333 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8334 return true; 8335 } 8336 8337 // Given the head of the old chain, ResChain, insert a token factor containing 8338 // it and NewResChain, and make users of ResChain now be users of that token 8339 // factor. 8340 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8341 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8342 SDValue NewResChain, 8343 SelectionDAG &DAG) const { 8344 if (!ResChain) 8345 return; 8346 8347 SDLoc dl(NewResChain); 8348 8349 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8350 NewResChain, DAG.getUNDEF(MVT::Other)); 8351 assert(TF.getNode() != NewResChain.getNode() && 8352 "A new TF really is required here"); 8353 8354 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8355 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8356 } 8357 8358 /// Analyze profitability of direct move 8359 /// prefer float load to int load plus direct move 8360 /// when there is no integer use of int load 8361 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8362 SDNode *Origin = Op.getOperand(0).getNode(); 8363 if (Origin->getOpcode() != ISD::LOAD) 8364 return true; 8365 8366 // If there is no LXSIBZX/LXSIHZX, like Power8, 8367 // prefer direct move if the memory size is 1 or 2 bytes. 8368 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8369 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8370 return true; 8371 8372 for (SDNode::use_iterator UI = Origin->use_begin(), 8373 UE = Origin->use_end(); 8374 UI != UE; ++UI) { 8375 8376 // Only look at the users of the loaded value. 8377 if (UI.getUse().get().getResNo() != 0) 8378 continue; 8379 8380 if (UI->getOpcode() != ISD::SINT_TO_FP && 8381 UI->getOpcode() != ISD::UINT_TO_FP) 8382 return true; 8383 } 8384 8385 return false; 8386 } 8387 8388 /// Custom lowers integer to floating point conversions to use 8389 /// the direct move instructions available in ISA 2.07 to avoid the 8390 /// need for load/store combinations. 8391 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8392 SelectionDAG &DAG, 8393 const SDLoc &dl) const { 8394 assert((Op.getValueType() == MVT::f32 || 8395 Op.getValueType() == MVT::f64) && 8396 "Invalid floating point type as target of conversion"); 8397 assert(Subtarget.hasFPCVT() && 8398 "Int to FP conversions with direct moves require FPCVT"); 8399 SDValue FP; 8400 SDValue Src = Op.getOperand(0); 8401 bool SinglePrec = Op.getValueType() == MVT::f32; 8402 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8403 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8404 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8405 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8406 8407 if (WordInt) { 8408 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8409 dl, MVT::f64, Src); 8410 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8411 } 8412 else { 8413 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8414 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8415 } 8416 8417 return FP; 8418 } 8419 8420 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8421 8422 EVT VecVT = Vec.getValueType(); 8423 assert(VecVT.isVector() && "Expected a vector type."); 8424 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8425 8426 EVT EltVT = VecVT.getVectorElementType(); 8427 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8428 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8429 8430 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8431 SmallVector<SDValue, 16> Ops(NumConcat); 8432 Ops[0] = Vec; 8433 SDValue UndefVec = DAG.getUNDEF(VecVT); 8434 for (unsigned i = 1; i < NumConcat; ++i) 8435 Ops[i] = UndefVec; 8436 8437 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8438 } 8439 8440 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8441 const SDLoc &dl) const { 8442 8443 unsigned Opc = Op.getOpcode(); 8444 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8445 "Unexpected conversion type"); 8446 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8447 "Supports conversions to v2f64/v4f32 only."); 8448 8449 bool SignedConv = Opc == ISD::SINT_TO_FP; 8450 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8451 8452 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8453 EVT WideVT = Wide.getValueType(); 8454 unsigned WideNumElts = WideVT.getVectorNumElements(); 8455 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8456 8457 SmallVector<int, 16> ShuffV; 8458 for (unsigned i = 0; i < WideNumElts; ++i) 8459 ShuffV.push_back(i + WideNumElts); 8460 8461 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8462 int SaveElts = FourEltRes ? 4 : 2; 8463 if (Subtarget.isLittleEndian()) 8464 for (int i = 0; i < SaveElts; i++) 8465 ShuffV[i * Stride] = i; 8466 else 8467 for (int i = 1; i <= SaveElts; i++) 8468 ShuffV[i * Stride - 1] = i - 1; 8469 8470 SDValue ShuffleSrc2 = 8471 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8472 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8473 8474 SDValue Extend; 8475 if (SignedConv) { 8476 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8477 EVT ExtVT = Op.getOperand(0).getValueType(); 8478 if (Subtarget.hasP9Altivec()) 8479 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8480 IntermediateVT.getVectorNumElements()); 8481 8482 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8483 DAG.getValueType(ExtVT)); 8484 } else 8485 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8486 8487 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8488 } 8489 8490 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8491 SelectionDAG &DAG) const { 8492 SDLoc dl(Op); 8493 8494 EVT InVT = Op.getOperand(0).getValueType(); 8495 EVT OutVT = Op.getValueType(); 8496 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8497 isOperationCustom(Op.getOpcode(), InVT)) 8498 return LowerINT_TO_FPVector(Op, DAG, dl); 8499 8500 // Conversions to f128 are legal. 8501 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8502 return Op; 8503 8504 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8505 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8506 return SDValue(); 8507 8508 SDValue Value = Op.getOperand(0); 8509 // The values are now known to be -1 (false) or 1 (true). To convert this 8510 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8511 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8512 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8513 8514 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8515 8516 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8517 8518 if (Op.getValueType() != MVT::v4f64) 8519 Value = DAG.getNode(ISD::FP_ROUND, dl, 8520 Op.getValueType(), Value, 8521 DAG.getIntPtrConstant(1, dl)); 8522 return Value; 8523 } 8524 8525 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8526 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8527 return SDValue(); 8528 8529 if (Op.getOperand(0).getValueType() == MVT::i1) 8530 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8531 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8532 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8533 8534 // If we have direct moves, we can do all the conversion, skip the store/load 8535 // however, without FPCVT we can't do most conversions. 8536 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8537 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8538 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8539 8540 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8541 "UINT_TO_FP is supported only with FPCVT"); 8542 8543 // If we have FCFIDS, then use it when converting to single-precision. 8544 // Otherwise, convert to double-precision and then round. 8545 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8546 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8547 : PPCISD::FCFIDS) 8548 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8549 : PPCISD::FCFID); 8550 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8551 ? MVT::f32 8552 : MVT::f64; 8553 8554 if (Op.getOperand(0).getValueType() == MVT::i64) { 8555 SDValue SINT = Op.getOperand(0); 8556 // When converting to single-precision, we actually need to convert 8557 // to double-precision first and then round to single-precision. 8558 // To avoid double-rounding effects during that operation, we have 8559 // to prepare the input operand. Bits that might be truncated when 8560 // converting to double-precision are replaced by a bit that won't 8561 // be lost at this stage, but is below the single-precision rounding 8562 // position. 8563 // 8564 // However, if -enable-unsafe-fp-math is in effect, accept double 8565 // rounding to avoid the extra overhead. 8566 if (Op.getValueType() == MVT::f32 && 8567 !Subtarget.hasFPCVT() && 8568 !DAG.getTarget().Options.UnsafeFPMath) { 8569 8570 // Twiddle input to make sure the low 11 bits are zero. (If this 8571 // is the case, we are guaranteed the value will fit into the 53 bit 8572 // mantissa of an IEEE double-precision value without rounding.) 8573 // If any of those low 11 bits were not zero originally, make sure 8574 // bit 12 (value 2048) is set instead, so that the final rounding 8575 // to single-precision gets the correct result. 8576 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8577 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8578 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8579 Round, DAG.getConstant(2047, dl, MVT::i64)); 8580 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8581 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8582 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8583 8584 // However, we cannot use that value unconditionally: if the magnitude 8585 // of the input value is small, the bit-twiddling we did above might 8586 // end up visibly changing the output. Fortunately, in that case, we 8587 // don't need to twiddle bits since the original input will convert 8588 // exactly to double-precision floating-point already. Therefore, 8589 // construct a conditional to use the original value if the top 11 8590 // bits are all sign-bit copies, and use the rounded value computed 8591 // above otherwise. 8592 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8593 SINT, DAG.getConstant(53, dl, MVT::i32)); 8594 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8595 Cond, DAG.getConstant(1, dl, MVT::i64)); 8596 Cond = DAG.getSetCC( 8597 dl, 8598 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8599 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8600 8601 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8602 } 8603 8604 ReuseLoadInfo RLI; 8605 SDValue Bits; 8606 8607 MachineFunction &MF = DAG.getMachineFunction(); 8608 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8609 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8610 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8611 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8612 } else if (Subtarget.hasLFIWAX() && 8613 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8614 MachineMemOperand *MMO = 8615 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8616 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8617 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8618 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8619 DAG.getVTList(MVT::f64, MVT::Other), 8620 Ops, MVT::i32, MMO); 8621 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8622 } else if (Subtarget.hasFPCVT() && 8623 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8624 MachineMemOperand *MMO = 8625 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8626 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8627 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8628 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8629 DAG.getVTList(MVT::f64, MVT::Other), 8630 Ops, MVT::i32, MMO); 8631 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8632 } else if (((Subtarget.hasLFIWAX() && 8633 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8634 (Subtarget.hasFPCVT() && 8635 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8636 SINT.getOperand(0).getValueType() == MVT::i32) { 8637 MachineFrameInfo &MFI = MF.getFrameInfo(); 8638 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8639 8640 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8641 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8642 8643 SDValue Store = 8644 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8645 MachinePointerInfo::getFixedStack( 8646 DAG.getMachineFunction(), FrameIdx)); 8647 8648 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8649 "Expected an i32 store"); 8650 8651 RLI.Ptr = FIdx; 8652 RLI.Chain = Store; 8653 RLI.MPI = 8654 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8655 RLI.Alignment = Align(4); 8656 8657 MachineMemOperand *MMO = 8658 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8659 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8660 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8661 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8662 PPCISD::LFIWZX : PPCISD::LFIWAX, 8663 dl, DAG.getVTList(MVT::f64, MVT::Other), 8664 Ops, MVT::i32, MMO); 8665 } else 8666 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8667 8668 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8669 8670 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8671 FP = DAG.getNode(ISD::FP_ROUND, dl, 8672 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8673 return FP; 8674 } 8675 8676 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8677 "Unhandled INT_TO_FP type in custom expander!"); 8678 // Since we only generate this in 64-bit mode, we can take advantage of 8679 // 64-bit registers. In particular, sign extend the input value into the 8680 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8681 // then lfd it and fcfid it. 8682 MachineFunction &MF = DAG.getMachineFunction(); 8683 MachineFrameInfo &MFI = MF.getFrameInfo(); 8684 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8685 8686 SDValue Ld; 8687 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8688 ReuseLoadInfo RLI; 8689 bool ReusingLoad; 8690 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8691 DAG))) { 8692 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8693 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8694 8695 SDValue Store = 8696 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8697 MachinePointerInfo::getFixedStack( 8698 DAG.getMachineFunction(), FrameIdx)); 8699 8700 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8701 "Expected an i32 store"); 8702 8703 RLI.Ptr = FIdx; 8704 RLI.Chain = Store; 8705 RLI.MPI = 8706 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8707 RLI.Alignment = Align(4); 8708 } 8709 8710 MachineMemOperand *MMO = 8711 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8712 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8713 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8714 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8715 PPCISD::LFIWZX : PPCISD::LFIWAX, 8716 dl, DAG.getVTList(MVT::f64, MVT::Other), 8717 Ops, MVT::i32, MMO); 8718 if (ReusingLoad) 8719 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8720 } else { 8721 assert(Subtarget.isPPC64() && 8722 "i32->FP without LFIWAX supported only on PPC64"); 8723 8724 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8725 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8726 8727 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8728 Op.getOperand(0)); 8729 8730 // STD the extended value into the stack slot. 8731 SDValue Store = DAG.getStore( 8732 DAG.getEntryNode(), dl, Ext64, FIdx, 8733 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8734 8735 // Load the value as a double. 8736 Ld = DAG.getLoad( 8737 MVT::f64, dl, Store, FIdx, 8738 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8739 } 8740 8741 // FCFID it and return it. 8742 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8743 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8744 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8745 DAG.getIntPtrConstant(0, dl)); 8746 return FP; 8747 } 8748 8749 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8750 SelectionDAG &DAG) const { 8751 SDLoc dl(Op); 8752 /* 8753 The rounding mode is in bits 30:31 of FPSR, and has the following 8754 settings: 8755 00 Round to nearest 8756 01 Round to 0 8757 10 Round to +inf 8758 11 Round to -inf 8759 8760 FLT_ROUNDS, on the other hand, expects the following: 8761 -1 Undefined 8762 0 Round to 0 8763 1 Round to nearest 8764 2 Round to +inf 8765 3 Round to -inf 8766 8767 To perform the conversion, we do: 8768 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8769 */ 8770 8771 MachineFunction &MF = DAG.getMachineFunction(); 8772 EVT VT = Op.getValueType(); 8773 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8774 8775 // Save FP Control Word to register 8776 SDValue Chain = Op.getOperand(0); 8777 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8778 Chain = MFFS.getValue(1); 8779 8780 // Save FP register to stack slot 8781 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8782 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8783 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8784 8785 // Load FP Control Word from low 32 bits of stack slot. 8786 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8787 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8788 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8789 Chain = CWD.getValue(1); 8790 8791 // Transform as necessary 8792 SDValue CWD1 = 8793 DAG.getNode(ISD::AND, dl, MVT::i32, 8794 CWD, DAG.getConstant(3, dl, MVT::i32)); 8795 SDValue CWD2 = 8796 DAG.getNode(ISD::SRL, dl, MVT::i32, 8797 DAG.getNode(ISD::AND, dl, MVT::i32, 8798 DAG.getNode(ISD::XOR, dl, MVT::i32, 8799 CWD, DAG.getConstant(3, dl, MVT::i32)), 8800 DAG.getConstant(3, dl, MVT::i32)), 8801 DAG.getConstant(1, dl, MVT::i32)); 8802 8803 SDValue RetVal = 8804 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8805 8806 RetVal = 8807 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8808 dl, VT, RetVal); 8809 8810 return DAG.getMergeValues({RetVal, Chain}, dl); 8811 } 8812 8813 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8814 EVT VT = Op.getValueType(); 8815 unsigned BitWidth = VT.getSizeInBits(); 8816 SDLoc dl(Op); 8817 assert(Op.getNumOperands() == 3 && 8818 VT == Op.getOperand(1).getValueType() && 8819 "Unexpected SHL!"); 8820 8821 // Expand into a bunch of logical ops. Note that these ops 8822 // depend on the PPC behavior for oversized shift amounts. 8823 SDValue Lo = Op.getOperand(0); 8824 SDValue Hi = Op.getOperand(1); 8825 SDValue Amt = Op.getOperand(2); 8826 EVT AmtVT = Amt.getValueType(); 8827 8828 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8829 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8830 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8831 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8832 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8833 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8834 DAG.getConstant(-BitWidth, dl, AmtVT)); 8835 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8836 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8837 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8838 SDValue OutOps[] = { OutLo, OutHi }; 8839 return DAG.getMergeValues(OutOps, dl); 8840 } 8841 8842 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8843 EVT VT = Op.getValueType(); 8844 SDLoc dl(Op); 8845 unsigned BitWidth = VT.getSizeInBits(); 8846 assert(Op.getNumOperands() == 3 && 8847 VT == Op.getOperand(1).getValueType() && 8848 "Unexpected SRL!"); 8849 8850 // Expand into a bunch of logical ops. Note that these ops 8851 // depend on the PPC behavior for oversized shift amounts. 8852 SDValue Lo = Op.getOperand(0); 8853 SDValue Hi = Op.getOperand(1); 8854 SDValue Amt = Op.getOperand(2); 8855 EVT AmtVT = Amt.getValueType(); 8856 8857 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8858 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8859 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8860 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8861 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8862 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8863 DAG.getConstant(-BitWidth, dl, AmtVT)); 8864 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8865 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8866 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8867 SDValue OutOps[] = { OutLo, OutHi }; 8868 return DAG.getMergeValues(OutOps, dl); 8869 } 8870 8871 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8872 SDLoc dl(Op); 8873 EVT VT = Op.getValueType(); 8874 unsigned BitWidth = VT.getSizeInBits(); 8875 assert(Op.getNumOperands() == 3 && 8876 VT == Op.getOperand(1).getValueType() && 8877 "Unexpected SRA!"); 8878 8879 // Expand into a bunch of logical ops, followed by a select_cc. 8880 SDValue Lo = Op.getOperand(0); 8881 SDValue Hi = Op.getOperand(1); 8882 SDValue Amt = Op.getOperand(2); 8883 EVT AmtVT = Amt.getValueType(); 8884 8885 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8886 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8887 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8888 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8889 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8890 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8891 DAG.getConstant(-BitWidth, dl, AmtVT)); 8892 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8893 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8894 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8895 Tmp4, Tmp6, ISD::SETLE); 8896 SDValue OutOps[] = { OutLo, OutHi }; 8897 return DAG.getMergeValues(OutOps, dl); 8898 } 8899 8900 //===----------------------------------------------------------------------===// 8901 // Vector related lowering. 8902 // 8903 8904 /// BuildSplatI - Build a canonical splati of Val with an element size of 8905 /// SplatSize. Cast the result to VT. 8906 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8907 SelectionDAG &DAG, const SDLoc &dl) { 8908 static const MVT VTys[] = { // canonical VT to use for each size. 8909 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8910 }; 8911 8912 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8913 8914 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8915 if (Val == -1) 8916 SplatSize = 1; 8917 8918 EVT CanonicalVT = VTys[SplatSize-1]; 8919 8920 // Build a canonical splat for this value. 8921 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8922 } 8923 8924 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8925 /// specified intrinsic ID. 8926 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8927 const SDLoc &dl, EVT DestVT = MVT::Other) { 8928 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8929 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8930 DAG.getConstant(IID, dl, MVT::i32), Op); 8931 } 8932 8933 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8934 /// specified intrinsic ID. 8935 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8936 SelectionDAG &DAG, const SDLoc &dl, 8937 EVT DestVT = MVT::Other) { 8938 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8939 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8940 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8941 } 8942 8943 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8944 /// specified intrinsic ID. 8945 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8946 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8947 EVT DestVT = MVT::Other) { 8948 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8949 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8950 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8951 } 8952 8953 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8954 /// amount. The result has the specified value type. 8955 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8956 SelectionDAG &DAG, const SDLoc &dl) { 8957 // Force LHS/RHS to be the right type. 8958 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8959 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8960 8961 int Ops[16]; 8962 for (unsigned i = 0; i != 16; ++i) 8963 Ops[i] = i + Amt; 8964 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8965 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8966 } 8967 8968 /// Do we have an efficient pattern in a .td file for this node? 8969 /// 8970 /// \param V - pointer to the BuildVectorSDNode being matched 8971 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8972 /// 8973 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8974 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8975 /// the opposite is true (expansion is beneficial) are: 8976 /// - The node builds a vector out of integers that are not 32 or 64-bits 8977 /// - The node builds a vector out of constants 8978 /// - The node is a "load-and-splat" 8979 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8980 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8981 bool HasDirectMove, 8982 bool HasP8Vector) { 8983 EVT VecVT = V->getValueType(0); 8984 bool RightType = VecVT == MVT::v2f64 || 8985 (HasP8Vector && VecVT == MVT::v4f32) || 8986 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8987 if (!RightType) 8988 return false; 8989 8990 bool IsSplat = true; 8991 bool IsLoad = false; 8992 SDValue Op0 = V->getOperand(0); 8993 8994 // This function is called in a block that confirms the node is not a constant 8995 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8996 // different constants. 8997 if (V->isConstant()) 8998 return false; 8999 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9000 if (V->getOperand(i).isUndef()) 9001 return false; 9002 // We want to expand nodes that represent load-and-splat even if the 9003 // loaded value is a floating point truncation or conversion to int. 9004 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9005 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9006 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9007 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9008 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9009 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9010 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9011 IsLoad = true; 9012 // If the operands are different or the input is not a load and has more 9013 // uses than just this BV node, then it isn't a splat. 9014 if (V->getOperand(i) != Op0 || 9015 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9016 IsSplat = false; 9017 } 9018 return !(IsSplat && IsLoad); 9019 } 9020 9021 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9022 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9023 9024 SDLoc dl(Op); 9025 SDValue Op0 = Op->getOperand(0); 9026 9027 if (!EnableQuadPrecision || 9028 (Op.getValueType() != MVT::f128 ) || 9029 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9030 (Op0.getOperand(0).getValueType() != MVT::i64) || 9031 (Op0.getOperand(1).getValueType() != MVT::i64)) 9032 return SDValue(); 9033 9034 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9035 Op0.getOperand(1)); 9036 } 9037 9038 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9039 const SDValue *InputLoad = &Op; 9040 if (InputLoad->getOpcode() == ISD::BITCAST) 9041 InputLoad = &InputLoad->getOperand(0); 9042 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 9043 InputLoad = &InputLoad->getOperand(0); 9044 if (InputLoad->getOpcode() != ISD::LOAD) 9045 return nullptr; 9046 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9047 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9048 } 9049 9050 // If this is a case we can't handle, return null and let the default 9051 // expansion code take care of it. If we CAN select this case, and if it 9052 // selects to a single instruction, return Op. Otherwise, if we can codegen 9053 // this case more efficiently than a constant pool load, lower it to the 9054 // sequence of ops that should be used. 9055 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9056 SelectionDAG &DAG) const { 9057 SDLoc dl(Op); 9058 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9059 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9060 9061 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9062 // We first build an i32 vector, load it into a QPX register, 9063 // then convert it to a floating-point vector and compare it 9064 // to a zero vector to get the boolean result. 9065 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9066 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9067 MachinePointerInfo PtrInfo = 9068 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9069 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9070 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9071 9072 assert(BVN->getNumOperands() == 4 && 9073 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9074 9075 bool IsConst = true; 9076 for (unsigned i = 0; i < 4; ++i) { 9077 if (BVN->getOperand(i).isUndef()) continue; 9078 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9079 IsConst = false; 9080 break; 9081 } 9082 } 9083 9084 if (IsConst) { 9085 Constant *One = 9086 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9087 Constant *NegOne = 9088 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9089 9090 Constant *CV[4]; 9091 for (unsigned i = 0; i < 4; ++i) { 9092 if (BVN->getOperand(i).isUndef()) 9093 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9094 else if (isNullConstant(BVN->getOperand(i))) 9095 CV[i] = NegOne; 9096 else 9097 CV[i] = One; 9098 } 9099 9100 Constant *CP = ConstantVector::get(CV); 9101 SDValue CPIdx = 9102 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9103 9104 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9105 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9106 return DAG.getMemIntrinsicNode( 9107 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9108 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9109 } 9110 9111 SmallVector<SDValue, 4> Stores; 9112 for (unsigned i = 0; i < 4; ++i) { 9113 if (BVN->getOperand(i).isUndef()) continue; 9114 9115 unsigned Offset = 4*i; 9116 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9117 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9118 9119 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9120 if (StoreSize > 4) { 9121 Stores.push_back( 9122 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9123 PtrInfo.getWithOffset(Offset), MVT::i32)); 9124 } else { 9125 SDValue StoreValue = BVN->getOperand(i); 9126 if (StoreSize < 4) 9127 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9128 9129 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9130 PtrInfo.getWithOffset(Offset))); 9131 } 9132 } 9133 9134 SDValue StoreChain; 9135 if (!Stores.empty()) 9136 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9137 else 9138 StoreChain = DAG.getEntryNode(); 9139 9140 // Now load from v4i32 into the QPX register; this will extend it to 9141 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9142 // is typed as v4f64 because the QPX register integer states are not 9143 // explicitly represented. 9144 9145 SDValue Ops[] = {StoreChain, 9146 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9147 FIdx}; 9148 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9149 9150 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9151 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9152 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9153 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9154 LoadedVect); 9155 9156 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9157 9158 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9159 } 9160 9161 // All other QPX vectors are handled by generic code. 9162 if (Subtarget.hasQPX()) 9163 return SDValue(); 9164 9165 // Check if this is a splat of a constant value. 9166 APInt APSplatBits, APSplatUndef; 9167 unsigned SplatBitSize; 9168 bool HasAnyUndefs; 9169 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9170 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9171 SplatBitSize > 32) { 9172 9173 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9174 // Handle load-and-splat patterns as we have instructions that will do this 9175 // in one go. 9176 if (InputLoad && DAG.isSplatValue(Op, true)) { 9177 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9178 9179 // We have handling for 4 and 8 byte elements. 9180 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9181 9182 // Checking for a single use of this load, we have to check for vector 9183 // width (128 bits) / ElementSize uses (since each operand of the 9184 // BUILD_VECTOR is a separate use of the value. 9185 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9186 ((Subtarget.hasVSX() && ElementSize == 64) || 9187 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9188 SDValue Ops[] = { 9189 LD->getChain(), // Chain 9190 LD->getBasePtr(), // Ptr 9191 DAG.getValueType(Op.getValueType()) // VT 9192 }; 9193 return 9194 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9195 DAG.getVTList(Op.getValueType(), MVT::Other), 9196 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9197 } 9198 } 9199 9200 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9201 // lowered to VSX instructions under certain conditions. 9202 // Without VSX, there is no pattern more efficient than expanding the node. 9203 if (Subtarget.hasVSX() && 9204 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9205 Subtarget.hasP8Vector())) 9206 return Op; 9207 return SDValue(); 9208 } 9209 9210 unsigned SplatBits = APSplatBits.getZExtValue(); 9211 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9212 unsigned SplatSize = SplatBitSize / 8; 9213 9214 // First, handle single instruction cases. 9215 9216 // All zeros? 9217 if (SplatBits == 0) { 9218 // Canonicalize all zero vectors to be v4i32. 9219 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9220 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9221 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9222 } 9223 return Op; 9224 } 9225 9226 // We have XXSPLTIB for constant splats one byte wide 9227 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9228 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9229 if (Subtarget.hasP9Vector() && SplatSize == 1) 9230 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9231 9232 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9233 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9234 (32-SplatBitSize)); 9235 if (SextVal >= -16 && SextVal <= 15) 9236 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9237 9238 // Two instruction sequences. 9239 9240 // If this value is in the range [-32,30] and is even, use: 9241 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9242 // If this value is in the range [17,31] and is odd, use: 9243 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9244 // If this value is in the range [-31,-17] and is odd, use: 9245 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9246 // Note the last two are three-instruction sequences. 9247 if (SextVal >= -32 && SextVal <= 31) { 9248 // To avoid having these optimizations undone by constant folding, 9249 // we convert to a pseudo that will be expanded later into one of 9250 // the above forms. 9251 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9252 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9253 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9254 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9255 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9256 if (VT == Op.getValueType()) 9257 return RetVal; 9258 else 9259 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9260 } 9261 9262 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9263 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9264 // for fneg/fabs. 9265 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9266 // Make -1 and vspltisw -1: 9267 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9268 9269 // Make the VSLW intrinsic, computing 0x8000_0000. 9270 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9271 OnesV, DAG, dl); 9272 9273 // xor by OnesV to invert it. 9274 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9275 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9276 } 9277 9278 // Check to see if this is a wide variety of vsplti*, binop self cases. 9279 static const signed char SplatCsts[] = { 9280 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9281 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9282 }; 9283 9284 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9285 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9286 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9287 int i = SplatCsts[idx]; 9288 9289 // Figure out what shift amount will be used by altivec if shifted by i in 9290 // this splat size. 9291 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9292 9293 // vsplti + shl self. 9294 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9295 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9296 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9297 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9298 Intrinsic::ppc_altivec_vslw 9299 }; 9300 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9301 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9302 } 9303 9304 // vsplti + srl self. 9305 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9306 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9307 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9308 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9309 Intrinsic::ppc_altivec_vsrw 9310 }; 9311 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9312 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9313 } 9314 9315 // vsplti + sra self. 9316 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9317 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9318 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9319 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9320 Intrinsic::ppc_altivec_vsraw 9321 }; 9322 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9323 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9324 } 9325 9326 // vsplti + rol self. 9327 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9328 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9329 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9330 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9331 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9332 Intrinsic::ppc_altivec_vrlw 9333 }; 9334 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9335 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9336 } 9337 9338 // t = vsplti c, result = vsldoi t, t, 1 9339 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9340 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9341 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9342 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9343 } 9344 // t = vsplti c, result = vsldoi t, t, 2 9345 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9346 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9347 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9348 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9349 } 9350 // t = vsplti c, result = vsldoi t, t, 3 9351 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9352 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9353 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9354 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9355 } 9356 } 9357 9358 return SDValue(); 9359 } 9360 9361 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9362 /// the specified operations to build the shuffle. 9363 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9364 SDValue RHS, SelectionDAG &DAG, 9365 const SDLoc &dl) { 9366 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9367 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9368 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9369 9370 enum { 9371 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9372 OP_VMRGHW, 9373 OP_VMRGLW, 9374 OP_VSPLTISW0, 9375 OP_VSPLTISW1, 9376 OP_VSPLTISW2, 9377 OP_VSPLTISW3, 9378 OP_VSLDOI4, 9379 OP_VSLDOI8, 9380 OP_VSLDOI12 9381 }; 9382 9383 if (OpNum == OP_COPY) { 9384 if (LHSID == (1*9+2)*9+3) return LHS; 9385 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9386 return RHS; 9387 } 9388 9389 SDValue OpLHS, OpRHS; 9390 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9391 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9392 9393 int ShufIdxs[16]; 9394 switch (OpNum) { 9395 default: llvm_unreachable("Unknown i32 permute!"); 9396 case OP_VMRGHW: 9397 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9398 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9399 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9400 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9401 break; 9402 case OP_VMRGLW: 9403 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9404 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9405 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9406 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9407 break; 9408 case OP_VSPLTISW0: 9409 for (unsigned i = 0; i != 16; ++i) 9410 ShufIdxs[i] = (i&3)+0; 9411 break; 9412 case OP_VSPLTISW1: 9413 for (unsigned i = 0; i != 16; ++i) 9414 ShufIdxs[i] = (i&3)+4; 9415 break; 9416 case OP_VSPLTISW2: 9417 for (unsigned i = 0; i != 16; ++i) 9418 ShufIdxs[i] = (i&3)+8; 9419 break; 9420 case OP_VSPLTISW3: 9421 for (unsigned i = 0; i != 16; ++i) 9422 ShufIdxs[i] = (i&3)+12; 9423 break; 9424 case OP_VSLDOI4: 9425 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9426 case OP_VSLDOI8: 9427 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9428 case OP_VSLDOI12: 9429 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9430 } 9431 EVT VT = OpLHS.getValueType(); 9432 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9433 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9434 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9435 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9436 } 9437 9438 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9439 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9440 /// SDValue. 9441 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9442 SelectionDAG &DAG) const { 9443 const unsigned BytesInVector = 16; 9444 bool IsLE = Subtarget.isLittleEndian(); 9445 SDLoc dl(N); 9446 SDValue V1 = N->getOperand(0); 9447 SDValue V2 = N->getOperand(1); 9448 unsigned ShiftElts = 0, InsertAtByte = 0; 9449 bool Swap = false; 9450 9451 // Shifts required to get the byte we want at element 7. 9452 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9453 0, 15, 14, 13, 12, 11, 10, 9}; 9454 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9455 1, 2, 3, 4, 5, 6, 7, 8}; 9456 9457 ArrayRef<int> Mask = N->getMask(); 9458 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9459 9460 // For each mask element, find out if we're just inserting something 9461 // from V2 into V1 or vice versa. 9462 // Possible permutations inserting an element from V2 into V1: 9463 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9464 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9465 // ... 9466 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9467 // Inserting from V1 into V2 will be similar, except mask range will be 9468 // [16,31]. 9469 9470 bool FoundCandidate = false; 9471 // If both vector operands for the shuffle are the same vector, the mask 9472 // will contain only elements from the first one and the second one will be 9473 // undef. 9474 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9475 // Go through the mask of half-words to find an element that's being moved 9476 // from one vector to the other. 9477 for (unsigned i = 0; i < BytesInVector; ++i) { 9478 unsigned CurrentElement = Mask[i]; 9479 // If 2nd operand is undefined, we should only look for element 7 in the 9480 // Mask. 9481 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9482 continue; 9483 9484 bool OtherElementsInOrder = true; 9485 // Examine the other elements in the Mask to see if they're in original 9486 // order. 9487 for (unsigned j = 0; j < BytesInVector; ++j) { 9488 if (j == i) 9489 continue; 9490 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9491 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9492 // in which we always assume we're always picking from the 1st operand. 9493 int MaskOffset = 9494 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9495 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9496 OtherElementsInOrder = false; 9497 break; 9498 } 9499 } 9500 // If other elements are in original order, we record the number of shifts 9501 // we need to get the element we want into element 7. Also record which byte 9502 // in the vector we should insert into. 9503 if (OtherElementsInOrder) { 9504 // If 2nd operand is undefined, we assume no shifts and no swapping. 9505 if (V2.isUndef()) { 9506 ShiftElts = 0; 9507 Swap = false; 9508 } else { 9509 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9510 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9511 : BigEndianShifts[CurrentElement & 0xF]; 9512 Swap = CurrentElement < BytesInVector; 9513 } 9514 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9515 FoundCandidate = true; 9516 break; 9517 } 9518 } 9519 9520 if (!FoundCandidate) 9521 return SDValue(); 9522 9523 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9524 // optionally with VECSHL if shift is required. 9525 if (Swap) 9526 std::swap(V1, V2); 9527 if (V2.isUndef()) 9528 V2 = V1; 9529 if (ShiftElts) { 9530 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9531 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9532 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9533 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9534 } 9535 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9536 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9537 } 9538 9539 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9540 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9541 /// SDValue. 9542 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9543 SelectionDAG &DAG) const { 9544 const unsigned NumHalfWords = 8; 9545 const unsigned BytesInVector = NumHalfWords * 2; 9546 // Check that the shuffle is on half-words. 9547 if (!isNByteElemShuffleMask(N, 2, 1)) 9548 return SDValue(); 9549 9550 bool IsLE = Subtarget.isLittleEndian(); 9551 SDLoc dl(N); 9552 SDValue V1 = N->getOperand(0); 9553 SDValue V2 = N->getOperand(1); 9554 unsigned ShiftElts = 0, InsertAtByte = 0; 9555 bool Swap = false; 9556 9557 // Shifts required to get the half-word we want at element 3. 9558 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9559 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9560 9561 uint32_t Mask = 0; 9562 uint32_t OriginalOrderLow = 0x1234567; 9563 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9564 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9565 // 32-bit space, only need 4-bit nibbles per element. 9566 for (unsigned i = 0; i < NumHalfWords; ++i) { 9567 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9568 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9569 } 9570 9571 // For each mask element, find out if we're just inserting something 9572 // from V2 into V1 or vice versa. Possible permutations inserting an element 9573 // from V2 into V1: 9574 // X, 1, 2, 3, 4, 5, 6, 7 9575 // 0, X, 2, 3, 4, 5, 6, 7 9576 // 0, 1, X, 3, 4, 5, 6, 7 9577 // 0, 1, 2, X, 4, 5, 6, 7 9578 // 0, 1, 2, 3, X, 5, 6, 7 9579 // 0, 1, 2, 3, 4, X, 6, 7 9580 // 0, 1, 2, 3, 4, 5, X, 7 9581 // 0, 1, 2, 3, 4, 5, 6, X 9582 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9583 9584 bool FoundCandidate = false; 9585 // Go through the mask of half-words to find an element that's being moved 9586 // from one vector to the other. 9587 for (unsigned i = 0; i < NumHalfWords; ++i) { 9588 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9589 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9590 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9591 uint32_t TargetOrder = 0x0; 9592 9593 // If both vector operands for the shuffle are the same vector, the mask 9594 // will contain only elements from the first one and the second one will be 9595 // undef. 9596 if (V2.isUndef()) { 9597 ShiftElts = 0; 9598 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9599 TargetOrder = OriginalOrderLow; 9600 Swap = false; 9601 // Skip if not the correct element or mask of other elements don't equal 9602 // to our expected order. 9603 if (MaskOneElt == VINSERTHSrcElem && 9604 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9605 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9606 FoundCandidate = true; 9607 break; 9608 } 9609 } else { // If both operands are defined. 9610 // Target order is [8,15] if the current mask is between [0,7]. 9611 TargetOrder = 9612 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9613 // Skip if mask of other elements don't equal our expected order. 9614 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9615 // We only need the last 3 bits for the number of shifts. 9616 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9617 : BigEndianShifts[MaskOneElt & 0x7]; 9618 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9619 Swap = MaskOneElt < NumHalfWords; 9620 FoundCandidate = true; 9621 break; 9622 } 9623 } 9624 } 9625 9626 if (!FoundCandidate) 9627 return SDValue(); 9628 9629 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9630 // optionally with VECSHL if shift is required. 9631 if (Swap) 9632 std::swap(V1, V2); 9633 if (V2.isUndef()) 9634 V2 = V1; 9635 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9636 if (ShiftElts) { 9637 // Double ShiftElts because we're left shifting on v16i8 type. 9638 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9639 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9640 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9641 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9642 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9643 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9644 } 9645 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9646 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9647 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9648 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9649 } 9650 9651 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9652 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9653 /// return the code it can be lowered into. Worst case, it can always be 9654 /// lowered into a vperm. 9655 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9656 SelectionDAG &DAG) const { 9657 SDLoc dl(Op); 9658 SDValue V1 = Op.getOperand(0); 9659 SDValue V2 = Op.getOperand(1); 9660 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9661 EVT VT = Op.getValueType(); 9662 bool isLittleEndian = Subtarget.isLittleEndian(); 9663 9664 unsigned ShiftElts, InsertAtByte; 9665 bool Swap = false; 9666 9667 // If this is a load-and-splat, we can do that with a single instruction 9668 // in some cases. However if the load has multiple uses, we don't want to 9669 // combine it because that will just produce multiple loads. 9670 const SDValue *InputLoad = getNormalLoadInput(V1); 9671 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9672 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9673 InputLoad->hasOneUse()) { 9674 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9675 int SplatIdx = 9676 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9677 9678 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9679 // For 4-byte load-and-splat, we need Power9. 9680 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9681 uint64_t Offset = 0; 9682 if (IsFourByte) 9683 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9684 else 9685 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9686 SDValue BasePtr = LD->getBasePtr(); 9687 if (Offset != 0) 9688 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9689 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9690 SDValue Ops[] = { 9691 LD->getChain(), // Chain 9692 BasePtr, // BasePtr 9693 DAG.getValueType(Op.getValueType()) // VT 9694 }; 9695 SDVTList VTL = 9696 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9697 SDValue LdSplt = 9698 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9699 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9700 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9701 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9702 return LdSplt; 9703 } 9704 } 9705 if (Subtarget.hasP9Vector() && 9706 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9707 isLittleEndian)) { 9708 if (Swap) 9709 std::swap(V1, V2); 9710 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9711 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9712 if (ShiftElts) { 9713 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9714 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9715 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9716 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9717 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9718 } 9719 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9720 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9721 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9722 } 9723 9724 if (Subtarget.hasP9Altivec()) { 9725 SDValue NewISDNode; 9726 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9727 return NewISDNode; 9728 9729 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9730 return NewISDNode; 9731 } 9732 9733 if (Subtarget.hasVSX() && 9734 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9735 if (Swap) 9736 std::swap(V1, V2); 9737 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9738 SDValue Conv2 = 9739 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9740 9741 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9742 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9743 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9744 } 9745 9746 if (Subtarget.hasVSX() && 9747 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9748 if (Swap) 9749 std::swap(V1, V2); 9750 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9751 SDValue Conv2 = 9752 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9753 9754 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9755 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9756 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9757 } 9758 9759 if (Subtarget.hasP9Vector()) { 9760 if (PPC::isXXBRHShuffleMask(SVOp)) { 9761 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9762 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9763 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9764 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9765 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9766 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9767 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9768 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9769 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9770 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9771 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9772 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9773 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9774 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9775 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9776 } 9777 } 9778 9779 if (Subtarget.hasVSX()) { 9780 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9781 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9782 9783 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9784 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9785 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9786 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9787 } 9788 9789 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9790 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9791 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9792 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9793 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9794 } 9795 } 9796 9797 if (Subtarget.hasQPX()) { 9798 if (VT.getVectorNumElements() != 4) 9799 return SDValue(); 9800 9801 if (V2.isUndef()) V2 = V1; 9802 9803 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9804 if (AlignIdx != -1) { 9805 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9806 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9807 } else if (SVOp->isSplat()) { 9808 int SplatIdx = SVOp->getSplatIndex(); 9809 if (SplatIdx >= 4) { 9810 std::swap(V1, V2); 9811 SplatIdx -= 4; 9812 } 9813 9814 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9815 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9816 } 9817 9818 // Lower this into a qvgpci/qvfperm pair. 9819 9820 // Compute the qvgpci literal 9821 unsigned idx = 0; 9822 for (unsigned i = 0; i < 4; ++i) { 9823 int m = SVOp->getMaskElt(i); 9824 unsigned mm = m >= 0 ? (unsigned) m : i; 9825 idx |= mm << (3-i)*3; 9826 } 9827 9828 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9829 DAG.getConstant(idx, dl, MVT::i32)); 9830 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9831 } 9832 9833 // Cases that are handled by instructions that take permute immediates 9834 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9835 // selected by the instruction selector. 9836 if (V2.isUndef()) { 9837 if (PPC::isSplatShuffleMask(SVOp, 1) || 9838 PPC::isSplatShuffleMask(SVOp, 2) || 9839 PPC::isSplatShuffleMask(SVOp, 4) || 9840 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9841 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9842 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9843 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9844 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9845 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9846 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9847 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9848 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9849 (Subtarget.hasP8Altivec() && ( 9850 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9851 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9852 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9853 return Op; 9854 } 9855 } 9856 9857 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9858 // and produce a fixed permutation. If any of these match, do not lower to 9859 // VPERM. 9860 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9861 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9862 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9863 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9864 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9865 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9866 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9867 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9868 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9869 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9870 (Subtarget.hasP8Altivec() && ( 9871 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9872 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9873 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9874 return Op; 9875 9876 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9877 // perfect shuffle table to emit an optimal matching sequence. 9878 ArrayRef<int> PermMask = SVOp->getMask(); 9879 9880 unsigned PFIndexes[4]; 9881 bool isFourElementShuffle = true; 9882 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9883 unsigned EltNo = 8; // Start out undef. 9884 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9885 if (PermMask[i*4+j] < 0) 9886 continue; // Undef, ignore it. 9887 9888 unsigned ByteSource = PermMask[i*4+j]; 9889 if ((ByteSource & 3) != j) { 9890 isFourElementShuffle = false; 9891 break; 9892 } 9893 9894 if (EltNo == 8) { 9895 EltNo = ByteSource/4; 9896 } else if (EltNo != ByteSource/4) { 9897 isFourElementShuffle = false; 9898 break; 9899 } 9900 } 9901 PFIndexes[i] = EltNo; 9902 } 9903 9904 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9905 // perfect shuffle vector to determine if it is cost effective to do this as 9906 // discrete instructions, or whether we should use a vperm. 9907 // For now, we skip this for little endian until such time as we have a 9908 // little-endian perfect shuffle table. 9909 if (isFourElementShuffle && !isLittleEndian) { 9910 // Compute the index in the perfect shuffle table. 9911 unsigned PFTableIndex = 9912 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9913 9914 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9915 unsigned Cost = (PFEntry >> 30); 9916 9917 // Determining when to avoid vperm is tricky. Many things affect the cost 9918 // of vperm, particularly how many times the perm mask needs to be computed. 9919 // For example, if the perm mask can be hoisted out of a loop or is already 9920 // used (perhaps because there are multiple permutes with the same shuffle 9921 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9922 // the loop requires an extra register. 9923 // 9924 // As a compromise, we only emit discrete instructions if the shuffle can be 9925 // generated in 3 or fewer operations. When we have loop information 9926 // available, if this block is within a loop, we should avoid using vperm 9927 // for 3-operation perms and use a constant pool load instead. 9928 if (Cost < 3) 9929 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9930 } 9931 9932 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9933 // vector that will get spilled to the constant pool. 9934 if (V2.isUndef()) V2 = V1; 9935 9936 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9937 // that it is in input element units, not in bytes. Convert now. 9938 9939 // For little endian, the order of the input vectors is reversed, and 9940 // the permutation mask is complemented with respect to 31. This is 9941 // necessary to produce proper semantics with the big-endian-biased vperm 9942 // instruction. 9943 EVT EltVT = V1.getValueType().getVectorElementType(); 9944 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9945 9946 SmallVector<SDValue, 16> ResultMask; 9947 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9948 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9949 9950 for (unsigned j = 0; j != BytesPerElement; ++j) 9951 if (isLittleEndian) 9952 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9953 dl, MVT::i32)); 9954 else 9955 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9956 MVT::i32)); 9957 } 9958 9959 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9960 if (isLittleEndian) 9961 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9962 V2, V1, VPermMask); 9963 else 9964 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9965 V1, V2, VPermMask); 9966 } 9967 9968 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9969 /// vector comparison. If it is, return true and fill in Opc/isDot with 9970 /// information about the intrinsic. 9971 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9972 bool &isDot, const PPCSubtarget &Subtarget) { 9973 unsigned IntrinsicID = 9974 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9975 CompareOpc = -1; 9976 isDot = false; 9977 switch (IntrinsicID) { 9978 default: 9979 return false; 9980 // Comparison predicates. 9981 case Intrinsic::ppc_altivec_vcmpbfp_p: 9982 CompareOpc = 966; 9983 isDot = true; 9984 break; 9985 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9986 CompareOpc = 198; 9987 isDot = true; 9988 break; 9989 case Intrinsic::ppc_altivec_vcmpequb_p: 9990 CompareOpc = 6; 9991 isDot = true; 9992 break; 9993 case Intrinsic::ppc_altivec_vcmpequh_p: 9994 CompareOpc = 70; 9995 isDot = true; 9996 break; 9997 case Intrinsic::ppc_altivec_vcmpequw_p: 9998 CompareOpc = 134; 9999 isDot = true; 10000 break; 10001 case Intrinsic::ppc_altivec_vcmpequd_p: 10002 if (Subtarget.hasP8Altivec()) { 10003 CompareOpc = 199; 10004 isDot = true; 10005 } else 10006 return false; 10007 break; 10008 case Intrinsic::ppc_altivec_vcmpneb_p: 10009 case Intrinsic::ppc_altivec_vcmpneh_p: 10010 case Intrinsic::ppc_altivec_vcmpnew_p: 10011 case Intrinsic::ppc_altivec_vcmpnezb_p: 10012 case Intrinsic::ppc_altivec_vcmpnezh_p: 10013 case Intrinsic::ppc_altivec_vcmpnezw_p: 10014 if (Subtarget.hasP9Altivec()) { 10015 switch (IntrinsicID) { 10016 default: 10017 llvm_unreachable("Unknown comparison intrinsic."); 10018 case Intrinsic::ppc_altivec_vcmpneb_p: 10019 CompareOpc = 7; 10020 break; 10021 case Intrinsic::ppc_altivec_vcmpneh_p: 10022 CompareOpc = 71; 10023 break; 10024 case Intrinsic::ppc_altivec_vcmpnew_p: 10025 CompareOpc = 135; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpnezb_p: 10028 CompareOpc = 263; 10029 break; 10030 case Intrinsic::ppc_altivec_vcmpnezh_p: 10031 CompareOpc = 327; 10032 break; 10033 case Intrinsic::ppc_altivec_vcmpnezw_p: 10034 CompareOpc = 391; 10035 break; 10036 } 10037 isDot = true; 10038 } else 10039 return false; 10040 break; 10041 case Intrinsic::ppc_altivec_vcmpgefp_p: 10042 CompareOpc = 454; 10043 isDot = true; 10044 break; 10045 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10046 CompareOpc = 710; 10047 isDot = true; 10048 break; 10049 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10050 CompareOpc = 774; 10051 isDot = true; 10052 break; 10053 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10054 CompareOpc = 838; 10055 isDot = true; 10056 break; 10057 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10058 CompareOpc = 902; 10059 isDot = true; 10060 break; 10061 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10062 if (Subtarget.hasP8Altivec()) { 10063 CompareOpc = 967; 10064 isDot = true; 10065 } else 10066 return false; 10067 break; 10068 case Intrinsic::ppc_altivec_vcmpgtub_p: 10069 CompareOpc = 518; 10070 isDot = true; 10071 break; 10072 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10073 CompareOpc = 582; 10074 isDot = true; 10075 break; 10076 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10077 CompareOpc = 646; 10078 isDot = true; 10079 break; 10080 case Intrinsic::ppc_altivec_vcmpgtud_p: 10081 if (Subtarget.hasP8Altivec()) { 10082 CompareOpc = 711; 10083 isDot = true; 10084 } else 10085 return false; 10086 break; 10087 10088 // VSX predicate comparisons use the same infrastructure 10089 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10090 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10091 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10092 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10093 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10094 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10095 if (Subtarget.hasVSX()) { 10096 switch (IntrinsicID) { 10097 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10098 CompareOpc = 99; 10099 break; 10100 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10101 CompareOpc = 115; 10102 break; 10103 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10104 CompareOpc = 107; 10105 break; 10106 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10107 CompareOpc = 67; 10108 break; 10109 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10110 CompareOpc = 83; 10111 break; 10112 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10113 CompareOpc = 75; 10114 break; 10115 } 10116 isDot = true; 10117 } else 10118 return false; 10119 break; 10120 10121 // Normal Comparisons. 10122 case Intrinsic::ppc_altivec_vcmpbfp: 10123 CompareOpc = 966; 10124 break; 10125 case Intrinsic::ppc_altivec_vcmpeqfp: 10126 CompareOpc = 198; 10127 break; 10128 case Intrinsic::ppc_altivec_vcmpequb: 10129 CompareOpc = 6; 10130 break; 10131 case Intrinsic::ppc_altivec_vcmpequh: 10132 CompareOpc = 70; 10133 break; 10134 case Intrinsic::ppc_altivec_vcmpequw: 10135 CompareOpc = 134; 10136 break; 10137 case Intrinsic::ppc_altivec_vcmpequd: 10138 if (Subtarget.hasP8Altivec()) 10139 CompareOpc = 199; 10140 else 10141 return false; 10142 break; 10143 case Intrinsic::ppc_altivec_vcmpneb: 10144 case Intrinsic::ppc_altivec_vcmpneh: 10145 case Intrinsic::ppc_altivec_vcmpnew: 10146 case Intrinsic::ppc_altivec_vcmpnezb: 10147 case Intrinsic::ppc_altivec_vcmpnezh: 10148 case Intrinsic::ppc_altivec_vcmpnezw: 10149 if (Subtarget.hasP9Altivec()) 10150 switch (IntrinsicID) { 10151 default: 10152 llvm_unreachable("Unknown comparison intrinsic."); 10153 case Intrinsic::ppc_altivec_vcmpneb: 10154 CompareOpc = 7; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpneh: 10157 CompareOpc = 71; 10158 break; 10159 case Intrinsic::ppc_altivec_vcmpnew: 10160 CompareOpc = 135; 10161 break; 10162 case Intrinsic::ppc_altivec_vcmpnezb: 10163 CompareOpc = 263; 10164 break; 10165 case Intrinsic::ppc_altivec_vcmpnezh: 10166 CompareOpc = 327; 10167 break; 10168 case Intrinsic::ppc_altivec_vcmpnezw: 10169 CompareOpc = 391; 10170 break; 10171 } 10172 else 10173 return false; 10174 break; 10175 case Intrinsic::ppc_altivec_vcmpgefp: 10176 CompareOpc = 454; 10177 break; 10178 case Intrinsic::ppc_altivec_vcmpgtfp: 10179 CompareOpc = 710; 10180 break; 10181 case Intrinsic::ppc_altivec_vcmpgtsb: 10182 CompareOpc = 774; 10183 break; 10184 case Intrinsic::ppc_altivec_vcmpgtsh: 10185 CompareOpc = 838; 10186 break; 10187 case Intrinsic::ppc_altivec_vcmpgtsw: 10188 CompareOpc = 902; 10189 break; 10190 case Intrinsic::ppc_altivec_vcmpgtsd: 10191 if (Subtarget.hasP8Altivec()) 10192 CompareOpc = 967; 10193 else 10194 return false; 10195 break; 10196 case Intrinsic::ppc_altivec_vcmpgtub: 10197 CompareOpc = 518; 10198 break; 10199 case Intrinsic::ppc_altivec_vcmpgtuh: 10200 CompareOpc = 582; 10201 break; 10202 case Intrinsic::ppc_altivec_vcmpgtuw: 10203 CompareOpc = 646; 10204 break; 10205 case Intrinsic::ppc_altivec_vcmpgtud: 10206 if (Subtarget.hasP8Altivec()) 10207 CompareOpc = 711; 10208 else 10209 return false; 10210 break; 10211 } 10212 return true; 10213 } 10214 10215 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10216 /// lower, do it, otherwise return null. 10217 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10218 SelectionDAG &DAG) const { 10219 unsigned IntrinsicID = 10220 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10221 10222 SDLoc dl(Op); 10223 10224 if (IntrinsicID == Intrinsic::thread_pointer) { 10225 // Reads the thread pointer register, used for __builtin_thread_pointer. 10226 if (Subtarget.isPPC64()) 10227 return DAG.getRegister(PPC::X13, MVT::i64); 10228 return DAG.getRegister(PPC::R2, MVT::i32); 10229 } 10230 10231 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10232 // opcode number of the comparison. 10233 int CompareOpc; 10234 bool isDot; 10235 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10236 return SDValue(); // Don't custom lower most intrinsics. 10237 10238 // If this is a non-dot comparison, make the VCMP node and we are done. 10239 if (!isDot) { 10240 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10241 Op.getOperand(1), Op.getOperand(2), 10242 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10243 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10244 } 10245 10246 // Create the PPCISD altivec 'dot' comparison node. 10247 SDValue Ops[] = { 10248 Op.getOperand(2), // LHS 10249 Op.getOperand(3), // RHS 10250 DAG.getConstant(CompareOpc, dl, MVT::i32) 10251 }; 10252 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10253 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10254 10255 // Now that we have the comparison, emit a copy from the CR to a GPR. 10256 // This is flagged to the above dot comparison. 10257 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10258 DAG.getRegister(PPC::CR6, MVT::i32), 10259 CompNode.getValue(1)); 10260 10261 // Unpack the result based on how the target uses it. 10262 unsigned BitNo; // Bit # of CR6. 10263 bool InvertBit; // Invert result? 10264 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10265 default: // Can't happen, don't crash on invalid number though. 10266 case 0: // Return the value of the EQ bit of CR6. 10267 BitNo = 0; InvertBit = false; 10268 break; 10269 case 1: // Return the inverted value of the EQ bit of CR6. 10270 BitNo = 0; InvertBit = true; 10271 break; 10272 case 2: // Return the value of the LT bit of CR6. 10273 BitNo = 2; InvertBit = false; 10274 break; 10275 case 3: // Return the inverted value of the LT bit of CR6. 10276 BitNo = 2; InvertBit = true; 10277 break; 10278 } 10279 10280 // Shift the bit into the low position. 10281 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10282 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10283 // Isolate the bit. 10284 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10285 DAG.getConstant(1, dl, MVT::i32)); 10286 10287 // If we are supposed to, toggle the bit. 10288 if (InvertBit) 10289 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10290 DAG.getConstant(1, dl, MVT::i32)); 10291 return Flags; 10292 } 10293 10294 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10295 SelectionDAG &DAG) const { 10296 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10297 // the beginning of the argument list. 10298 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10299 SDLoc DL(Op); 10300 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10301 case Intrinsic::ppc_cfence: { 10302 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10303 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10304 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10305 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10306 Op.getOperand(ArgStart + 1)), 10307 Op.getOperand(0)), 10308 0); 10309 } 10310 default: 10311 break; 10312 } 10313 return SDValue(); 10314 } 10315 10316 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10317 // Check for a DIV with the same operands as this REM. 10318 for (auto UI : Op.getOperand(1)->uses()) { 10319 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10320 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10321 if (UI->getOperand(0) == Op.getOperand(0) && 10322 UI->getOperand(1) == Op.getOperand(1)) 10323 return SDValue(); 10324 } 10325 return Op; 10326 } 10327 10328 // Lower scalar BSWAP64 to xxbrd. 10329 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10330 SDLoc dl(Op); 10331 // MTVSRDD 10332 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10333 Op.getOperand(0)); 10334 // XXBRD 10335 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10336 // MFVSRD 10337 int VectorIndex = 0; 10338 if (Subtarget.isLittleEndian()) 10339 VectorIndex = 1; 10340 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10341 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10342 return Op; 10343 } 10344 10345 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10346 // compared to a value that is atomically loaded (atomic loads zero-extend). 10347 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10348 SelectionDAG &DAG) const { 10349 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10350 "Expecting an atomic compare-and-swap here."); 10351 SDLoc dl(Op); 10352 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10353 EVT MemVT = AtomicNode->getMemoryVT(); 10354 if (MemVT.getSizeInBits() >= 32) 10355 return Op; 10356 10357 SDValue CmpOp = Op.getOperand(2); 10358 // If this is already correctly zero-extended, leave it alone. 10359 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10360 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10361 return Op; 10362 10363 // Clear the high bits of the compare operand. 10364 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10365 SDValue NewCmpOp = 10366 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10367 DAG.getConstant(MaskVal, dl, MVT::i32)); 10368 10369 // Replace the existing compare operand with the properly zero-extended one. 10370 SmallVector<SDValue, 4> Ops; 10371 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10372 Ops.push_back(AtomicNode->getOperand(i)); 10373 Ops[2] = NewCmpOp; 10374 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10375 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10376 auto NodeTy = 10377 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10378 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10379 } 10380 10381 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10382 SelectionDAG &DAG) const { 10383 SDLoc dl(Op); 10384 // Create a stack slot that is 16-byte aligned. 10385 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10386 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10387 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10388 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10389 10390 // Store the input value into Value#0 of the stack slot. 10391 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10392 MachinePointerInfo()); 10393 // Load it out. 10394 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10395 } 10396 10397 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10398 SelectionDAG &DAG) const { 10399 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10400 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10401 10402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10403 // We have legal lowering for constant indices but not for variable ones. 10404 if (!C) 10405 return SDValue(); 10406 10407 EVT VT = Op.getValueType(); 10408 SDLoc dl(Op); 10409 SDValue V1 = Op.getOperand(0); 10410 SDValue V2 = Op.getOperand(1); 10411 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10412 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10413 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10414 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10415 unsigned InsertAtElement = C->getZExtValue(); 10416 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10417 if (Subtarget.isLittleEndian()) { 10418 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10419 } 10420 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10421 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10422 } 10423 return Op; 10424 } 10425 10426 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10427 SelectionDAG &DAG) const { 10428 SDLoc dl(Op); 10429 SDNode *N = Op.getNode(); 10430 10431 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10432 "Unknown extract_vector_elt type"); 10433 10434 SDValue Value = N->getOperand(0); 10435 10436 // The first part of this is like the store lowering except that we don't 10437 // need to track the chain. 10438 10439 // The values are now known to be -1 (false) or 1 (true). To convert this 10440 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10441 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10442 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10443 10444 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10445 // understand how to form the extending load. 10446 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10447 10448 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10449 10450 // Now convert to an integer and store. 10451 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10452 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10453 Value); 10454 10455 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10456 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10457 MachinePointerInfo PtrInfo = 10458 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10459 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10460 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10461 10462 SDValue StoreChain = DAG.getEntryNode(); 10463 SDValue Ops[] = {StoreChain, 10464 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10465 Value, FIdx}; 10466 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10467 10468 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10469 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10470 10471 // Extract the value requested. 10472 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10473 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10474 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10475 10476 SDValue IntVal = 10477 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10478 10479 if (!Subtarget.useCRBits()) 10480 return IntVal; 10481 10482 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10483 } 10484 10485 /// Lowering for QPX v4i1 loads 10486 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10487 SelectionDAG &DAG) const { 10488 SDLoc dl(Op); 10489 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10490 SDValue LoadChain = LN->getChain(); 10491 SDValue BasePtr = LN->getBasePtr(); 10492 10493 if (Op.getValueType() == MVT::v4f64 || 10494 Op.getValueType() == MVT::v4f32) { 10495 EVT MemVT = LN->getMemoryVT(); 10496 unsigned Alignment = LN->getAlignment(); 10497 10498 // If this load is properly aligned, then it is legal. 10499 if (Alignment >= MemVT.getStoreSize()) 10500 return Op; 10501 10502 EVT ScalarVT = Op.getValueType().getScalarType(), 10503 ScalarMemVT = MemVT.getScalarType(); 10504 unsigned Stride = ScalarMemVT.getStoreSize(); 10505 10506 SDValue Vals[4], LoadChains[4]; 10507 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10508 SDValue Load; 10509 if (ScalarVT != ScalarMemVT) 10510 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10511 BasePtr, 10512 LN->getPointerInfo().getWithOffset(Idx * Stride), 10513 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10514 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10515 else 10516 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10517 LN->getPointerInfo().getWithOffset(Idx * Stride), 10518 MinAlign(Alignment, Idx * Stride), 10519 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10520 10521 if (Idx == 0 && LN->isIndexed()) { 10522 assert(LN->getAddressingMode() == ISD::PRE_INC && 10523 "Unknown addressing mode on vector load"); 10524 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10525 LN->getAddressingMode()); 10526 } 10527 10528 Vals[Idx] = Load; 10529 LoadChains[Idx] = Load.getValue(1); 10530 10531 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10532 DAG.getConstant(Stride, dl, 10533 BasePtr.getValueType())); 10534 } 10535 10536 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10537 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10538 10539 if (LN->isIndexed()) { 10540 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10541 return DAG.getMergeValues(RetOps, dl); 10542 } 10543 10544 SDValue RetOps[] = { Value, TF }; 10545 return DAG.getMergeValues(RetOps, dl); 10546 } 10547 10548 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10549 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10550 10551 // To lower v4i1 from a byte array, we load the byte elements of the 10552 // vector and then reuse the BUILD_VECTOR logic. 10553 10554 SDValue VectElmts[4], VectElmtChains[4]; 10555 for (unsigned i = 0; i < 4; ++i) { 10556 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10557 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10558 10559 VectElmts[i] = DAG.getExtLoad( 10560 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10561 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10562 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10563 VectElmtChains[i] = VectElmts[i].getValue(1); 10564 } 10565 10566 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10567 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10568 10569 SDValue RVals[] = { Value, LoadChain }; 10570 return DAG.getMergeValues(RVals, dl); 10571 } 10572 10573 /// Lowering for QPX v4i1 stores 10574 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10575 SelectionDAG &DAG) const { 10576 SDLoc dl(Op); 10577 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10578 SDValue StoreChain = SN->getChain(); 10579 SDValue BasePtr = SN->getBasePtr(); 10580 SDValue Value = SN->getValue(); 10581 10582 if (Value.getValueType() == MVT::v4f64 || 10583 Value.getValueType() == MVT::v4f32) { 10584 EVT MemVT = SN->getMemoryVT(); 10585 unsigned Alignment = SN->getAlignment(); 10586 10587 // If this store is properly aligned, then it is legal. 10588 if (Alignment >= MemVT.getStoreSize()) 10589 return Op; 10590 10591 EVT ScalarVT = Value.getValueType().getScalarType(), 10592 ScalarMemVT = MemVT.getScalarType(); 10593 unsigned Stride = ScalarMemVT.getStoreSize(); 10594 10595 SDValue Stores[4]; 10596 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10597 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10598 DAG.getVectorIdxConstant(Idx, dl)); 10599 SDValue Store; 10600 if (ScalarVT != ScalarMemVT) 10601 Store = 10602 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10603 SN->getPointerInfo().getWithOffset(Idx * Stride), 10604 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10605 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10606 else 10607 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10608 SN->getPointerInfo().getWithOffset(Idx * Stride), 10609 MinAlign(Alignment, Idx * Stride), 10610 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10611 10612 if (Idx == 0 && SN->isIndexed()) { 10613 assert(SN->getAddressingMode() == ISD::PRE_INC && 10614 "Unknown addressing mode on vector store"); 10615 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10616 SN->getAddressingMode()); 10617 } 10618 10619 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10620 DAG.getConstant(Stride, dl, 10621 BasePtr.getValueType())); 10622 Stores[Idx] = Store; 10623 } 10624 10625 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10626 10627 if (SN->isIndexed()) { 10628 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10629 return DAG.getMergeValues(RetOps, dl); 10630 } 10631 10632 return TF; 10633 } 10634 10635 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10636 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10637 10638 // The values are now known to be -1 (false) or 1 (true). To convert this 10639 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10640 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10641 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10642 10643 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10644 // understand how to form the extending load. 10645 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10646 10647 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10648 10649 // Now convert to an integer and store. 10650 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10651 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10652 Value); 10653 10654 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10655 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10656 MachinePointerInfo PtrInfo = 10657 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10658 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10659 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10660 10661 SDValue Ops[] = {StoreChain, 10662 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10663 Value, FIdx}; 10664 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10665 10666 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10667 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10668 10669 // Move data into the byte array. 10670 SDValue Loads[4], LoadChains[4]; 10671 for (unsigned i = 0; i < 4; ++i) { 10672 unsigned Offset = 4*i; 10673 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10674 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10675 10676 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10677 PtrInfo.getWithOffset(Offset)); 10678 LoadChains[i] = Loads[i].getValue(1); 10679 } 10680 10681 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10682 10683 SDValue Stores[4]; 10684 for (unsigned i = 0; i < 4; ++i) { 10685 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10686 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10687 10688 Stores[i] = DAG.getTruncStore( 10689 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10690 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10691 SN->getAAInfo()); 10692 } 10693 10694 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10695 10696 return StoreChain; 10697 } 10698 10699 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10700 SDLoc dl(Op); 10701 if (Op.getValueType() == MVT::v4i32) { 10702 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10703 10704 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10705 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10706 10707 SDValue RHSSwap = // = vrlw RHS, 16 10708 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10709 10710 // Shrinkify inputs to v8i16. 10711 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10712 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10713 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10714 10715 // Low parts multiplied together, generating 32-bit results (we ignore the 10716 // top parts). 10717 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10718 LHS, RHS, DAG, dl, MVT::v4i32); 10719 10720 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10721 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10722 // Shift the high parts up 16 bits. 10723 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10724 Neg16, DAG, dl); 10725 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10726 } else if (Op.getValueType() == MVT::v16i8) { 10727 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10728 bool isLittleEndian = Subtarget.isLittleEndian(); 10729 10730 // Multiply the even 8-bit parts, producing 16-bit sums. 10731 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10732 LHS, RHS, DAG, dl, MVT::v8i16); 10733 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10734 10735 // Multiply the odd 8-bit parts, producing 16-bit sums. 10736 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10737 LHS, RHS, DAG, dl, MVT::v8i16); 10738 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10739 10740 // Merge the results together. Because vmuleub and vmuloub are 10741 // instructions with a big-endian bias, we must reverse the 10742 // element numbering and reverse the meaning of "odd" and "even" 10743 // when generating little endian code. 10744 int Ops[16]; 10745 for (unsigned i = 0; i != 8; ++i) { 10746 if (isLittleEndian) { 10747 Ops[i*2 ] = 2*i; 10748 Ops[i*2+1] = 2*i+16; 10749 } else { 10750 Ops[i*2 ] = 2*i+1; 10751 Ops[i*2+1] = 2*i+1+16; 10752 } 10753 } 10754 if (isLittleEndian) 10755 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10756 else 10757 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10758 } else { 10759 llvm_unreachable("Unknown mul to lower!"); 10760 } 10761 } 10762 10763 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10764 10765 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10766 10767 EVT VT = Op.getValueType(); 10768 assert(VT.isVector() && 10769 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10770 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10771 VT == MVT::v16i8) && 10772 "Unexpected vector element type!"); 10773 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10774 "Current subtarget doesn't support smax v2i64!"); 10775 10776 // For vector abs, it can be lowered to: 10777 // abs x 10778 // ==> 10779 // y = -x 10780 // smax(x, y) 10781 10782 SDLoc dl(Op); 10783 SDValue X = Op.getOperand(0); 10784 SDValue Zero = DAG.getConstant(0, dl, VT); 10785 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10786 10787 // SMAX patch https://reviews.llvm.org/D47332 10788 // hasn't landed yet, so use intrinsic first here. 10789 // TODO: Should use SMAX directly once SMAX patch landed 10790 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10791 if (VT == MVT::v2i64) 10792 BifID = Intrinsic::ppc_altivec_vmaxsd; 10793 else if (VT == MVT::v8i16) 10794 BifID = Intrinsic::ppc_altivec_vmaxsh; 10795 else if (VT == MVT::v16i8) 10796 BifID = Intrinsic::ppc_altivec_vmaxsb; 10797 10798 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10799 } 10800 10801 // Custom lowering for fpext vf32 to v2f64 10802 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10803 10804 assert(Op.getOpcode() == ISD::FP_EXTEND && 10805 "Should only be called for ISD::FP_EXTEND"); 10806 10807 // FIXME: handle extends from half precision float vectors on P9. 10808 // We only want to custom lower an extend from v2f32 to v2f64. 10809 if (Op.getValueType() != MVT::v2f64 || 10810 Op.getOperand(0).getValueType() != MVT::v2f32) 10811 return SDValue(); 10812 10813 SDLoc dl(Op); 10814 SDValue Op0 = Op.getOperand(0); 10815 10816 switch (Op0.getOpcode()) { 10817 default: 10818 return SDValue(); 10819 case ISD::EXTRACT_SUBVECTOR: { 10820 assert(Op0.getNumOperands() == 2 && 10821 isa<ConstantSDNode>(Op0->getOperand(1)) && 10822 "Node should have 2 operands with second one being a constant!"); 10823 10824 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10825 return SDValue(); 10826 10827 // Custom lower is only done for high or low doubleword. 10828 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10829 if (Idx % 2 != 0) 10830 return SDValue(); 10831 10832 // Since input is v4f32, at this point Idx is either 0 or 2. 10833 // Shift to get the doubleword position we want. 10834 int DWord = Idx >> 1; 10835 10836 // High and low word positions are different on little endian. 10837 if (Subtarget.isLittleEndian()) 10838 DWord ^= 0x1; 10839 10840 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10841 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10842 } 10843 case ISD::FADD: 10844 case ISD::FMUL: 10845 case ISD::FSUB: { 10846 SDValue NewLoad[2]; 10847 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10848 // Ensure both input are loads. 10849 SDValue LdOp = Op0.getOperand(i); 10850 if (LdOp.getOpcode() != ISD::LOAD) 10851 return SDValue(); 10852 // Generate new load node. 10853 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10854 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10855 NewLoad[i] = DAG.getMemIntrinsicNode( 10856 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10857 LD->getMemoryVT(), LD->getMemOperand()); 10858 } 10859 SDValue NewOp = 10860 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10861 NewLoad[1], Op0.getNode()->getFlags()); 10862 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10863 DAG.getConstant(0, dl, MVT::i32)); 10864 } 10865 case ISD::LOAD: { 10866 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10867 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10868 SDValue NewLd = DAG.getMemIntrinsicNode( 10869 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10870 LD->getMemoryVT(), LD->getMemOperand()); 10871 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10872 DAG.getConstant(0, dl, MVT::i32)); 10873 } 10874 } 10875 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10876 } 10877 10878 /// LowerOperation - Provide custom lowering hooks for some operations. 10879 /// 10880 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10881 switch (Op.getOpcode()) { 10882 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10883 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10884 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10885 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10886 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10887 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10888 case ISD::SETCC: return LowerSETCC(Op, DAG); 10889 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10890 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10891 10892 // Variable argument lowering. 10893 case ISD::VASTART: return LowerVASTART(Op, DAG); 10894 case ISD::VAARG: return LowerVAARG(Op, DAG); 10895 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10896 10897 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10898 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10899 case ISD::GET_DYNAMIC_AREA_OFFSET: 10900 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10901 10902 // Exception handling lowering. 10903 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10904 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10905 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10906 10907 case ISD::LOAD: return LowerLOAD(Op, DAG); 10908 case ISD::STORE: return LowerSTORE(Op, DAG); 10909 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10910 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10911 case ISD::FP_TO_UINT: 10912 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10913 case ISD::UINT_TO_FP: 10914 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10915 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10916 10917 // Lower 64-bit shifts. 10918 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10919 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10920 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10921 10922 // Vector-related lowering. 10923 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10924 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10925 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10926 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10927 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10928 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10929 case ISD::MUL: return LowerMUL(Op, DAG); 10930 case ISD::ABS: return LowerABS(Op, DAG); 10931 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10932 10933 // For counter-based loop handling. 10934 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10935 10936 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10937 10938 // Frame & Return address. 10939 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10940 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10941 10942 case ISD::INTRINSIC_VOID: 10943 return LowerINTRINSIC_VOID(Op, DAG); 10944 case ISD::SREM: 10945 case ISD::UREM: 10946 return LowerREM(Op, DAG); 10947 case ISD::BSWAP: 10948 return LowerBSWAP(Op, DAG); 10949 case ISD::ATOMIC_CMP_SWAP: 10950 return LowerATOMIC_CMP_SWAP(Op, DAG); 10951 } 10952 } 10953 10954 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10955 SmallVectorImpl<SDValue>&Results, 10956 SelectionDAG &DAG) const { 10957 SDLoc dl(N); 10958 switch (N->getOpcode()) { 10959 default: 10960 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10961 case ISD::READCYCLECOUNTER: { 10962 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10963 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10964 10965 Results.push_back( 10966 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10967 Results.push_back(RTB.getValue(2)); 10968 break; 10969 } 10970 case ISD::INTRINSIC_W_CHAIN: { 10971 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10972 Intrinsic::loop_decrement) 10973 break; 10974 10975 assert(N->getValueType(0) == MVT::i1 && 10976 "Unexpected result type for CTR decrement intrinsic"); 10977 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10978 N->getValueType(0)); 10979 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10980 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10981 N->getOperand(1)); 10982 10983 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10984 Results.push_back(NewInt.getValue(1)); 10985 break; 10986 } 10987 case ISD::VAARG: { 10988 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10989 return; 10990 10991 EVT VT = N->getValueType(0); 10992 10993 if (VT == MVT::i64) { 10994 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10995 10996 Results.push_back(NewNode); 10997 Results.push_back(NewNode.getValue(1)); 10998 } 10999 return; 11000 } 11001 case ISD::FP_TO_SINT: 11002 case ISD::FP_TO_UINT: 11003 // LowerFP_TO_INT() can only handle f32 and f64. 11004 if (N->getOperand(0).getValueType() == MVT::ppcf128) 11005 return; 11006 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11007 return; 11008 case ISD::TRUNCATE: { 11009 EVT TrgVT = N->getValueType(0); 11010 EVT OpVT = N->getOperand(0).getValueType(); 11011 if (TrgVT.isVector() && 11012 isOperationCustom(N->getOpcode(), TrgVT) && 11013 OpVT.getSizeInBits() <= 128 && 11014 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 11015 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 11016 return; 11017 } 11018 case ISD::BITCAST: 11019 // Don't handle bitcast here. 11020 return; 11021 case ISD::FP_EXTEND: 11022 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11023 if (Lowered) 11024 Results.push_back(Lowered); 11025 return; 11026 } 11027 } 11028 11029 //===----------------------------------------------------------------------===// 11030 // Other Lowering Code 11031 //===----------------------------------------------------------------------===// 11032 11033 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11034 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11035 Function *Func = Intrinsic::getDeclaration(M, Id); 11036 return Builder.CreateCall(Func, {}); 11037 } 11038 11039 // The mappings for emitLeading/TrailingFence is taken from 11040 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11041 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11042 Instruction *Inst, 11043 AtomicOrdering Ord) const { 11044 if (Ord == AtomicOrdering::SequentiallyConsistent) 11045 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11046 if (isReleaseOrStronger(Ord)) 11047 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11048 return nullptr; 11049 } 11050 11051 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11052 Instruction *Inst, 11053 AtomicOrdering Ord) const { 11054 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11055 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11056 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11057 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11058 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11059 return Builder.CreateCall( 11060 Intrinsic::getDeclaration( 11061 Builder.GetInsertBlock()->getParent()->getParent(), 11062 Intrinsic::ppc_cfence, {Inst->getType()}), 11063 {Inst}); 11064 // FIXME: Can use isync for rmw operation. 11065 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11066 } 11067 return nullptr; 11068 } 11069 11070 MachineBasicBlock * 11071 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11072 unsigned AtomicSize, 11073 unsigned BinOpcode, 11074 unsigned CmpOpcode, 11075 unsigned CmpPred) const { 11076 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11077 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11078 11079 auto LoadMnemonic = PPC::LDARX; 11080 auto StoreMnemonic = PPC::STDCX; 11081 switch (AtomicSize) { 11082 default: 11083 llvm_unreachable("Unexpected size of atomic entity"); 11084 case 1: 11085 LoadMnemonic = PPC::LBARX; 11086 StoreMnemonic = PPC::STBCX; 11087 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11088 break; 11089 case 2: 11090 LoadMnemonic = PPC::LHARX; 11091 StoreMnemonic = PPC::STHCX; 11092 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11093 break; 11094 case 4: 11095 LoadMnemonic = PPC::LWARX; 11096 StoreMnemonic = PPC::STWCX; 11097 break; 11098 case 8: 11099 LoadMnemonic = PPC::LDARX; 11100 StoreMnemonic = PPC::STDCX; 11101 break; 11102 } 11103 11104 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11105 MachineFunction *F = BB->getParent(); 11106 MachineFunction::iterator It = ++BB->getIterator(); 11107 11108 Register dest = MI.getOperand(0).getReg(); 11109 Register ptrA = MI.getOperand(1).getReg(); 11110 Register ptrB = MI.getOperand(2).getReg(); 11111 Register incr = MI.getOperand(3).getReg(); 11112 DebugLoc dl = MI.getDebugLoc(); 11113 11114 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11115 MachineBasicBlock *loop2MBB = 11116 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11117 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11118 F->insert(It, loopMBB); 11119 if (CmpOpcode) 11120 F->insert(It, loop2MBB); 11121 F->insert(It, exitMBB); 11122 exitMBB->splice(exitMBB->begin(), BB, 11123 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11124 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11125 11126 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11127 Register TmpReg = (!BinOpcode) ? incr : 11128 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11129 : &PPC::GPRCRegClass); 11130 11131 // thisMBB: 11132 // ... 11133 // fallthrough --> loopMBB 11134 BB->addSuccessor(loopMBB); 11135 11136 // loopMBB: 11137 // l[wd]arx dest, ptr 11138 // add r0, dest, incr 11139 // st[wd]cx. r0, ptr 11140 // bne- loopMBB 11141 // fallthrough --> exitMBB 11142 11143 // For max/min... 11144 // loopMBB: 11145 // l[wd]arx dest, ptr 11146 // cmpl?[wd] incr, dest 11147 // bgt exitMBB 11148 // loop2MBB: 11149 // st[wd]cx. dest, ptr 11150 // bne- loopMBB 11151 // fallthrough --> exitMBB 11152 11153 BB = loopMBB; 11154 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11155 .addReg(ptrA).addReg(ptrB); 11156 if (BinOpcode) 11157 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11158 if (CmpOpcode) { 11159 // Signed comparisons of byte or halfword values must be sign-extended. 11160 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11161 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11162 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11163 ExtReg).addReg(dest); 11164 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11165 .addReg(incr).addReg(ExtReg); 11166 } else 11167 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11168 .addReg(incr).addReg(dest); 11169 11170 BuildMI(BB, dl, TII->get(PPC::BCC)) 11171 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11172 BB->addSuccessor(loop2MBB); 11173 BB->addSuccessor(exitMBB); 11174 BB = loop2MBB; 11175 } 11176 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11177 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11178 BuildMI(BB, dl, TII->get(PPC::BCC)) 11179 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11180 BB->addSuccessor(loopMBB); 11181 BB->addSuccessor(exitMBB); 11182 11183 // exitMBB: 11184 // ... 11185 BB = exitMBB; 11186 return BB; 11187 } 11188 11189 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11190 MachineInstr &MI, MachineBasicBlock *BB, 11191 bool is8bit, // operation 11192 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11193 // If we support part-word atomic mnemonics, just use them 11194 if (Subtarget.hasPartwordAtomics()) 11195 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11196 CmpPred); 11197 11198 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11199 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11200 // In 64 bit mode we have to use 64 bits for addresses, even though the 11201 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11202 // registers without caring whether they're 32 or 64, but here we're 11203 // doing actual arithmetic on the addresses. 11204 bool is64bit = Subtarget.isPPC64(); 11205 bool isLittleEndian = Subtarget.isLittleEndian(); 11206 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11207 11208 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11209 MachineFunction *F = BB->getParent(); 11210 MachineFunction::iterator It = ++BB->getIterator(); 11211 11212 Register dest = MI.getOperand(0).getReg(); 11213 Register ptrA = MI.getOperand(1).getReg(); 11214 Register ptrB = MI.getOperand(2).getReg(); 11215 Register incr = MI.getOperand(3).getReg(); 11216 DebugLoc dl = MI.getDebugLoc(); 11217 11218 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11219 MachineBasicBlock *loop2MBB = 11220 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11221 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11222 F->insert(It, loopMBB); 11223 if (CmpOpcode) 11224 F->insert(It, loop2MBB); 11225 F->insert(It, exitMBB); 11226 exitMBB->splice(exitMBB->begin(), BB, 11227 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11228 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11229 11230 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11231 const TargetRegisterClass *RC = 11232 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11233 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11234 11235 Register PtrReg = RegInfo.createVirtualRegister(RC); 11236 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11237 Register ShiftReg = 11238 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11239 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11240 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11241 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11242 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11243 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11244 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11245 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11246 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11247 Register Ptr1Reg; 11248 Register TmpReg = 11249 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11250 11251 // thisMBB: 11252 // ... 11253 // fallthrough --> loopMBB 11254 BB->addSuccessor(loopMBB); 11255 11256 // The 4-byte load must be aligned, while a char or short may be 11257 // anywhere in the word. Hence all this nasty bookkeeping code. 11258 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11259 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11260 // xori shift, shift1, 24 [16] 11261 // rlwinm ptr, ptr1, 0, 0, 29 11262 // slw incr2, incr, shift 11263 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11264 // slw mask, mask2, shift 11265 // loopMBB: 11266 // lwarx tmpDest, ptr 11267 // add tmp, tmpDest, incr2 11268 // andc tmp2, tmpDest, mask 11269 // and tmp3, tmp, mask 11270 // or tmp4, tmp3, tmp2 11271 // stwcx. tmp4, ptr 11272 // bne- loopMBB 11273 // fallthrough --> exitMBB 11274 // srw dest, tmpDest, shift 11275 if (ptrA != ZeroReg) { 11276 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11277 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11278 .addReg(ptrA) 11279 .addReg(ptrB); 11280 } else { 11281 Ptr1Reg = ptrB; 11282 } 11283 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11284 // mode. 11285 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11286 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11287 .addImm(3) 11288 .addImm(27) 11289 .addImm(is8bit ? 28 : 27); 11290 if (!isLittleEndian) 11291 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11292 .addReg(Shift1Reg) 11293 .addImm(is8bit ? 24 : 16); 11294 if (is64bit) 11295 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11296 .addReg(Ptr1Reg) 11297 .addImm(0) 11298 .addImm(61); 11299 else 11300 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11301 .addReg(Ptr1Reg) 11302 .addImm(0) 11303 .addImm(0) 11304 .addImm(29); 11305 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11306 if (is8bit) 11307 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11308 else { 11309 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11310 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11311 .addReg(Mask3Reg) 11312 .addImm(65535); 11313 } 11314 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11315 .addReg(Mask2Reg) 11316 .addReg(ShiftReg); 11317 11318 BB = loopMBB; 11319 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11320 .addReg(ZeroReg) 11321 .addReg(PtrReg); 11322 if (BinOpcode) 11323 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11324 .addReg(Incr2Reg) 11325 .addReg(TmpDestReg); 11326 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11327 .addReg(TmpDestReg) 11328 .addReg(MaskReg); 11329 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11330 if (CmpOpcode) { 11331 // For unsigned comparisons, we can directly compare the shifted values. 11332 // For signed comparisons we shift and sign extend. 11333 Register SReg = RegInfo.createVirtualRegister(GPRC); 11334 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11335 .addReg(TmpDestReg) 11336 .addReg(MaskReg); 11337 unsigned ValueReg = SReg; 11338 unsigned CmpReg = Incr2Reg; 11339 if (CmpOpcode == PPC::CMPW) { 11340 ValueReg = RegInfo.createVirtualRegister(GPRC); 11341 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11342 .addReg(SReg) 11343 .addReg(ShiftReg); 11344 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11345 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11346 .addReg(ValueReg); 11347 ValueReg = ValueSReg; 11348 CmpReg = incr; 11349 } 11350 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11351 .addReg(CmpReg) 11352 .addReg(ValueReg); 11353 BuildMI(BB, dl, TII->get(PPC::BCC)) 11354 .addImm(CmpPred) 11355 .addReg(PPC::CR0) 11356 .addMBB(exitMBB); 11357 BB->addSuccessor(loop2MBB); 11358 BB->addSuccessor(exitMBB); 11359 BB = loop2MBB; 11360 } 11361 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11362 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11363 .addReg(Tmp4Reg) 11364 .addReg(ZeroReg) 11365 .addReg(PtrReg); 11366 BuildMI(BB, dl, TII->get(PPC::BCC)) 11367 .addImm(PPC::PRED_NE) 11368 .addReg(PPC::CR0) 11369 .addMBB(loopMBB); 11370 BB->addSuccessor(loopMBB); 11371 BB->addSuccessor(exitMBB); 11372 11373 // exitMBB: 11374 // ... 11375 BB = exitMBB; 11376 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11377 .addReg(TmpDestReg) 11378 .addReg(ShiftReg); 11379 return BB; 11380 } 11381 11382 llvm::MachineBasicBlock * 11383 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11384 MachineBasicBlock *MBB) const { 11385 DebugLoc DL = MI.getDebugLoc(); 11386 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11387 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11388 11389 MachineFunction *MF = MBB->getParent(); 11390 MachineRegisterInfo &MRI = MF->getRegInfo(); 11391 11392 const BasicBlock *BB = MBB->getBasicBlock(); 11393 MachineFunction::iterator I = ++MBB->getIterator(); 11394 11395 Register DstReg = MI.getOperand(0).getReg(); 11396 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11397 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11398 Register mainDstReg = MRI.createVirtualRegister(RC); 11399 Register restoreDstReg = MRI.createVirtualRegister(RC); 11400 11401 MVT PVT = getPointerTy(MF->getDataLayout()); 11402 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11403 "Invalid Pointer Size!"); 11404 // For v = setjmp(buf), we generate 11405 // 11406 // thisMBB: 11407 // SjLjSetup mainMBB 11408 // bl mainMBB 11409 // v_restore = 1 11410 // b sinkMBB 11411 // 11412 // mainMBB: 11413 // buf[LabelOffset] = LR 11414 // v_main = 0 11415 // 11416 // sinkMBB: 11417 // v = phi(main, restore) 11418 // 11419 11420 MachineBasicBlock *thisMBB = MBB; 11421 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11422 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11423 MF->insert(I, mainMBB); 11424 MF->insert(I, sinkMBB); 11425 11426 MachineInstrBuilder MIB; 11427 11428 // Transfer the remainder of BB and its successor edges to sinkMBB. 11429 sinkMBB->splice(sinkMBB->begin(), MBB, 11430 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11431 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11432 11433 // Note that the structure of the jmp_buf used here is not compatible 11434 // with that used by libc, and is not designed to be. Specifically, it 11435 // stores only those 'reserved' registers that LLVM does not otherwise 11436 // understand how to spill. Also, by convention, by the time this 11437 // intrinsic is called, Clang has already stored the frame address in the 11438 // first slot of the buffer and stack address in the third. Following the 11439 // X86 target code, we'll store the jump address in the second slot. We also 11440 // need to save the TOC pointer (R2) to handle jumps between shared 11441 // libraries, and that will be stored in the fourth slot. The thread 11442 // identifier (R13) is not affected. 11443 11444 // thisMBB: 11445 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11446 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11447 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11448 11449 // Prepare IP either in reg. 11450 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11451 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11452 Register BufReg = MI.getOperand(1).getReg(); 11453 11454 if (Subtarget.is64BitELFABI()) { 11455 setUsesTOCBasePtr(*MBB->getParent()); 11456 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11457 .addReg(PPC::X2) 11458 .addImm(TOCOffset) 11459 .addReg(BufReg) 11460 .cloneMemRefs(MI); 11461 } 11462 11463 // Naked functions never have a base pointer, and so we use r1. For all 11464 // other functions, this decision must be delayed until during PEI. 11465 unsigned BaseReg; 11466 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11467 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11468 else 11469 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11470 11471 MIB = BuildMI(*thisMBB, MI, DL, 11472 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11473 .addReg(BaseReg) 11474 .addImm(BPOffset) 11475 .addReg(BufReg) 11476 .cloneMemRefs(MI); 11477 11478 // Setup 11479 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11480 MIB.addRegMask(TRI->getNoPreservedMask()); 11481 11482 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11483 11484 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11485 .addMBB(mainMBB); 11486 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11487 11488 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11489 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11490 11491 // mainMBB: 11492 // mainDstReg = 0 11493 MIB = 11494 BuildMI(mainMBB, DL, 11495 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11496 11497 // Store IP 11498 if (Subtarget.isPPC64()) { 11499 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11500 .addReg(LabelReg) 11501 .addImm(LabelOffset) 11502 .addReg(BufReg); 11503 } else { 11504 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11505 .addReg(LabelReg) 11506 .addImm(LabelOffset) 11507 .addReg(BufReg); 11508 } 11509 MIB.cloneMemRefs(MI); 11510 11511 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11512 mainMBB->addSuccessor(sinkMBB); 11513 11514 // sinkMBB: 11515 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11516 TII->get(PPC::PHI), DstReg) 11517 .addReg(mainDstReg).addMBB(mainMBB) 11518 .addReg(restoreDstReg).addMBB(thisMBB); 11519 11520 MI.eraseFromParent(); 11521 return sinkMBB; 11522 } 11523 11524 MachineBasicBlock * 11525 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11526 MachineBasicBlock *MBB) const { 11527 DebugLoc DL = MI.getDebugLoc(); 11528 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11529 11530 MachineFunction *MF = MBB->getParent(); 11531 MachineRegisterInfo &MRI = MF->getRegInfo(); 11532 11533 MVT PVT = getPointerTy(MF->getDataLayout()); 11534 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11535 "Invalid Pointer Size!"); 11536 11537 const TargetRegisterClass *RC = 11538 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11539 Register Tmp = MRI.createVirtualRegister(RC); 11540 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11541 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11542 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11543 unsigned BP = 11544 (PVT == MVT::i64) 11545 ? PPC::X30 11546 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11547 : PPC::R30); 11548 11549 MachineInstrBuilder MIB; 11550 11551 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11552 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11553 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11554 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11555 11556 Register BufReg = MI.getOperand(0).getReg(); 11557 11558 // Reload FP (the jumped-to function may not have had a 11559 // frame pointer, and if so, then its r31 will be restored 11560 // as necessary). 11561 if (PVT == MVT::i64) { 11562 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11563 .addImm(0) 11564 .addReg(BufReg); 11565 } else { 11566 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11567 .addImm(0) 11568 .addReg(BufReg); 11569 } 11570 MIB.cloneMemRefs(MI); 11571 11572 // Reload IP 11573 if (PVT == MVT::i64) { 11574 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11575 .addImm(LabelOffset) 11576 .addReg(BufReg); 11577 } else { 11578 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11579 .addImm(LabelOffset) 11580 .addReg(BufReg); 11581 } 11582 MIB.cloneMemRefs(MI); 11583 11584 // Reload SP 11585 if (PVT == MVT::i64) { 11586 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11587 .addImm(SPOffset) 11588 .addReg(BufReg); 11589 } else { 11590 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11591 .addImm(SPOffset) 11592 .addReg(BufReg); 11593 } 11594 MIB.cloneMemRefs(MI); 11595 11596 // Reload BP 11597 if (PVT == MVT::i64) { 11598 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11599 .addImm(BPOffset) 11600 .addReg(BufReg); 11601 } else { 11602 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11603 .addImm(BPOffset) 11604 .addReg(BufReg); 11605 } 11606 MIB.cloneMemRefs(MI); 11607 11608 // Reload TOC 11609 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11610 setUsesTOCBasePtr(*MBB->getParent()); 11611 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11612 .addImm(TOCOffset) 11613 .addReg(BufReg) 11614 .cloneMemRefs(MI); 11615 } 11616 11617 // Jump 11618 BuildMI(*MBB, MI, DL, 11619 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11620 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11621 11622 MI.eraseFromParent(); 11623 return MBB; 11624 } 11625 11626 MachineBasicBlock * 11627 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11628 MachineBasicBlock *BB) const { 11629 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11630 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11631 if (Subtarget.is64BitELFABI() && 11632 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11633 !Subtarget.isUsingPCRelativeCalls()) { 11634 // Call lowering should have added an r2 operand to indicate a dependence 11635 // on the TOC base pointer value. It can't however, because there is no 11636 // way to mark the dependence as implicit there, and so the stackmap code 11637 // will confuse it with a regular operand. Instead, add the dependence 11638 // here. 11639 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11640 } 11641 11642 return emitPatchPoint(MI, BB); 11643 } 11644 11645 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11646 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11647 return emitEHSjLjSetJmp(MI, BB); 11648 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11649 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11650 return emitEHSjLjLongJmp(MI, BB); 11651 } 11652 11653 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11654 11655 // To "insert" these instructions we actually have to insert their 11656 // control-flow patterns. 11657 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11658 MachineFunction::iterator It = ++BB->getIterator(); 11659 11660 MachineFunction *F = BB->getParent(); 11661 11662 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11663 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11664 MI.getOpcode() == PPC::SELECT_I8) { 11665 SmallVector<MachineOperand, 2> Cond; 11666 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11667 MI.getOpcode() == PPC::SELECT_CC_I8) 11668 Cond.push_back(MI.getOperand(4)); 11669 else 11670 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11671 Cond.push_back(MI.getOperand(1)); 11672 11673 DebugLoc dl = MI.getDebugLoc(); 11674 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11675 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11676 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11677 MI.getOpcode() == PPC::SELECT_CC_F8 || 11678 MI.getOpcode() == PPC::SELECT_CC_F16 || 11679 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11680 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11681 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11682 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11683 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11684 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11685 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11686 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11687 MI.getOpcode() == PPC::SELECT_CC_SPE || 11688 MI.getOpcode() == PPC::SELECT_F4 || 11689 MI.getOpcode() == PPC::SELECT_F8 || 11690 MI.getOpcode() == PPC::SELECT_F16 || 11691 MI.getOpcode() == PPC::SELECT_QFRC || 11692 MI.getOpcode() == PPC::SELECT_QSRC || 11693 MI.getOpcode() == PPC::SELECT_QBRC || 11694 MI.getOpcode() == PPC::SELECT_SPE || 11695 MI.getOpcode() == PPC::SELECT_SPE4 || 11696 MI.getOpcode() == PPC::SELECT_VRRC || 11697 MI.getOpcode() == PPC::SELECT_VSFRC || 11698 MI.getOpcode() == PPC::SELECT_VSSRC || 11699 MI.getOpcode() == PPC::SELECT_VSRC) { 11700 // The incoming instruction knows the destination vreg to set, the 11701 // condition code register to branch on, the true/false values to 11702 // select between, and a branch opcode to use. 11703 11704 // thisMBB: 11705 // ... 11706 // TrueVal = ... 11707 // cmpTY ccX, r1, r2 11708 // bCC copy1MBB 11709 // fallthrough --> copy0MBB 11710 MachineBasicBlock *thisMBB = BB; 11711 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11712 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11713 DebugLoc dl = MI.getDebugLoc(); 11714 F->insert(It, copy0MBB); 11715 F->insert(It, sinkMBB); 11716 11717 // Transfer the remainder of BB and its successor edges to sinkMBB. 11718 sinkMBB->splice(sinkMBB->begin(), BB, 11719 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11720 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11721 11722 // Next, add the true and fallthrough blocks as its successors. 11723 BB->addSuccessor(copy0MBB); 11724 BB->addSuccessor(sinkMBB); 11725 11726 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11727 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11728 MI.getOpcode() == PPC::SELECT_F16 || 11729 MI.getOpcode() == PPC::SELECT_SPE4 || 11730 MI.getOpcode() == PPC::SELECT_SPE || 11731 MI.getOpcode() == PPC::SELECT_QFRC || 11732 MI.getOpcode() == PPC::SELECT_QSRC || 11733 MI.getOpcode() == PPC::SELECT_QBRC || 11734 MI.getOpcode() == PPC::SELECT_VRRC || 11735 MI.getOpcode() == PPC::SELECT_VSFRC || 11736 MI.getOpcode() == PPC::SELECT_VSSRC || 11737 MI.getOpcode() == PPC::SELECT_VSRC) { 11738 BuildMI(BB, dl, TII->get(PPC::BC)) 11739 .addReg(MI.getOperand(1).getReg()) 11740 .addMBB(sinkMBB); 11741 } else { 11742 unsigned SelectPred = MI.getOperand(4).getImm(); 11743 BuildMI(BB, dl, TII->get(PPC::BCC)) 11744 .addImm(SelectPred) 11745 .addReg(MI.getOperand(1).getReg()) 11746 .addMBB(sinkMBB); 11747 } 11748 11749 // copy0MBB: 11750 // %FalseValue = ... 11751 // # fallthrough to sinkMBB 11752 BB = copy0MBB; 11753 11754 // Update machine-CFG edges 11755 BB->addSuccessor(sinkMBB); 11756 11757 // sinkMBB: 11758 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11759 // ... 11760 BB = sinkMBB; 11761 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11762 .addReg(MI.getOperand(3).getReg()) 11763 .addMBB(copy0MBB) 11764 .addReg(MI.getOperand(2).getReg()) 11765 .addMBB(thisMBB); 11766 } else if (MI.getOpcode() == PPC::ReadTB) { 11767 // To read the 64-bit time-base register on a 32-bit target, we read the 11768 // two halves. Should the counter have wrapped while it was being read, we 11769 // need to try again. 11770 // ... 11771 // readLoop: 11772 // mfspr Rx,TBU # load from TBU 11773 // mfspr Ry,TB # load from TB 11774 // mfspr Rz,TBU # load from TBU 11775 // cmpw crX,Rx,Rz # check if 'old'='new' 11776 // bne readLoop # branch if they're not equal 11777 // ... 11778 11779 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11780 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11781 DebugLoc dl = MI.getDebugLoc(); 11782 F->insert(It, readMBB); 11783 F->insert(It, sinkMBB); 11784 11785 // Transfer the remainder of BB and its successor edges to sinkMBB. 11786 sinkMBB->splice(sinkMBB->begin(), BB, 11787 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11788 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11789 11790 BB->addSuccessor(readMBB); 11791 BB = readMBB; 11792 11793 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11794 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11795 Register LoReg = MI.getOperand(0).getReg(); 11796 Register HiReg = MI.getOperand(1).getReg(); 11797 11798 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11799 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11800 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11801 11802 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11803 11804 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11805 .addReg(HiReg) 11806 .addReg(ReadAgainReg); 11807 BuildMI(BB, dl, TII->get(PPC::BCC)) 11808 .addImm(PPC::PRED_NE) 11809 .addReg(CmpReg) 11810 .addMBB(readMBB); 11811 11812 BB->addSuccessor(readMBB); 11813 BB->addSuccessor(sinkMBB); 11814 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11815 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11817 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11819 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11821 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11822 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11824 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11826 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11828 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11830 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11831 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11833 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11835 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11837 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11839 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11840 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11842 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11844 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11846 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11848 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11849 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11851 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11853 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11855 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11857 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11858 11859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11860 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11862 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11863 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11864 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11866 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11867 11868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11869 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11871 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11872 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11873 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11874 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11875 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11876 11877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11878 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11880 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11881 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11882 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11883 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11884 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11885 11886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11887 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11889 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11890 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11891 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11892 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11893 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11894 11895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11896 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11898 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11899 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11900 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11901 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11902 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11903 11904 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11905 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11906 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11907 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11908 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11909 BB = EmitAtomicBinary(MI, BB, 4, 0); 11910 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11911 BB = EmitAtomicBinary(MI, BB, 8, 0); 11912 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11913 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11914 (Subtarget.hasPartwordAtomics() && 11915 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11916 (Subtarget.hasPartwordAtomics() && 11917 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11918 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11919 11920 auto LoadMnemonic = PPC::LDARX; 11921 auto StoreMnemonic = PPC::STDCX; 11922 switch (MI.getOpcode()) { 11923 default: 11924 llvm_unreachable("Compare and swap of unknown size"); 11925 case PPC::ATOMIC_CMP_SWAP_I8: 11926 LoadMnemonic = PPC::LBARX; 11927 StoreMnemonic = PPC::STBCX; 11928 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11929 break; 11930 case PPC::ATOMIC_CMP_SWAP_I16: 11931 LoadMnemonic = PPC::LHARX; 11932 StoreMnemonic = PPC::STHCX; 11933 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11934 break; 11935 case PPC::ATOMIC_CMP_SWAP_I32: 11936 LoadMnemonic = PPC::LWARX; 11937 StoreMnemonic = PPC::STWCX; 11938 break; 11939 case PPC::ATOMIC_CMP_SWAP_I64: 11940 LoadMnemonic = PPC::LDARX; 11941 StoreMnemonic = PPC::STDCX; 11942 break; 11943 } 11944 Register dest = MI.getOperand(0).getReg(); 11945 Register ptrA = MI.getOperand(1).getReg(); 11946 Register ptrB = MI.getOperand(2).getReg(); 11947 Register oldval = MI.getOperand(3).getReg(); 11948 Register newval = MI.getOperand(4).getReg(); 11949 DebugLoc dl = MI.getDebugLoc(); 11950 11951 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11952 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11953 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11954 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11955 F->insert(It, loop1MBB); 11956 F->insert(It, loop2MBB); 11957 F->insert(It, midMBB); 11958 F->insert(It, exitMBB); 11959 exitMBB->splice(exitMBB->begin(), BB, 11960 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11961 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11962 11963 // thisMBB: 11964 // ... 11965 // fallthrough --> loopMBB 11966 BB->addSuccessor(loop1MBB); 11967 11968 // loop1MBB: 11969 // l[bhwd]arx dest, ptr 11970 // cmp[wd] dest, oldval 11971 // bne- midMBB 11972 // loop2MBB: 11973 // st[bhwd]cx. newval, ptr 11974 // bne- loopMBB 11975 // b exitBB 11976 // midMBB: 11977 // st[bhwd]cx. dest, ptr 11978 // exitBB: 11979 BB = loop1MBB; 11980 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11981 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11982 .addReg(oldval) 11983 .addReg(dest); 11984 BuildMI(BB, dl, TII->get(PPC::BCC)) 11985 .addImm(PPC::PRED_NE) 11986 .addReg(PPC::CR0) 11987 .addMBB(midMBB); 11988 BB->addSuccessor(loop2MBB); 11989 BB->addSuccessor(midMBB); 11990 11991 BB = loop2MBB; 11992 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11993 .addReg(newval) 11994 .addReg(ptrA) 11995 .addReg(ptrB); 11996 BuildMI(BB, dl, TII->get(PPC::BCC)) 11997 .addImm(PPC::PRED_NE) 11998 .addReg(PPC::CR0) 11999 .addMBB(loop1MBB); 12000 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12001 BB->addSuccessor(loop1MBB); 12002 BB->addSuccessor(exitMBB); 12003 12004 BB = midMBB; 12005 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12006 .addReg(dest) 12007 .addReg(ptrA) 12008 .addReg(ptrB); 12009 BB->addSuccessor(exitMBB); 12010 12011 // exitMBB: 12012 // ... 12013 BB = exitMBB; 12014 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12015 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12016 // We must use 64-bit registers for addresses when targeting 64-bit, 12017 // since we're actually doing arithmetic on them. Other registers 12018 // can be 32-bit. 12019 bool is64bit = Subtarget.isPPC64(); 12020 bool isLittleEndian = Subtarget.isLittleEndian(); 12021 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12022 12023 Register dest = MI.getOperand(0).getReg(); 12024 Register ptrA = MI.getOperand(1).getReg(); 12025 Register ptrB = MI.getOperand(2).getReg(); 12026 Register oldval = MI.getOperand(3).getReg(); 12027 Register newval = MI.getOperand(4).getReg(); 12028 DebugLoc dl = MI.getDebugLoc(); 12029 12030 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12031 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12032 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12033 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12034 F->insert(It, loop1MBB); 12035 F->insert(It, loop2MBB); 12036 F->insert(It, midMBB); 12037 F->insert(It, exitMBB); 12038 exitMBB->splice(exitMBB->begin(), BB, 12039 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12040 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12041 12042 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12043 const TargetRegisterClass *RC = 12044 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12045 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12046 12047 Register PtrReg = RegInfo.createVirtualRegister(RC); 12048 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12049 Register ShiftReg = 12050 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12051 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12052 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12053 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12054 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12055 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12056 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12057 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12058 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12059 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12060 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12061 Register Ptr1Reg; 12062 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12063 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12064 // thisMBB: 12065 // ... 12066 // fallthrough --> loopMBB 12067 BB->addSuccessor(loop1MBB); 12068 12069 // The 4-byte load must be aligned, while a char or short may be 12070 // anywhere in the word. Hence all this nasty bookkeeping code. 12071 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12072 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12073 // xori shift, shift1, 24 [16] 12074 // rlwinm ptr, ptr1, 0, 0, 29 12075 // slw newval2, newval, shift 12076 // slw oldval2, oldval,shift 12077 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12078 // slw mask, mask2, shift 12079 // and newval3, newval2, mask 12080 // and oldval3, oldval2, mask 12081 // loop1MBB: 12082 // lwarx tmpDest, ptr 12083 // and tmp, tmpDest, mask 12084 // cmpw tmp, oldval3 12085 // bne- midMBB 12086 // loop2MBB: 12087 // andc tmp2, tmpDest, mask 12088 // or tmp4, tmp2, newval3 12089 // stwcx. tmp4, ptr 12090 // bne- loop1MBB 12091 // b exitBB 12092 // midMBB: 12093 // stwcx. tmpDest, ptr 12094 // exitBB: 12095 // srw dest, tmpDest, shift 12096 if (ptrA != ZeroReg) { 12097 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12098 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12099 .addReg(ptrA) 12100 .addReg(ptrB); 12101 } else { 12102 Ptr1Reg = ptrB; 12103 } 12104 12105 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12106 // mode. 12107 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12108 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12109 .addImm(3) 12110 .addImm(27) 12111 .addImm(is8bit ? 28 : 27); 12112 if (!isLittleEndian) 12113 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12114 .addReg(Shift1Reg) 12115 .addImm(is8bit ? 24 : 16); 12116 if (is64bit) 12117 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12118 .addReg(Ptr1Reg) 12119 .addImm(0) 12120 .addImm(61); 12121 else 12122 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12123 .addReg(Ptr1Reg) 12124 .addImm(0) 12125 .addImm(0) 12126 .addImm(29); 12127 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12128 .addReg(newval) 12129 .addReg(ShiftReg); 12130 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12131 .addReg(oldval) 12132 .addReg(ShiftReg); 12133 if (is8bit) 12134 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12135 else { 12136 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12137 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12138 .addReg(Mask3Reg) 12139 .addImm(65535); 12140 } 12141 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12142 .addReg(Mask2Reg) 12143 .addReg(ShiftReg); 12144 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12145 .addReg(NewVal2Reg) 12146 .addReg(MaskReg); 12147 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12148 .addReg(OldVal2Reg) 12149 .addReg(MaskReg); 12150 12151 BB = loop1MBB; 12152 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12153 .addReg(ZeroReg) 12154 .addReg(PtrReg); 12155 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12156 .addReg(TmpDestReg) 12157 .addReg(MaskReg); 12158 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12159 .addReg(TmpReg) 12160 .addReg(OldVal3Reg); 12161 BuildMI(BB, dl, TII->get(PPC::BCC)) 12162 .addImm(PPC::PRED_NE) 12163 .addReg(PPC::CR0) 12164 .addMBB(midMBB); 12165 BB->addSuccessor(loop2MBB); 12166 BB->addSuccessor(midMBB); 12167 12168 BB = loop2MBB; 12169 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12170 .addReg(TmpDestReg) 12171 .addReg(MaskReg); 12172 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12173 .addReg(Tmp2Reg) 12174 .addReg(NewVal3Reg); 12175 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12176 .addReg(Tmp4Reg) 12177 .addReg(ZeroReg) 12178 .addReg(PtrReg); 12179 BuildMI(BB, dl, TII->get(PPC::BCC)) 12180 .addImm(PPC::PRED_NE) 12181 .addReg(PPC::CR0) 12182 .addMBB(loop1MBB); 12183 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12184 BB->addSuccessor(loop1MBB); 12185 BB->addSuccessor(exitMBB); 12186 12187 BB = midMBB; 12188 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12189 .addReg(TmpDestReg) 12190 .addReg(ZeroReg) 12191 .addReg(PtrReg); 12192 BB->addSuccessor(exitMBB); 12193 12194 // exitMBB: 12195 // ... 12196 BB = exitMBB; 12197 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12198 .addReg(TmpReg) 12199 .addReg(ShiftReg); 12200 } else if (MI.getOpcode() == PPC::FADDrtz) { 12201 // This pseudo performs an FADD with rounding mode temporarily forced 12202 // to round-to-zero. We emit this via custom inserter since the FPSCR 12203 // is not modeled at the SelectionDAG level. 12204 Register Dest = MI.getOperand(0).getReg(); 12205 Register Src1 = MI.getOperand(1).getReg(); 12206 Register Src2 = MI.getOperand(2).getReg(); 12207 DebugLoc dl = MI.getDebugLoc(); 12208 12209 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12210 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12211 12212 // Save FPSCR value. 12213 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12214 12215 // Set rounding mode to round-to-zero. 12216 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12217 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12218 12219 // Perform addition. 12220 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12221 12222 // Restore FPSCR value. 12223 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12224 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12225 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12226 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12227 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12228 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12229 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12230 ? PPC::ANDI8_rec 12231 : PPC::ANDI_rec; 12232 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12233 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12234 12235 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12236 Register Dest = RegInfo.createVirtualRegister( 12237 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12238 12239 DebugLoc Dl = MI.getDebugLoc(); 12240 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12241 .addReg(MI.getOperand(1).getReg()) 12242 .addImm(1); 12243 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12244 MI.getOperand(0).getReg()) 12245 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12246 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12247 DebugLoc Dl = MI.getDebugLoc(); 12248 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12249 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12250 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12251 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12252 MI.getOperand(0).getReg()) 12253 .addReg(CRReg); 12254 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12255 DebugLoc Dl = MI.getDebugLoc(); 12256 unsigned Imm = MI.getOperand(1).getImm(); 12257 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12258 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12259 MI.getOperand(0).getReg()) 12260 .addReg(PPC::CR0EQ); 12261 } else if (MI.getOpcode() == PPC::SETRNDi) { 12262 DebugLoc dl = MI.getDebugLoc(); 12263 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12264 12265 // Save FPSCR value. 12266 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12267 12268 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12269 // the following settings: 12270 // 00 Round to nearest 12271 // 01 Round to 0 12272 // 10 Round to +inf 12273 // 11 Round to -inf 12274 12275 // When the operand is immediate, using the two least significant bits of 12276 // the immediate to set the bits 62:63 of FPSCR. 12277 unsigned Mode = MI.getOperand(1).getImm(); 12278 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12279 .addImm(31); 12280 12281 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12282 .addImm(30); 12283 } else if (MI.getOpcode() == PPC::SETRND) { 12284 DebugLoc dl = MI.getDebugLoc(); 12285 12286 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12287 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12288 // If the target doesn't have DirectMove, we should use stack to do the 12289 // conversion, because the target doesn't have the instructions like mtvsrd 12290 // or mfvsrd to do this conversion directly. 12291 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12292 if (Subtarget.hasDirectMove()) { 12293 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12294 .addReg(SrcReg); 12295 } else { 12296 // Use stack to do the register copy. 12297 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12298 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12299 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12300 if (RC == &PPC::F8RCRegClass) { 12301 // Copy register from F8RCRegClass to G8RCRegclass. 12302 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12303 "Unsupported RegClass."); 12304 12305 StoreOp = PPC::STFD; 12306 LoadOp = PPC::LD; 12307 } else { 12308 // Copy register from G8RCRegClass to F8RCRegclass. 12309 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12310 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12311 "Unsupported RegClass."); 12312 } 12313 12314 MachineFrameInfo &MFI = F->getFrameInfo(); 12315 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12316 12317 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12318 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12319 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12320 MFI.getObjectAlign(FrameIdx)); 12321 12322 // Store the SrcReg into the stack. 12323 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12324 .addReg(SrcReg) 12325 .addImm(0) 12326 .addFrameIndex(FrameIdx) 12327 .addMemOperand(MMOStore); 12328 12329 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12330 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12331 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12332 MFI.getObjectAlign(FrameIdx)); 12333 12334 // Load from the stack where SrcReg is stored, and save to DestReg, 12335 // so we have done the RegClass conversion from RegClass::SrcReg to 12336 // RegClass::DestReg. 12337 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12338 .addImm(0) 12339 .addFrameIndex(FrameIdx) 12340 .addMemOperand(MMOLoad); 12341 } 12342 }; 12343 12344 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12345 12346 // Save FPSCR value. 12347 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12348 12349 // When the operand is gprc register, use two least significant bits of the 12350 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12351 // 12352 // copy OldFPSCRTmpReg, OldFPSCRReg 12353 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12354 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12355 // copy NewFPSCRReg, NewFPSCRTmpReg 12356 // mtfsf 255, NewFPSCRReg 12357 MachineOperand SrcOp = MI.getOperand(1); 12358 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12359 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12360 12361 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12362 12363 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12364 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12365 12366 // The first operand of INSERT_SUBREG should be a register which has 12367 // subregisters, we only care about its RegClass, so we should use an 12368 // IMPLICIT_DEF register. 12369 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12370 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12371 .addReg(ImDefReg) 12372 .add(SrcOp) 12373 .addImm(1); 12374 12375 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12376 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12377 .addReg(OldFPSCRTmpReg) 12378 .addReg(ExtSrcReg) 12379 .addImm(0) 12380 .addImm(62); 12381 12382 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12383 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12384 12385 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12386 // bits of FPSCR. 12387 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12388 .addImm(255) 12389 .addReg(NewFPSCRReg) 12390 .addImm(0) 12391 .addImm(0); 12392 } else { 12393 llvm_unreachable("Unexpected instr type to insert"); 12394 } 12395 12396 MI.eraseFromParent(); // The pseudo instruction is gone now. 12397 return BB; 12398 } 12399 12400 //===----------------------------------------------------------------------===// 12401 // Target Optimization Hooks 12402 //===----------------------------------------------------------------------===// 12403 12404 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12405 // For the estimates, convergence is quadratic, so we essentially double the 12406 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12407 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12408 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12409 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12410 if (VT.getScalarType() == MVT::f64) 12411 RefinementSteps++; 12412 return RefinementSteps; 12413 } 12414 12415 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12416 int Enabled, int &RefinementSteps, 12417 bool &UseOneConstNR, 12418 bool Reciprocal) const { 12419 EVT VT = Operand.getValueType(); 12420 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12421 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12422 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12423 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12424 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12425 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12426 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12427 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12428 12429 // The Newton-Raphson computation with a single constant does not provide 12430 // enough accuracy on some CPUs. 12431 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12432 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12433 } 12434 return SDValue(); 12435 } 12436 12437 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12438 int Enabled, 12439 int &RefinementSteps) const { 12440 EVT VT = Operand.getValueType(); 12441 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12442 (VT == MVT::f64 && Subtarget.hasFRE()) || 12443 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12444 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12445 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12446 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12447 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12448 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12449 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12450 } 12451 return SDValue(); 12452 } 12453 12454 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12455 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12456 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12457 // enabled for division), this functionality is redundant with the default 12458 // combiner logic (once the division -> reciprocal/multiply transformation 12459 // has taken place). As a result, this matters more for older cores than for 12460 // newer ones. 12461 12462 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12463 // reciprocal if there are two or more FDIVs (for embedded cores with only 12464 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12465 switch (Subtarget.getCPUDirective()) { 12466 default: 12467 return 3; 12468 case PPC::DIR_440: 12469 case PPC::DIR_A2: 12470 case PPC::DIR_E500: 12471 case PPC::DIR_E500mc: 12472 case PPC::DIR_E5500: 12473 return 2; 12474 } 12475 } 12476 12477 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12478 // collapsed, and so we need to look through chains of them. 12479 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12480 int64_t& Offset, SelectionDAG &DAG) { 12481 if (DAG.isBaseWithConstantOffset(Loc)) { 12482 Base = Loc.getOperand(0); 12483 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12484 12485 // The base might itself be a base plus an offset, and if so, accumulate 12486 // that as well. 12487 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12488 } 12489 } 12490 12491 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12492 unsigned Bytes, int Dist, 12493 SelectionDAG &DAG) { 12494 if (VT.getSizeInBits() / 8 != Bytes) 12495 return false; 12496 12497 SDValue BaseLoc = Base->getBasePtr(); 12498 if (Loc.getOpcode() == ISD::FrameIndex) { 12499 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12500 return false; 12501 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12502 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12503 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12504 int FS = MFI.getObjectSize(FI); 12505 int BFS = MFI.getObjectSize(BFI); 12506 if (FS != BFS || FS != (int)Bytes) return false; 12507 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12508 } 12509 12510 SDValue Base1 = Loc, Base2 = BaseLoc; 12511 int64_t Offset1 = 0, Offset2 = 0; 12512 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12513 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12514 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12515 return true; 12516 12517 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12518 const GlobalValue *GV1 = nullptr; 12519 const GlobalValue *GV2 = nullptr; 12520 Offset1 = 0; 12521 Offset2 = 0; 12522 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12523 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12524 if (isGA1 && isGA2 && GV1 == GV2) 12525 return Offset1 == (Offset2 + Dist*Bytes); 12526 return false; 12527 } 12528 12529 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12530 // not enforce equality of the chain operands. 12531 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12532 unsigned Bytes, int Dist, 12533 SelectionDAG &DAG) { 12534 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12535 EVT VT = LS->getMemoryVT(); 12536 SDValue Loc = LS->getBasePtr(); 12537 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12538 } 12539 12540 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12541 EVT VT; 12542 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12543 default: return false; 12544 case Intrinsic::ppc_qpx_qvlfd: 12545 case Intrinsic::ppc_qpx_qvlfda: 12546 VT = MVT::v4f64; 12547 break; 12548 case Intrinsic::ppc_qpx_qvlfs: 12549 case Intrinsic::ppc_qpx_qvlfsa: 12550 VT = MVT::v4f32; 12551 break; 12552 case Intrinsic::ppc_qpx_qvlfcd: 12553 case Intrinsic::ppc_qpx_qvlfcda: 12554 VT = MVT::v2f64; 12555 break; 12556 case Intrinsic::ppc_qpx_qvlfcs: 12557 case Intrinsic::ppc_qpx_qvlfcsa: 12558 VT = MVT::v2f32; 12559 break; 12560 case Intrinsic::ppc_qpx_qvlfiwa: 12561 case Intrinsic::ppc_qpx_qvlfiwz: 12562 case Intrinsic::ppc_altivec_lvx: 12563 case Intrinsic::ppc_altivec_lvxl: 12564 case Intrinsic::ppc_vsx_lxvw4x: 12565 case Intrinsic::ppc_vsx_lxvw4x_be: 12566 VT = MVT::v4i32; 12567 break; 12568 case Intrinsic::ppc_vsx_lxvd2x: 12569 case Intrinsic::ppc_vsx_lxvd2x_be: 12570 VT = MVT::v2f64; 12571 break; 12572 case Intrinsic::ppc_altivec_lvebx: 12573 VT = MVT::i8; 12574 break; 12575 case Intrinsic::ppc_altivec_lvehx: 12576 VT = MVT::i16; 12577 break; 12578 case Intrinsic::ppc_altivec_lvewx: 12579 VT = MVT::i32; 12580 break; 12581 } 12582 12583 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12584 } 12585 12586 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12587 EVT VT; 12588 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12589 default: return false; 12590 case Intrinsic::ppc_qpx_qvstfd: 12591 case Intrinsic::ppc_qpx_qvstfda: 12592 VT = MVT::v4f64; 12593 break; 12594 case Intrinsic::ppc_qpx_qvstfs: 12595 case Intrinsic::ppc_qpx_qvstfsa: 12596 VT = MVT::v4f32; 12597 break; 12598 case Intrinsic::ppc_qpx_qvstfcd: 12599 case Intrinsic::ppc_qpx_qvstfcda: 12600 VT = MVT::v2f64; 12601 break; 12602 case Intrinsic::ppc_qpx_qvstfcs: 12603 case Intrinsic::ppc_qpx_qvstfcsa: 12604 VT = MVT::v2f32; 12605 break; 12606 case Intrinsic::ppc_qpx_qvstfiw: 12607 case Intrinsic::ppc_qpx_qvstfiwa: 12608 case Intrinsic::ppc_altivec_stvx: 12609 case Intrinsic::ppc_altivec_stvxl: 12610 case Intrinsic::ppc_vsx_stxvw4x: 12611 VT = MVT::v4i32; 12612 break; 12613 case Intrinsic::ppc_vsx_stxvd2x: 12614 VT = MVT::v2f64; 12615 break; 12616 case Intrinsic::ppc_vsx_stxvw4x_be: 12617 VT = MVT::v4i32; 12618 break; 12619 case Intrinsic::ppc_vsx_stxvd2x_be: 12620 VT = MVT::v2f64; 12621 break; 12622 case Intrinsic::ppc_altivec_stvebx: 12623 VT = MVT::i8; 12624 break; 12625 case Intrinsic::ppc_altivec_stvehx: 12626 VT = MVT::i16; 12627 break; 12628 case Intrinsic::ppc_altivec_stvewx: 12629 VT = MVT::i32; 12630 break; 12631 } 12632 12633 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12634 } 12635 12636 return false; 12637 } 12638 12639 // Return true is there is a nearyby consecutive load to the one provided 12640 // (regardless of alignment). We search up and down the chain, looking though 12641 // token factors and other loads (but nothing else). As a result, a true result 12642 // indicates that it is safe to create a new consecutive load adjacent to the 12643 // load provided. 12644 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12645 SDValue Chain = LD->getChain(); 12646 EVT VT = LD->getMemoryVT(); 12647 12648 SmallSet<SDNode *, 16> LoadRoots; 12649 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12650 SmallSet<SDNode *, 16> Visited; 12651 12652 // First, search up the chain, branching to follow all token-factor operands. 12653 // If we find a consecutive load, then we're done, otherwise, record all 12654 // nodes just above the top-level loads and token factors. 12655 while (!Queue.empty()) { 12656 SDNode *ChainNext = Queue.pop_back_val(); 12657 if (!Visited.insert(ChainNext).second) 12658 continue; 12659 12660 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12661 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12662 return true; 12663 12664 if (!Visited.count(ChainLD->getChain().getNode())) 12665 Queue.push_back(ChainLD->getChain().getNode()); 12666 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12667 for (const SDUse &O : ChainNext->ops()) 12668 if (!Visited.count(O.getNode())) 12669 Queue.push_back(O.getNode()); 12670 } else 12671 LoadRoots.insert(ChainNext); 12672 } 12673 12674 // Second, search down the chain, starting from the top-level nodes recorded 12675 // in the first phase. These top-level nodes are the nodes just above all 12676 // loads and token factors. Starting with their uses, recursively look though 12677 // all loads (just the chain uses) and token factors to find a consecutive 12678 // load. 12679 Visited.clear(); 12680 Queue.clear(); 12681 12682 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12683 IE = LoadRoots.end(); I != IE; ++I) { 12684 Queue.push_back(*I); 12685 12686 while (!Queue.empty()) { 12687 SDNode *LoadRoot = Queue.pop_back_val(); 12688 if (!Visited.insert(LoadRoot).second) 12689 continue; 12690 12691 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12692 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12693 return true; 12694 12695 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12696 UE = LoadRoot->use_end(); UI != UE; ++UI) 12697 if (((isa<MemSDNode>(*UI) && 12698 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12699 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12700 Queue.push_back(*UI); 12701 } 12702 } 12703 12704 return false; 12705 } 12706 12707 /// This function is called when we have proved that a SETCC node can be replaced 12708 /// by subtraction (and other supporting instructions) so that the result of 12709 /// comparison is kept in a GPR instead of CR. This function is purely for 12710 /// codegen purposes and has some flags to guide the codegen process. 12711 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12712 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12713 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12714 12715 // Zero extend the operands to the largest legal integer. Originally, they 12716 // must be of a strictly smaller size. 12717 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12718 DAG.getConstant(Size, DL, MVT::i32)); 12719 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12720 DAG.getConstant(Size, DL, MVT::i32)); 12721 12722 // Swap if needed. Depends on the condition code. 12723 if (Swap) 12724 std::swap(Op0, Op1); 12725 12726 // Subtract extended integers. 12727 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12728 12729 // Move the sign bit to the least significant position and zero out the rest. 12730 // Now the least significant bit carries the result of original comparison. 12731 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12732 DAG.getConstant(Size - 1, DL, MVT::i32)); 12733 auto Final = Shifted; 12734 12735 // Complement the result if needed. Based on the condition code. 12736 if (Complement) 12737 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12738 DAG.getConstant(1, DL, MVT::i64)); 12739 12740 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12741 } 12742 12743 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12744 DAGCombinerInfo &DCI) const { 12745 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12746 12747 SelectionDAG &DAG = DCI.DAG; 12748 SDLoc DL(N); 12749 12750 // Size of integers being compared has a critical role in the following 12751 // analysis, so we prefer to do this when all types are legal. 12752 if (!DCI.isAfterLegalizeDAG()) 12753 return SDValue(); 12754 12755 // If all users of SETCC extend its value to a legal integer type 12756 // then we replace SETCC with a subtraction 12757 for (SDNode::use_iterator UI = N->use_begin(), 12758 UE = N->use_end(); UI != UE; ++UI) { 12759 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12760 return SDValue(); 12761 } 12762 12763 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12764 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12765 12766 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12767 12768 if (OpSize < Size) { 12769 switch (CC) { 12770 default: break; 12771 case ISD::SETULT: 12772 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12773 case ISD::SETULE: 12774 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12775 case ISD::SETUGT: 12776 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12777 case ISD::SETUGE: 12778 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12779 } 12780 } 12781 12782 return SDValue(); 12783 } 12784 12785 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12786 DAGCombinerInfo &DCI) const { 12787 SelectionDAG &DAG = DCI.DAG; 12788 SDLoc dl(N); 12789 12790 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12791 // If we're tracking CR bits, we need to be careful that we don't have: 12792 // trunc(binary-ops(zext(x), zext(y))) 12793 // or 12794 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12795 // such that we're unnecessarily moving things into GPRs when it would be 12796 // better to keep them in CR bits. 12797 12798 // Note that trunc here can be an actual i1 trunc, or can be the effective 12799 // truncation that comes from a setcc or select_cc. 12800 if (N->getOpcode() == ISD::TRUNCATE && 12801 N->getValueType(0) != MVT::i1) 12802 return SDValue(); 12803 12804 if (N->getOperand(0).getValueType() != MVT::i32 && 12805 N->getOperand(0).getValueType() != MVT::i64) 12806 return SDValue(); 12807 12808 if (N->getOpcode() == ISD::SETCC || 12809 N->getOpcode() == ISD::SELECT_CC) { 12810 // If we're looking at a comparison, then we need to make sure that the 12811 // high bits (all except for the first) don't matter the result. 12812 ISD::CondCode CC = 12813 cast<CondCodeSDNode>(N->getOperand( 12814 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12815 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12816 12817 if (ISD::isSignedIntSetCC(CC)) { 12818 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12819 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12820 return SDValue(); 12821 } else if (ISD::isUnsignedIntSetCC(CC)) { 12822 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12823 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12824 !DAG.MaskedValueIsZero(N->getOperand(1), 12825 APInt::getHighBitsSet(OpBits, OpBits-1))) 12826 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12827 : SDValue()); 12828 } else { 12829 // This is neither a signed nor an unsigned comparison, just make sure 12830 // that the high bits are equal. 12831 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12832 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12833 12834 // We don't really care about what is known about the first bit (if 12835 // anything), so clear it in all masks prior to comparing them. 12836 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12837 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12838 12839 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12840 return SDValue(); 12841 } 12842 } 12843 12844 // We now know that the higher-order bits are irrelevant, we just need to 12845 // make sure that all of the intermediate operations are bit operations, and 12846 // all inputs are extensions. 12847 if (N->getOperand(0).getOpcode() != ISD::AND && 12848 N->getOperand(0).getOpcode() != ISD::OR && 12849 N->getOperand(0).getOpcode() != ISD::XOR && 12850 N->getOperand(0).getOpcode() != ISD::SELECT && 12851 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12852 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12853 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12854 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12855 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12856 return SDValue(); 12857 12858 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12859 N->getOperand(1).getOpcode() != ISD::AND && 12860 N->getOperand(1).getOpcode() != ISD::OR && 12861 N->getOperand(1).getOpcode() != ISD::XOR && 12862 N->getOperand(1).getOpcode() != ISD::SELECT && 12863 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12864 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12865 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12866 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12867 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12868 return SDValue(); 12869 12870 SmallVector<SDValue, 4> Inputs; 12871 SmallVector<SDValue, 8> BinOps, PromOps; 12872 SmallPtrSet<SDNode *, 16> Visited; 12873 12874 for (unsigned i = 0; i < 2; ++i) { 12875 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12876 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12877 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12878 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12879 isa<ConstantSDNode>(N->getOperand(i))) 12880 Inputs.push_back(N->getOperand(i)); 12881 else 12882 BinOps.push_back(N->getOperand(i)); 12883 12884 if (N->getOpcode() == ISD::TRUNCATE) 12885 break; 12886 } 12887 12888 // Visit all inputs, collect all binary operations (and, or, xor and 12889 // select) that are all fed by extensions. 12890 while (!BinOps.empty()) { 12891 SDValue BinOp = BinOps.back(); 12892 BinOps.pop_back(); 12893 12894 if (!Visited.insert(BinOp.getNode()).second) 12895 continue; 12896 12897 PromOps.push_back(BinOp); 12898 12899 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12900 // The condition of the select is not promoted. 12901 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12902 continue; 12903 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12904 continue; 12905 12906 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12907 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12908 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12909 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12910 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12911 Inputs.push_back(BinOp.getOperand(i)); 12912 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12913 BinOp.getOperand(i).getOpcode() == ISD::OR || 12914 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12915 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12916 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12917 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12918 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12919 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12920 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12921 BinOps.push_back(BinOp.getOperand(i)); 12922 } else { 12923 // We have an input that is not an extension or another binary 12924 // operation; we'll abort this transformation. 12925 return SDValue(); 12926 } 12927 } 12928 } 12929 12930 // Make sure that this is a self-contained cluster of operations (which 12931 // is not quite the same thing as saying that everything has only one 12932 // use). 12933 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12934 if (isa<ConstantSDNode>(Inputs[i])) 12935 continue; 12936 12937 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12938 UE = Inputs[i].getNode()->use_end(); 12939 UI != UE; ++UI) { 12940 SDNode *User = *UI; 12941 if (User != N && !Visited.count(User)) 12942 return SDValue(); 12943 12944 // Make sure that we're not going to promote the non-output-value 12945 // operand(s) or SELECT or SELECT_CC. 12946 // FIXME: Although we could sometimes handle this, and it does occur in 12947 // practice that one of the condition inputs to the select is also one of 12948 // the outputs, we currently can't deal with this. 12949 if (User->getOpcode() == ISD::SELECT) { 12950 if (User->getOperand(0) == Inputs[i]) 12951 return SDValue(); 12952 } else if (User->getOpcode() == ISD::SELECT_CC) { 12953 if (User->getOperand(0) == Inputs[i] || 12954 User->getOperand(1) == Inputs[i]) 12955 return SDValue(); 12956 } 12957 } 12958 } 12959 12960 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12961 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12962 UE = PromOps[i].getNode()->use_end(); 12963 UI != UE; ++UI) { 12964 SDNode *User = *UI; 12965 if (User != N && !Visited.count(User)) 12966 return SDValue(); 12967 12968 // Make sure that we're not going to promote the non-output-value 12969 // operand(s) or SELECT or SELECT_CC. 12970 // FIXME: Although we could sometimes handle this, and it does occur in 12971 // practice that one of the condition inputs to the select is also one of 12972 // the outputs, we currently can't deal with this. 12973 if (User->getOpcode() == ISD::SELECT) { 12974 if (User->getOperand(0) == PromOps[i]) 12975 return SDValue(); 12976 } else if (User->getOpcode() == ISD::SELECT_CC) { 12977 if (User->getOperand(0) == PromOps[i] || 12978 User->getOperand(1) == PromOps[i]) 12979 return SDValue(); 12980 } 12981 } 12982 } 12983 12984 // Replace all inputs with the extension operand. 12985 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12986 // Constants may have users outside the cluster of to-be-promoted nodes, 12987 // and so we need to replace those as we do the promotions. 12988 if (isa<ConstantSDNode>(Inputs[i])) 12989 continue; 12990 else 12991 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12992 } 12993 12994 std::list<HandleSDNode> PromOpHandles; 12995 for (auto &PromOp : PromOps) 12996 PromOpHandles.emplace_back(PromOp); 12997 12998 // Replace all operations (these are all the same, but have a different 12999 // (i1) return type). DAG.getNode will validate that the types of 13000 // a binary operator match, so go through the list in reverse so that 13001 // we've likely promoted both operands first. Any intermediate truncations or 13002 // extensions disappear. 13003 while (!PromOpHandles.empty()) { 13004 SDValue PromOp = PromOpHandles.back().getValue(); 13005 PromOpHandles.pop_back(); 13006 13007 if (PromOp.getOpcode() == ISD::TRUNCATE || 13008 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13009 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13010 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13011 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13012 PromOp.getOperand(0).getValueType() != MVT::i1) { 13013 // The operand is not yet ready (see comment below). 13014 PromOpHandles.emplace_front(PromOp); 13015 continue; 13016 } 13017 13018 SDValue RepValue = PromOp.getOperand(0); 13019 if (isa<ConstantSDNode>(RepValue)) 13020 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13021 13022 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13023 continue; 13024 } 13025 13026 unsigned C; 13027 switch (PromOp.getOpcode()) { 13028 default: C = 0; break; 13029 case ISD::SELECT: C = 1; break; 13030 case ISD::SELECT_CC: C = 2; break; 13031 } 13032 13033 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13034 PromOp.getOperand(C).getValueType() != MVT::i1) || 13035 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13036 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13037 // The to-be-promoted operands of this node have not yet been 13038 // promoted (this should be rare because we're going through the 13039 // list backward, but if one of the operands has several users in 13040 // this cluster of to-be-promoted nodes, it is possible). 13041 PromOpHandles.emplace_front(PromOp); 13042 continue; 13043 } 13044 13045 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13046 PromOp.getNode()->op_end()); 13047 13048 // If there are any constant inputs, make sure they're replaced now. 13049 for (unsigned i = 0; i < 2; ++i) 13050 if (isa<ConstantSDNode>(Ops[C+i])) 13051 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13052 13053 DAG.ReplaceAllUsesOfValueWith(PromOp, 13054 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13055 } 13056 13057 // Now we're left with the initial truncation itself. 13058 if (N->getOpcode() == ISD::TRUNCATE) 13059 return N->getOperand(0); 13060 13061 // Otherwise, this is a comparison. The operands to be compared have just 13062 // changed type (to i1), but everything else is the same. 13063 return SDValue(N, 0); 13064 } 13065 13066 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13067 DAGCombinerInfo &DCI) const { 13068 SelectionDAG &DAG = DCI.DAG; 13069 SDLoc dl(N); 13070 13071 // If we're tracking CR bits, we need to be careful that we don't have: 13072 // zext(binary-ops(trunc(x), trunc(y))) 13073 // or 13074 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13075 // such that we're unnecessarily moving things into CR bits that can more 13076 // efficiently stay in GPRs. Note that if we're not certain that the high 13077 // bits are set as required by the final extension, we still may need to do 13078 // some masking to get the proper behavior. 13079 13080 // This same functionality is important on PPC64 when dealing with 13081 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13082 // the return values of functions. Because it is so similar, it is handled 13083 // here as well. 13084 13085 if (N->getValueType(0) != MVT::i32 && 13086 N->getValueType(0) != MVT::i64) 13087 return SDValue(); 13088 13089 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13090 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13091 return SDValue(); 13092 13093 if (N->getOperand(0).getOpcode() != ISD::AND && 13094 N->getOperand(0).getOpcode() != ISD::OR && 13095 N->getOperand(0).getOpcode() != ISD::XOR && 13096 N->getOperand(0).getOpcode() != ISD::SELECT && 13097 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13098 return SDValue(); 13099 13100 SmallVector<SDValue, 4> Inputs; 13101 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13102 SmallPtrSet<SDNode *, 16> Visited; 13103 13104 // Visit all inputs, collect all binary operations (and, or, xor and 13105 // select) that are all fed by truncations. 13106 while (!BinOps.empty()) { 13107 SDValue BinOp = BinOps.back(); 13108 BinOps.pop_back(); 13109 13110 if (!Visited.insert(BinOp.getNode()).second) 13111 continue; 13112 13113 PromOps.push_back(BinOp); 13114 13115 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13116 // The condition of the select is not promoted. 13117 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13118 continue; 13119 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13120 continue; 13121 13122 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13123 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13124 Inputs.push_back(BinOp.getOperand(i)); 13125 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13126 BinOp.getOperand(i).getOpcode() == ISD::OR || 13127 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13128 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13129 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13130 BinOps.push_back(BinOp.getOperand(i)); 13131 } else { 13132 // We have an input that is not a truncation or another binary 13133 // operation; we'll abort this transformation. 13134 return SDValue(); 13135 } 13136 } 13137 } 13138 13139 // The operands of a select that must be truncated when the select is 13140 // promoted because the operand is actually part of the to-be-promoted set. 13141 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13142 13143 // Make sure that this is a self-contained cluster of operations (which 13144 // is not quite the same thing as saying that everything has only one 13145 // use). 13146 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13147 if (isa<ConstantSDNode>(Inputs[i])) 13148 continue; 13149 13150 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13151 UE = Inputs[i].getNode()->use_end(); 13152 UI != UE; ++UI) { 13153 SDNode *User = *UI; 13154 if (User != N && !Visited.count(User)) 13155 return SDValue(); 13156 13157 // If we're going to promote the non-output-value operand(s) or SELECT or 13158 // SELECT_CC, record them for truncation. 13159 if (User->getOpcode() == ISD::SELECT) { 13160 if (User->getOperand(0) == Inputs[i]) 13161 SelectTruncOp[0].insert(std::make_pair(User, 13162 User->getOperand(0).getValueType())); 13163 } else if (User->getOpcode() == ISD::SELECT_CC) { 13164 if (User->getOperand(0) == Inputs[i]) 13165 SelectTruncOp[0].insert(std::make_pair(User, 13166 User->getOperand(0).getValueType())); 13167 if (User->getOperand(1) == Inputs[i]) 13168 SelectTruncOp[1].insert(std::make_pair(User, 13169 User->getOperand(1).getValueType())); 13170 } 13171 } 13172 } 13173 13174 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13175 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13176 UE = PromOps[i].getNode()->use_end(); 13177 UI != UE; ++UI) { 13178 SDNode *User = *UI; 13179 if (User != N && !Visited.count(User)) 13180 return SDValue(); 13181 13182 // If we're going to promote the non-output-value operand(s) or SELECT or 13183 // SELECT_CC, record them for truncation. 13184 if (User->getOpcode() == ISD::SELECT) { 13185 if (User->getOperand(0) == PromOps[i]) 13186 SelectTruncOp[0].insert(std::make_pair(User, 13187 User->getOperand(0).getValueType())); 13188 } else if (User->getOpcode() == ISD::SELECT_CC) { 13189 if (User->getOperand(0) == PromOps[i]) 13190 SelectTruncOp[0].insert(std::make_pair(User, 13191 User->getOperand(0).getValueType())); 13192 if (User->getOperand(1) == PromOps[i]) 13193 SelectTruncOp[1].insert(std::make_pair(User, 13194 User->getOperand(1).getValueType())); 13195 } 13196 } 13197 } 13198 13199 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13200 bool ReallyNeedsExt = false; 13201 if (N->getOpcode() != ISD::ANY_EXTEND) { 13202 // If all of the inputs are not already sign/zero extended, then 13203 // we'll still need to do that at the end. 13204 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13205 if (isa<ConstantSDNode>(Inputs[i])) 13206 continue; 13207 13208 unsigned OpBits = 13209 Inputs[i].getOperand(0).getValueSizeInBits(); 13210 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13211 13212 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13213 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13214 APInt::getHighBitsSet(OpBits, 13215 OpBits-PromBits))) || 13216 (N->getOpcode() == ISD::SIGN_EXTEND && 13217 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13218 (OpBits-(PromBits-1)))) { 13219 ReallyNeedsExt = true; 13220 break; 13221 } 13222 } 13223 } 13224 13225 // Replace all inputs, either with the truncation operand, or a 13226 // truncation or extension to the final output type. 13227 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13228 // Constant inputs need to be replaced with the to-be-promoted nodes that 13229 // use them because they might have users outside of the cluster of 13230 // promoted nodes. 13231 if (isa<ConstantSDNode>(Inputs[i])) 13232 continue; 13233 13234 SDValue InSrc = Inputs[i].getOperand(0); 13235 if (Inputs[i].getValueType() == N->getValueType(0)) 13236 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13237 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13238 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13239 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13240 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13241 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13242 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13243 else 13244 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13245 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13246 } 13247 13248 std::list<HandleSDNode> PromOpHandles; 13249 for (auto &PromOp : PromOps) 13250 PromOpHandles.emplace_back(PromOp); 13251 13252 // Replace all operations (these are all the same, but have a different 13253 // (promoted) return type). DAG.getNode will validate that the types of 13254 // a binary operator match, so go through the list in reverse so that 13255 // we've likely promoted both operands first. 13256 while (!PromOpHandles.empty()) { 13257 SDValue PromOp = PromOpHandles.back().getValue(); 13258 PromOpHandles.pop_back(); 13259 13260 unsigned C; 13261 switch (PromOp.getOpcode()) { 13262 default: C = 0; break; 13263 case ISD::SELECT: C = 1; break; 13264 case ISD::SELECT_CC: C = 2; break; 13265 } 13266 13267 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13268 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13269 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13270 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13271 // The to-be-promoted operands of this node have not yet been 13272 // promoted (this should be rare because we're going through the 13273 // list backward, but if one of the operands has several users in 13274 // this cluster of to-be-promoted nodes, it is possible). 13275 PromOpHandles.emplace_front(PromOp); 13276 continue; 13277 } 13278 13279 // For SELECT and SELECT_CC nodes, we do a similar check for any 13280 // to-be-promoted comparison inputs. 13281 if (PromOp.getOpcode() == ISD::SELECT || 13282 PromOp.getOpcode() == ISD::SELECT_CC) { 13283 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13284 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13285 (SelectTruncOp[1].count(PromOp.getNode()) && 13286 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13287 PromOpHandles.emplace_front(PromOp); 13288 continue; 13289 } 13290 } 13291 13292 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13293 PromOp.getNode()->op_end()); 13294 13295 // If this node has constant inputs, then they'll need to be promoted here. 13296 for (unsigned i = 0; i < 2; ++i) { 13297 if (!isa<ConstantSDNode>(Ops[C+i])) 13298 continue; 13299 if (Ops[C+i].getValueType() == N->getValueType(0)) 13300 continue; 13301 13302 if (N->getOpcode() == ISD::SIGN_EXTEND) 13303 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13304 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13305 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13306 else 13307 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13308 } 13309 13310 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13311 // truncate them again to the original value type. 13312 if (PromOp.getOpcode() == ISD::SELECT || 13313 PromOp.getOpcode() == ISD::SELECT_CC) { 13314 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13315 if (SI0 != SelectTruncOp[0].end()) 13316 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13317 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13318 if (SI1 != SelectTruncOp[1].end()) 13319 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13320 } 13321 13322 DAG.ReplaceAllUsesOfValueWith(PromOp, 13323 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13324 } 13325 13326 // Now we're left with the initial extension itself. 13327 if (!ReallyNeedsExt) 13328 return N->getOperand(0); 13329 13330 // To zero extend, just mask off everything except for the first bit (in the 13331 // i1 case). 13332 if (N->getOpcode() == ISD::ZERO_EXTEND) 13333 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13334 DAG.getConstant(APInt::getLowBitsSet( 13335 N->getValueSizeInBits(0), PromBits), 13336 dl, N->getValueType(0))); 13337 13338 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13339 "Invalid extension type"); 13340 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13341 SDValue ShiftCst = 13342 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13343 return DAG.getNode( 13344 ISD::SRA, dl, N->getValueType(0), 13345 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13346 ShiftCst); 13347 } 13348 13349 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13350 DAGCombinerInfo &DCI) const { 13351 assert(N->getOpcode() == ISD::SETCC && 13352 "Should be called with a SETCC node"); 13353 13354 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13355 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13356 SDValue LHS = N->getOperand(0); 13357 SDValue RHS = N->getOperand(1); 13358 13359 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13360 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13361 LHS.hasOneUse()) 13362 std::swap(LHS, RHS); 13363 13364 // x == 0-y --> x+y == 0 13365 // x != 0-y --> x+y != 0 13366 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13367 RHS.hasOneUse()) { 13368 SDLoc DL(N); 13369 SelectionDAG &DAG = DCI.DAG; 13370 EVT VT = N->getValueType(0); 13371 EVT OpVT = LHS.getValueType(); 13372 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13373 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13374 } 13375 } 13376 13377 return DAGCombineTruncBoolExt(N, DCI); 13378 } 13379 13380 // Is this an extending load from an f32 to an f64? 13381 static bool isFPExtLoad(SDValue Op) { 13382 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13383 return LD->getExtensionType() == ISD::EXTLOAD && 13384 Op.getValueType() == MVT::f64; 13385 return false; 13386 } 13387 13388 /// Reduces the number of fp-to-int conversion when building a vector. 13389 /// 13390 /// If this vector is built out of floating to integer conversions, 13391 /// transform it to a vector built out of floating point values followed by a 13392 /// single floating to integer conversion of the vector. 13393 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13394 /// becomes (fptosi (build_vector ($A, $B, ...))) 13395 SDValue PPCTargetLowering:: 13396 combineElementTruncationToVectorTruncation(SDNode *N, 13397 DAGCombinerInfo &DCI) const { 13398 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13399 "Should be called with a BUILD_VECTOR node"); 13400 13401 SelectionDAG &DAG = DCI.DAG; 13402 SDLoc dl(N); 13403 13404 SDValue FirstInput = N->getOperand(0); 13405 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13406 "The input operand must be an fp-to-int conversion."); 13407 13408 // This combine happens after legalization so the fp_to_[su]i nodes are 13409 // already converted to PPCSISD nodes. 13410 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13411 if (FirstConversion == PPCISD::FCTIDZ || 13412 FirstConversion == PPCISD::FCTIDUZ || 13413 FirstConversion == PPCISD::FCTIWZ || 13414 FirstConversion == PPCISD::FCTIWUZ) { 13415 bool IsSplat = true; 13416 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13417 FirstConversion == PPCISD::FCTIWUZ; 13418 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13419 SmallVector<SDValue, 4> Ops; 13420 EVT TargetVT = N->getValueType(0); 13421 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13422 SDValue NextOp = N->getOperand(i); 13423 if (NextOp.getOpcode() != PPCISD::MFVSR) 13424 return SDValue(); 13425 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13426 if (NextConversion != FirstConversion) 13427 return SDValue(); 13428 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13429 // This is not valid if the input was originally double precision. It is 13430 // also not profitable to do unless this is an extending load in which 13431 // case doing this combine will allow us to combine consecutive loads. 13432 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13433 return SDValue(); 13434 if (N->getOperand(i) != FirstInput) 13435 IsSplat = false; 13436 } 13437 13438 // If this is a splat, we leave it as-is since there will be only a single 13439 // fp-to-int conversion followed by a splat of the integer. This is better 13440 // for 32-bit and smaller ints and neutral for 64-bit ints. 13441 if (IsSplat) 13442 return SDValue(); 13443 13444 // Now that we know we have the right type of node, get its operands 13445 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13446 SDValue In = N->getOperand(i).getOperand(0); 13447 if (Is32Bit) { 13448 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13449 // here, we know that all inputs are extending loads so this is safe). 13450 if (In.isUndef()) 13451 Ops.push_back(DAG.getUNDEF(SrcVT)); 13452 else { 13453 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13454 MVT::f32, In.getOperand(0), 13455 DAG.getIntPtrConstant(1, dl)); 13456 Ops.push_back(Trunc); 13457 } 13458 } else 13459 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13460 } 13461 13462 unsigned Opcode; 13463 if (FirstConversion == PPCISD::FCTIDZ || 13464 FirstConversion == PPCISD::FCTIWZ) 13465 Opcode = ISD::FP_TO_SINT; 13466 else 13467 Opcode = ISD::FP_TO_UINT; 13468 13469 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13470 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13471 return DAG.getNode(Opcode, dl, TargetVT, BV); 13472 } 13473 return SDValue(); 13474 } 13475 13476 /// Reduce the number of loads when building a vector. 13477 /// 13478 /// Building a vector out of multiple loads can be converted to a load 13479 /// of the vector type if the loads are consecutive. If the loads are 13480 /// consecutive but in descending order, a shuffle is added at the end 13481 /// to reorder the vector. 13482 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13483 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13484 "Should be called with a BUILD_VECTOR node"); 13485 13486 SDLoc dl(N); 13487 13488 // Return early for non byte-sized type, as they can't be consecutive. 13489 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13490 return SDValue(); 13491 13492 bool InputsAreConsecutiveLoads = true; 13493 bool InputsAreReverseConsecutive = true; 13494 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13495 SDValue FirstInput = N->getOperand(0); 13496 bool IsRoundOfExtLoad = false; 13497 13498 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13499 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13500 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13501 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13502 } 13503 // Not a build vector of (possibly fp_rounded) loads. 13504 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13505 N->getNumOperands() == 1) 13506 return SDValue(); 13507 13508 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13509 // If any inputs are fp_round(extload), they all must be. 13510 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13511 return SDValue(); 13512 13513 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13514 N->getOperand(i); 13515 if (NextInput.getOpcode() != ISD::LOAD) 13516 return SDValue(); 13517 13518 SDValue PreviousInput = 13519 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13520 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13521 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13522 13523 // If any inputs are fp_round(extload), they all must be. 13524 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13525 return SDValue(); 13526 13527 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13528 InputsAreConsecutiveLoads = false; 13529 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13530 InputsAreReverseConsecutive = false; 13531 13532 // Exit early if the loads are neither consecutive nor reverse consecutive. 13533 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13534 return SDValue(); 13535 } 13536 13537 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13538 "The loads cannot be both consecutive and reverse consecutive."); 13539 13540 SDValue FirstLoadOp = 13541 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13542 SDValue LastLoadOp = 13543 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13544 N->getOperand(N->getNumOperands()-1); 13545 13546 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13547 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13548 if (InputsAreConsecutiveLoads) { 13549 assert(LD1 && "Input needs to be a LoadSDNode."); 13550 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13551 LD1->getBasePtr(), LD1->getPointerInfo(), 13552 LD1->getAlignment()); 13553 } 13554 if (InputsAreReverseConsecutive) { 13555 assert(LDL && "Input needs to be a LoadSDNode."); 13556 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13557 LDL->getBasePtr(), LDL->getPointerInfo(), 13558 LDL->getAlignment()); 13559 SmallVector<int, 16> Ops; 13560 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13561 Ops.push_back(i); 13562 13563 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13564 DAG.getUNDEF(N->getValueType(0)), Ops); 13565 } 13566 return SDValue(); 13567 } 13568 13569 // This function adds the required vector_shuffle needed to get 13570 // the elements of the vector extract in the correct position 13571 // as specified by the CorrectElems encoding. 13572 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13573 SDValue Input, uint64_t Elems, 13574 uint64_t CorrectElems) { 13575 SDLoc dl(N); 13576 13577 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13578 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13579 13580 // Knowing the element indices being extracted from the original 13581 // vector and the order in which they're being inserted, just put 13582 // them at element indices required for the instruction. 13583 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13584 if (DAG.getDataLayout().isLittleEndian()) 13585 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13586 else 13587 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13588 CorrectElems = CorrectElems >> 8; 13589 Elems = Elems >> 8; 13590 } 13591 13592 SDValue Shuffle = 13593 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13594 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13595 13596 EVT VT = N->getValueType(0); 13597 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13598 13599 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13600 Input.getValueType().getVectorElementType(), 13601 VT.getVectorNumElements()); 13602 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13603 DAG.getValueType(ExtVT)); 13604 } 13605 13606 // Look for build vector patterns where input operands come from sign 13607 // extended vector_extract elements of specific indices. If the correct indices 13608 // aren't used, add a vector shuffle to fix up the indices and create 13609 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13610 // during instruction selection. 13611 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13612 // This array encodes the indices that the vector sign extend instructions 13613 // extract from when extending from one type to another for both BE and LE. 13614 // The right nibble of each byte corresponds to the LE incides. 13615 // and the left nibble of each byte corresponds to the BE incides. 13616 // For example: 0x3074B8FC byte->word 13617 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13618 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13619 // For example: 0x000070F8 byte->double word 13620 // For LE: the allowed indices are: 0x0,0x8 13621 // For BE: the allowed indices are: 0x7,0xF 13622 uint64_t TargetElems[] = { 13623 0x3074B8FC, // b->w 13624 0x000070F8, // b->d 13625 0x10325476, // h->w 13626 0x00003074, // h->d 13627 0x00001032, // w->d 13628 }; 13629 13630 uint64_t Elems = 0; 13631 int Index; 13632 SDValue Input; 13633 13634 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13635 if (!Op) 13636 return false; 13637 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13638 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13639 return false; 13640 13641 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13642 // of the right width. 13643 SDValue Extract = Op.getOperand(0); 13644 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13645 Extract = Extract.getOperand(0); 13646 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13647 return false; 13648 13649 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13650 if (!ExtOp) 13651 return false; 13652 13653 Index = ExtOp->getZExtValue(); 13654 if (Input && Input != Extract.getOperand(0)) 13655 return false; 13656 13657 if (!Input) 13658 Input = Extract.getOperand(0); 13659 13660 Elems = Elems << 8; 13661 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13662 Elems |= Index; 13663 13664 return true; 13665 }; 13666 13667 // If the build vector operands aren't sign extended vector extracts, 13668 // of the same input vector, then return. 13669 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13670 if (!isSExtOfVecExtract(N->getOperand(i))) { 13671 return SDValue(); 13672 } 13673 } 13674 13675 // If the vector extract indicies are not correct, add the appropriate 13676 // vector_shuffle. 13677 int TgtElemArrayIdx; 13678 int InputSize = Input.getValueType().getScalarSizeInBits(); 13679 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13680 if (InputSize + OutputSize == 40) 13681 TgtElemArrayIdx = 0; 13682 else if (InputSize + OutputSize == 72) 13683 TgtElemArrayIdx = 1; 13684 else if (InputSize + OutputSize == 48) 13685 TgtElemArrayIdx = 2; 13686 else if (InputSize + OutputSize == 80) 13687 TgtElemArrayIdx = 3; 13688 else if (InputSize + OutputSize == 96) 13689 TgtElemArrayIdx = 4; 13690 else 13691 return SDValue(); 13692 13693 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13694 CorrectElems = DAG.getDataLayout().isLittleEndian() 13695 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13696 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13697 if (Elems != CorrectElems) { 13698 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13699 } 13700 13701 // Regular lowering will catch cases where a shuffle is not needed. 13702 return SDValue(); 13703 } 13704 13705 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13706 DAGCombinerInfo &DCI) const { 13707 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13708 "Should be called with a BUILD_VECTOR node"); 13709 13710 SelectionDAG &DAG = DCI.DAG; 13711 SDLoc dl(N); 13712 13713 if (!Subtarget.hasVSX()) 13714 return SDValue(); 13715 13716 // The target independent DAG combiner will leave a build_vector of 13717 // float-to-int conversions intact. We can generate MUCH better code for 13718 // a float-to-int conversion of a vector of floats. 13719 SDValue FirstInput = N->getOperand(0); 13720 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13721 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13722 if (Reduced) 13723 return Reduced; 13724 } 13725 13726 // If we're building a vector out of consecutive loads, just load that 13727 // vector type. 13728 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13729 if (Reduced) 13730 return Reduced; 13731 13732 // If we're building a vector out of extended elements from another vector 13733 // we have P9 vector integer extend instructions. The code assumes legal 13734 // input types (i.e. it can't handle things like v4i16) so do not run before 13735 // legalization. 13736 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13737 Reduced = combineBVOfVecSExt(N, DAG); 13738 if (Reduced) 13739 return Reduced; 13740 } 13741 13742 13743 if (N->getValueType(0) != MVT::v2f64) 13744 return SDValue(); 13745 13746 // Looking for: 13747 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13748 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13749 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13750 return SDValue(); 13751 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13752 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13753 return SDValue(); 13754 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13755 return SDValue(); 13756 13757 SDValue Ext1 = FirstInput.getOperand(0); 13758 SDValue Ext2 = N->getOperand(1).getOperand(0); 13759 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13760 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13761 return SDValue(); 13762 13763 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13764 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13765 if (!Ext1Op || !Ext2Op) 13766 return SDValue(); 13767 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13768 Ext1.getOperand(0) != Ext2.getOperand(0)) 13769 return SDValue(); 13770 13771 int FirstElem = Ext1Op->getZExtValue(); 13772 int SecondElem = Ext2Op->getZExtValue(); 13773 int SubvecIdx; 13774 if (FirstElem == 0 && SecondElem == 1) 13775 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13776 else if (FirstElem == 2 && SecondElem == 3) 13777 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13778 else 13779 return SDValue(); 13780 13781 SDValue SrcVec = Ext1.getOperand(0); 13782 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13783 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13784 return DAG.getNode(NodeType, dl, MVT::v2f64, 13785 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13786 } 13787 13788 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13789 DAGCombinerInfo &DCI) const { 13790 assert((N->getOpcode() == ISD::SINT_TO_FP || 13791 N->getOpcode() == ISD::UINT_TO_FP) && 13792 "Need an int -> FP conversion node here"); 13793 13794 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13795 return SDValue(); 13796 13797 SelectionDAG &DAG = DCI.DAG; 13798 SDLoc dl(N); 13799 SDValue Op(N, 0); 13800 13801 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13802 // from the hardware. 13803 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13804 return SDValue(); 13805 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13806 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13807 return SDValue(); 13808 13809 SDValue FirstOperand(Op.getOperand(0)); 13810 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13811 (FirstOperand.getValueType() == MVT::i8 || 13812 FirstOperand.getValueType() == MVT::i16); 13813 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13814 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13815 bool DstDouble = Op.getValueType() == MVT::f64; 13816 unsigned ConvOp = Signed ? 13817 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13818 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13819 SDValue WidthConst = 13820 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13821 dl, false); 13822 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13823 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13824 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13825 DAG.getVTList(MVT::f64, MVT::Other), 13826 Ops, MVT::i8, LDN->getMemOperand()); 13827 13828 // For signed conversion, we need to sign-extend the value in the VSR 13829 if (Signed) { 13830 SDValue ExtOps[] = { Ld, WidthConst }; 13831 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13832 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13833 } else 13834 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13835 } 13836 13837 13838 // For i32 intermediate values, unfortunately, the conversion functions 13839 // leave the upper 32 bits of the value are undefined. Within the set of 13840 // scalar instructions, we have no method for zero- or sign-extending the 13841 // value. Thus, we cannot handle i32 intermediate values here. 13842 if (Op.getOperand(0).getValueType() == MVT::i32) 13843 return SDValue(); 13844 13845 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13846 "UINT_TO_FP is supported only with FPCVT"); 13847 13848 // If we have FCFIDS, then use it when converting to single-precision. 13849 // Otherwise, convert to double-precision and then round. 13850 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13851 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13852 : PPCISD::FCFIDS) 13853 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13854 : PPCISD::FCFID); 13855 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13856 ? MVT::f32 13857 : MVT::f64; 13858 13859 // If we're converting from a float, to an int, and back to a float again, 13860 // then we don't need the store/load pair at all. 13861 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13862 Subtarget.hasFPCVT()) || 13863 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13864 SDValue Src = Op.getOperand(0).getOperand(0); 13865 if (Src.getValueType() == MVT::f32) { 13866 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13867 DCI.AddToWorklist(Src.getNode()); 13868 } else if (Src.getValueType() != MVT::f64) { 13869 // Make sure that we don't pick up a ppc_fp128 source value. 13870 return SDValue(); 13871 } 13872 13873 unsigned FCTOp = 13874 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13875 PPCISD::FCTIDUZ; 13876 13877 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13878 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13879 13880 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13881 FP = DAG.getNode(ISD::FP_ROUND, dl, 13882 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13883 DCI.AddToWorklist(FP.getNode()); 13884 } 13885 13886 return FP; 13887 } 13888 13889 return SDValue(); 13890 } 13891 13892 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13893 // builtins) into loads with swaps. 13894 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13895 DAGCombinerInfo &DCI) const { 13896 SelectionDAG &DAG = DCI.DAG; 13897 SDLoc dl(N); 13898 SDValue Chain; 13899 SDValue Base; 13900 MachineMemOperand *MMO; 13901 13902 switch (N->getOpcode()) { 13903 default: 13904 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13905 case ISD::LOAD: { 13906 LoadSDNode *LD = cast<LoadSDNode>(N); 13907 Chain = LD->getChain(); 13908 Base = LD->getBasePtr(); 13909 MMO = LD->getMemOperand(); 13910 // If the MMO suggests this isn't a load of a full vector, leave 13911 // things alone. For a built-in, we have to make the change for 13912 // correctness, so if there is a size problem that will be a bug. 13913 if (MMO->getSize() < 16) 13914 return SDValue(); 13915 break; 13916 } 13917 case ISD::INTRINSIC_W_CHAIN: { 13918 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13919 Chain = Intrin->getChain(); 13920 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13921 // us what we want. Get operand 2 instead. 13922 Base = Intrin->getOperand(2); 13923 MMO = Intrin->getMemOperand(); 13924 break; 13925 } 13926 } 13927 13928 MVT VecTy = N->getValueType(0).getSimpleVT(); 13929 13930 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13931 // aligned and the type is a vector with elements up to 4 bytes 13932 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13933 VecTy.getScalarSizeInBits() <= 32) { 13934 return SDValue(); 13935 } 13936 13937 SDValue LoadOps[] = { Chain, Base }; 13938 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13939 DAG.getVTList(MVT::v2f64, MVT::Other), 13940 LoadOps, MVT::v2f64, MMO); 13941 13942 DCI.AddToWorklist(Load.getNode()); 13943 Chain = Load.getValue(1); 13944 SDValue Swap = DAG.getNode( 13945 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13946 DCI.AddToWorklist(Swap.getNode()); 13947 13948 // Add a bitcast if the resulting load type doesn't match v2f64. 13949 if (VecTy != MVT::v2f64) { 13950 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13951 DCI.AddToWorklist(N.getNode()); 13952 // Package {bitcast value, swap's chain} to match Load's shape. 13953 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13954 N, Swap.getValue(1)); 13955 } 13956 13957 return Swap; 13958 } 13959 13960 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13961 // builtins) into stores with swaps. 13962 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13963 DAGCombinerInfo &DCI) const { 13964 SelectionDAG &DAG = DCI.DAG; 13965 SDLoc dl(N); 13966 SDValue Chain; 13967 SDValue Base; 13968 unsigned SrcOpnd; 13969 MachineMemOperand *MMO; 13970 13971 switch (N->getOpcode()) { 13972 default: 13973 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13974 case ISD::STORE: { 13975 StoreSDNode *ST = cast<StoreSDNode>(N); 13976 Chain = ST->getChain(); 13977 Base = ST->getBasePtr(); 13978 MMO = ST->getMemOperand(); 13979 SrcOpnd = 1; 13980 // If the MMO suggests this isn't a store of a full vector, leave 13981 // things alone. For a built-in, we have to make the change for 13982 // correctness, so if there is a size problem that will be a bug. 13983 if (MMO->getSize() < 16) 13984 return SDValue(); 13985 break; 13986 } 13987 case ISD::INTRINSIC_VOID: { 13988 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13989 Chain = Intrin->getChain(); 13990 // Intrin->getBasePtr() oddly does not get what we want. 13991 Base = Intrin->getOperand(3); 13992 MMO = Intrin->getMemOperand(); 13993 SrcOpnd = 2; 13994 break; 13995 } 13996 } 13997 13998 SDValue Src = N->getOperand(SrcOpnd); 13999 MVT VecTy = Src.getValueType().getSimpleVT(); 14000 14001 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14002 // aligned and the type is a vector with elements up to 4 bytes 14003 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14004 VecTy.getScalarSizeInBits() <= 32) { 14005 return SDValue(); 14006 } 14007 14008 // All stores are done as v2f64 and possible bit cast. 14009 if (VecTy != MVT::v2f64) { 14010 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14011 DCI.AddToWorklist(Src.getNode()); 14012 } 14013 14014 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14015 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14016 DCI.AddToWorklist(Swap.getNode()); 14017 Chain = Swap.getValue(1); 14018 SDValue StoreOps[] = { Chain, Swap, Base }; 14019 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14020 DAG.getVTList(MVT::Other), 14021 StoreOps, VecTy, MMO); 14022 DCI.AddToWorklist(Store.getNode()); 14023 return Store; 14024 } 14025 14026 // Handle DAG combine for STORE (FP_TO_INT F). 14027 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14028 DAGCombinerInfo &DCI) const { 14029 14030 SelectionDAG &DAG = DCI.DAG; 14031 SDLoc dl(N); 14032 unsigned Opcode = N->getOperand(1).getOpcode(); 14033 14034 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14035 && "Not a FP_TO_INT Instruction!"); 14036 14037 SDValue Val = N->getOperand(1).getOperand(0); 14038 EVT Op1VT = N->getOperand(1).getValueType(); 14039 EVT ResVT = Val.getValueType(); 14040 14041 // Floating point types smaller than 32 bits are not legal on Power. 14042 if (ResVT.getScalarSizeInBits() < 32) 14043 return SDValue(); 14044 14045 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14046 bool ValidTypeForStoreFltAsInt = 14047 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14048 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14049 14050 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14051 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14052 return SDValue(); 14053 14054 // Extend f32 values to f64 14055 if (ResVT.getScalarSizeInBits() == 32) { 14056 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14057 DCI.AddToWorklist(Val.getNode()); 14058 } 14059 14060 // Set signed or unsigned conversion opcode. 14061 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14062 PPCISD::FP_TO_SINT_IN_VSR : 14063 PPCISD::FP_TO_UINT_IN_VSR; 14064 14065 Val = DAG.getNode(ConvOpcode, 14066 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14067 DCI.AddToWorklist(Val.getNode()); 14068 14069 // Set number of bytes being converted. 14070 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14071 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14072 DAG.getIntPtrConstant(ByteSize, dl, false), 14073 DAG.getValueType(Op1VT) }; 14074 14075 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14076 DAG.getVTList(MVT::Other), Ops, 14077 cast<StoreSDNode>(N)->getMemoryVT(), 14078 cast<StoreSDNode>(N)->getMemOperand()); 14079 14080 DCI.AddToWorklist(Val.getNode()); 14081 return Val; 14082 } 14083 14084 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14085 LSBaseSDNode *LSBase, 14086 DAGCombinerInfo &DCI) const { 14087 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14088 "Not a reverse memop pattern!"); 14089 14090 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14091 auto Mask = SVN->getMask(); 14092 int i = 0; 14093 auto I = Mask.rbegin(); 14094 auto E = Mask.rend(); 14095 14096 for (; I != E; ++I) { 14097 if (*I != i) 14098 return false; 14099 i++; 14100 } 14101 return true; 14102 }; 14103 14104 SelectionDAG &DAG = DCI.DAG; 14105 EVT VT = SVN->getValueType(0); 14106 14107 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14108 return SDValue(); 14109 14110 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14111 // See comment in PPCVSXSwapRemoval.cpp. 14112 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14113 if (!Subtarget.hasP9Vector()) 14114 return SDValue(); 14115 14116 if(!IsElementReverse(SVN)) 14117 return SDValue(); 14118 14119 if (LSBase->getOpcode() == ISD::LOAD) { 14120 SDLoc dl(SVN); 14121 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14122 return DAG.getMemIntrinsicNode( 14123 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14124 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14125 } 14126 14127 if (LSBase->getOpcode() == ISD::STORE) { 14128 SDLoc dl(LSBase); 14129 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14130 LSBase->getBasePtr()}; 14131 return DAG.getMemIntrinsicNode( 14132 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14133 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14134 } 14135 14136 llvm_unreachable("Expected a load or store node here"); 14137 } 14138 14139 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14140 DAGCombinerInfo &DCI) const { 14141 SelectionDAG &DAG = DCI.DAG; 14142 SDLoc dl(N); 14143 switch (N->getOpcode()) { 14144 default: break; 14145 case ISD::ADD: 14146 return combineADD(N, DCI); 14147 case ISD::SHL: 14148 return combineSHL(N, DCI); 14149 case ISD::SRA: 14150 return combineSRA(N, DCI); 14151 case ISD::SRL: 14152 return combineSRL(N, DCI); 14153 case ISD::MUL: 14154 return combineMUL(N, DCI); 14155 case ISD::FMA: 14156 case PPCISD::FNMSUB: 14157 return combineFMALike(N, DCI); 14158 case PPCISD::SHL: 14159 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14160 return N->getOperand(0); 14161 break; 14162 case PPCISD::SRL: 14163 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14164 return N->getOperand(0); 14165 break; 14166 case PPCISD::SRA: 14167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14168 if (C->isNullValue() || // 0 >>s V -> 0. 14169 C->isAllOnesValue()) // -1 >>s V -> -1. 14170 return N->getOperand(0); 14171 } 14172 break; 14173 case ISD::SIGN_EXTEND: 14174 case ISD::ZERO_EXTEND: 14175 case ISD::ANY_EXTEND: 14176 return DAGCombineExtBoolTrunc(N, DCI); 14177 case ISD::TRUNCATE: 14178 return combineTRUNCATE(N, DCI); 14179 case ISD::SETCC: 14180 if (SDValue CSCC = combineSetCC(N, DCI)) 14181 return CSCC; 14182 LLVM_FALLTHROUGH; 14183 case ISD::SELECT_CC: 14184 return DAGCombineTruncBoolExt(N, DCI); 14185 case ISD::SINT_TO_FP: 14186 case ISD::UINT_TO_FP: 14187 return combineFPToIntToFP(N, DCI); 14188 case ISD::VECTOR_SHUFFLE: 14189 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14190 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14191 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14192 } 14193 break; 14194 case ISD::STORE: { 14195 14196 EVT Op1VT = N->getOperand(1).getValueType(); 14197 unsigned Opcode = N->getOperand(1).getOpcode(); 14198 14199 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14200 SDValue Val= combineStoreFPToInt(N, DCI); 14201 if (Val) 14202 return Val; 14203 } 14204 14205 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14206 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14207 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14208 if (Val) 14209 return Val; 14210 } 14211 14212 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14213 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14214 N->getOperand(1).getNode()->hasOneUse() && 14215 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14216 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14217 14218 // STBRX can only handle simple types and it makes no sense to store less 14219 // two bytes in byte-reversed order. 14220 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14221 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14222 break; 14223 14224 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14225 // Do an any-extend to 32-bits if this is a half-word input. 14226 if (BSwapOp.getValueType() == MVT::i16) 14227 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14228 14229 // If the type of BSWAP operand is wider than stored memory width 14230 // it need to be shifted to the right side before STBRX. 14231 if (Op1VT.bitsGT(mVT)) { 14232 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14233 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14234 DAG.getConstant(Shift, dl, MVT::i32)); 14235 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14236 if (Op1VT == MVT::i64) 14237 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14238 } 14239 14240 SDValue Ops[] = { 14241 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14242 }; 14243 return 14244 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14245 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14246 cast<StoreSDNode>(N)->getMemOperand()); 14247 } 14248 14249 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14250 // So it can increase the chance of CSE constant construction. 14251 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14252 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14253 // Need to sign-extended to 64-bits to handle negative values. 14254 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14255 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14256 MemVT.getSizeInBits()); 14257 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14258 14259 // DAG.getTruncStore() can't be used here because it doesn't accept 14260 // the general (base + offset) addressing mode. 14261 // So we use UpdateNodeOperands and setTruncatingStore instead. 14262 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14263 N->getOperand(3)); 14264 cast<StoreSDNode>(N)->setTruncatingStore(true); 14265 return SDValue(N, 0); 14266 } 14267 14268 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14269 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14270 if (Op1VT.isSimple()) { 14271 MVT StoreVT = Op1VT.getSimpleVT(); 14272 if (Subtarget.needsSwapsForVSXMemOps() && 14273 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14274 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14275 return expandVSXStoreForLE(N, DCI); 14276 } 14277 break; 14278 } 14279 case ISD::LOAD: { 14280 LoadSDNode *LD = cast<LoadSDNode>(N); 14281 EVT VT = LD->getValueType(0); 14282 14283 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14284 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14285 if (VT.isSimple()) { 14286 MVT LoadVT = VT.getSimpleVT(); 14287 if (Subtarget.needsSwapsForVSXMemOps() && 14288 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14289 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14290 return expandVSXLoadForLE(N, DCI); 14291 } 14292 14293 // We sometimes end up with a 64-bit integer load, from which we extract 14294 // two single-precision floating-point numbers. This happens with 14295 // std::complex<float>, and other similar structures, because of the way we 14296 // canonicalize structure copies. However, if we lack direct moves, 14297 // then the final bitcasts from the extracted integer values to the 14298 // floating-point numbers turn into store/load pairs. Even with direct moves, 14299 // just loading the two floating-point numbers is likely better. 14300 auto ReplaceTwoFloatLoad = [&]() { 14301 if (VT != MVT::i64) 14302 return false; 14303 14304 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14305 LD->isVolatile()) 14306 return false; 14307 14308 // We're looking for a sequence like this: 14309 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14310 // t16: i64 = srl t13, Constant:i32<32> 14311 // t17: i32 = truncate t16 14312 // t18: f32 = bitcast t17 14313 // t19: i32 = truncate t13 14314 // t20: f32 = bitcast t19 14315 14316 if (!LD->hasNUsesOfValue(2, 0)) 14317 return false; 14318 14319 auto UI = LD->use_begin(); 14320 while (UI.getUse().getResNo() != 0) ++UI; 14321 SDNode *Trunc = *UI++; 14322 while (UI.getUse().getResNo() != 0) ++UI; 14323 SDNode *RightShift = *UI; 14324 if (Trunc->getOpcode() != ISD::TRUNCATE) 14325 std::swap(Trunc, RightShift); 14326 14327 if (Trunc->getOpcode() != ISD::TRUNCATE || 14328 Trunc->getValueType(0) != MVT::i32 || 14329 !Trunc->hasOneUse()) 14330 return false; 14331 if (RightShift->getOpcode() != ISD::SRL || 14332 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14333 RightShift->getConstantOperandVal(1) != 32 || 14334 !RightShift->hasOneUse()) 14335 return false; 14336 14337 SDNode *Trunc2 = *RightShift->use_begin(); 14338 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14339 Trunc2->getValueType(0) != MVT::i32 || 14340 !Trunc2->hasOneUse()) 14341 return false; 14342 14343 SDNode *Bitcast = *Trunc->use_begin(); 14344 SDNode *Bitcast2 = *Trunc2->use_begin(); 14345 14346 if (Bitcast->getOpcode() != ISD::BITCAST || 14347 Bitcast->getValueType(0) != MVT::f32) 14348 return false; 14349 if (Bitcast2->getOpcode() != ISD::BITCAST || 14350 Bitcast2->getValueType(0) != MVT::f32) 14351 return false; 14352 14353 if (Subtarget.isLittleEndian()) 14354 std::swap(Bitcast, Bitcast2); 14355 14356 // Bitcast has the second float (in memory-layout order) and Bitcast2 14357 // has the first one. 14358 14359 SDValue BasePtr = LD->getBasePtr(); 14360 if (LD->isIndexed()) { 14361 assert(LD->getAddressingMode() == ISD::PRE_INC && 14362 "Non-pre-inc AM on PPC?"); 14363 BasePtr = 14364 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14365 LD->getOffset()); 14366 } 14367 14368 auto MMOFlags = 14369 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14370 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14371 LD->getPointerInfo(), LD->getAlignment(), 14372 MMOFlags, LD->getAAInfo()); 14373 SDValue AddPtr = 14374 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14375 BasePtr, DAG.getIntPtrConstant(4, dl)); 14376 SDValue FloatLoad2 = DAG.getLoad( 14377 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14378 LD->getPointerInfo().getWithOffset(4), 14379 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14380 14381 if (LD->isIndexed()) { 14382 // Note that DAGCombine should re-form any pre-increment load(s) from 14383 // what is produced here if that makes sense. 14384 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14385 } 14386 14387 DCI.CombineTo(Bitcast2, FloatLoad); 14388 DCI.CombineTo(Bitcast, FloatLoad2); 14389 14390 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14391 SDValue(FloatLoad2.getNode(), 1)); 14392 return true; 14393 }; 14394 14395 if (ReplaceTwoFloatLoad()) 14396 return SDValue(N, 0); 14397 14398 EVT MemVT = LD->getMemoryVT(); 14399 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14400 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14401 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14402 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14403 if (LD->isUnindexed() && VT.isVector() && 14404 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14405 // P8 and later hardware should just use LOAD. 14406 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14407 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14408 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14409 LD->getAlignment() >= ScalarABIAlignment)) && 14410 LD->getAlignment() < ABIAlignment) { 14411 // This is a type-legal unaligned Altivec or QPX load. 14412 SDValue Chain = LD->getChain(); 14413 SDValue Ptr = LD->getBasePtr(); 14414 bool isLittleEndian = Subtarget.isLittleEndian(); 14415 14416 // This implements the loading of unaligned vectors as described in 14417 // the venerable Apple Velocity Engine overview. Specifically: 14418 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14419 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14420 // 14421 // The general idea is to expand a sequence of one or more unaligned 14422 // loads into an alignment-based permutation-control instruction (lvsl 14423 // or lvsr), a series of regular vector loads (which always truncate 14424 // their input address to an aligned address), and a series of 14425 // permutations. The results of these permutations are the requested 14426 // loaded values. The trick is that the last "extra" load is not taken 14427 // from the address you might suspect (sizeof(vector) bytes after the 14428 // last requested load), but rather sizeof(vector) - 1 bytes after the 14429 // last requested vector. The point of this is to avoid a page fault if 14430 // the base address happened to be aligned. This works because if the 14431 // base address is aligned, then adding less than a full vector length 14432 // will cause the last vector in the sequence to be (re)loaded. 14433 // Otherwise, the next vector will be fetched as you might suspect was 14434 // necessary. 14435 14436 // We might be able to reuse the permutation generation from 14437 // a different base address offset from this one by an aligned amount. 14438 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14439 // optimization later. 14440 Intrinsic::ID Intr, IntrLD, IntrPerm; 14441 MVT PermCntlTy, PermTy, LDTy; 14442 if (Subtarget.hasAltivec()) { 14443 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14444 Intrinsic::ppc_altivec_lvsl; 14445 IntrLD = Intrinsic::ppc_altivec_lvx; 14446 IntrPerm = Intrinsic::ppc_altivec_vperm; 14447 PermCntlTy = MVT::v16i8; 14448 PermTy = MVT::v4i32; 14449 LDTy = MVT::v4i32; 14450 } else { 14451 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14452 Intrinsic::ppc_qpx_qvlpcls; 14453 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14454 Intrinsic::ppc_qpx_qvlfs; 14455 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14456 PermCntlTy = MVT::v4f64; 14457 PermTy = MVT::v4f64; 14458 LDTy = MemVT.getSimpleVT(); 14459 } 14460 14461 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14462 14463 // Create the new MMO for the new base load. It is like the original MMO, 14464 // but represents an area in memory almost twice the vector size centered 14465 // on the original address. If the address is unaligned, we might start 14466 // reading up to (sizeof(vector)-1) bytes below the address of the 14467 // original unaligned load. 14468 MachineFunction &MF = DAG.getMachineFunction(); 14469 MachineMemOperand *BaseMMO = 14470 MF.getMachineMemOperand(LD->getMemOperand(), 14471 -(long)MemVT.getStoreSize()+1, 14472 2*MemVT.getStoreSize()-1); 14473 14474 // Create the new base load. 14475 SDValue LDXIntID = 14476 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14477 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14478 SDValue BaseLoad = 14479 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14480 DAG.getVTList(PermTy, MVT::Other), 14481 BaseLoadOps, LDTy, BaseMMO); 14482 14483 // Note that the value of IncOffset (which is provided to the next 14484 // load's pointer info offset value, and thus used to calculate the 14485 // alignment), and the value of IncValue (which is actually used to 14486 // increment the pointer value) are different! This is because we 14487 // require the next load to appear to be aligned, even though it 14488 // is actually offset from the base pointer by a lesser amount. 14489 int IncOffset = VT.getSizeInBits() / 8; 14490 int IncValue = IncOffset; 14491 14492 // Walk (both up and down) the chain looking for another load at the real 14493 // (aligned) offset (the alignment of the other load does not matter in 14494 // this case). If found, then do not use the offset reduction trick, as 14495 // that will prevent the loads from being later combined (as they would 14496 // otherwise be duplicates). 14497 if (!findConsecutiveLoad(LD, DAG)) 14498 --IncValue; 14499 14500 SDValue Increment = 14501 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14502 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14503 14504 MachineMemOperand *ExtraMMO = 14505 MF.getMachineMemOperand(LD->getMemOperand(), 14506 1, 2*MemVT.getStoreSize()-1); 14507 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14508 SDValue ExtraLoad = 14509 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14510 DAG.getVTList(PermTy, MVT::Other), 14511 ExtraLoadOps, LDTy, ExtraMMO); 14512 14513 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14514 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14515 14516 // Because vperm has a big-endian bias, we must reverse the order 14517 // of the input vectors and complement the permute control vector 14518 // when generating little endian code. We have already handled the 14519 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14520 // and ExtraLoad here. 14521 SDValue Perm; 14522 if (isLittleEndian) 14523 Perm = BuildIntrinsicOp(IntrPerm, 14524 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14525 else 14526 Perm = BuildIntrinsicOp(IntrPerm, 14527 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14528 14529 if (VT != PermTy) 14530 Perm = Subtarget.hasAltivec() ? 14531 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14532 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14533 DAG.getTargetConstant(1, dl, MVT::i64)); 14534 // second argument is 1 because this rounding 14535 // is always exact. 14536 14537 // The output of the permutation is our loaded result, the TokenFactor is 14538 // our new chain. 14539 DCI.CombineTo(N, Perm, TF); 14540 return SDValue(N, 0); 14541 } 14542 } 14543 break; 14544 case ISD::INTRINSIC_WO_CHAIN: { 14545 bool isLittleEndian = Subtarget.isLittleEndian(); 14546 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14547 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14548 : Intrinsic::ppc_altivec_lvsl); 14549 if ((IID == Intr || 14550 IID == Intrinsic::ppc_qpx_qvlpcld || 14551 IID == Intrinsic::ppc_qpx_qvlpcls) && 14552 N->getOperand(1)->getOpcode() == ISD::ADD) { 14553 SDValue Add = N->getOperand(1); 14554 14555 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14556 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14557 14558 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14559 APInt::getAllOnesValue(Bits /* alignment */) 14560 .zext(Add.getScalarValueSizeInBits()))) { 14561 SDNode *BasePtr = Add->getOperand(0).getNode(); 14562 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14563 UE = BasePtr->use_end(); 14564 UI != UE; ++UI) { 14565 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14566 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14567 // We've found another LVSL/LVSR, and this address is an aligned 14568 // multiple of that one. The results will be the same, so use the 14569 // one we've just found instead. 14570 14571 return SDValue(*UI, 0); 14572 } 14573 } 14574 } 14575 14576 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14577 SDNode *BasePtr = Add->getOperand(0).getNode(); 14578 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14579 UE = BasePtr->use_end(); UI != UE; ++UI) { 14580 if (UI->getOpcode() == ISD::ADD && 14581 isa<ConstantSDNode>(UI->getOperand(1)) && 14582 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14583 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14584 (1ULL << Bits) == 0) { 14585 SDNode *OtherAdd = *UI; 14586 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14587 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14588 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14589 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14590 return SDValue(*VI, 0); 14591 } 14592 } 14593 } 14594 } 14595 } 14596 } 14597 14598 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14599 // Expose the vabsduw/h/b opportunity for down stream 14600 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14601 (IID == Intrinsic::ppc_altivec_vmaxsw || 14602 IID == Intrinsic::ppc_altivec_vmaxsh || 14603 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14604 SDValue V1 = N->getOperand(1); 14605 SDValue V2 = N->getOperand(2); 14606 if ((V1.getSimpleValueType() == MVT::v4i32 || 14607 V1.getSimpleValueType() == MVT::v8i16 || 14608 V1.getSimpleValueType() == MVT::v16i8) && 14609 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14610 // (0-a, a) 14611 if (V1.getOpcode() == ISD::SUB && 14612 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14613 V1.getOperand(1) == V2) { 14614 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14615 } 14616 // (a, 0-a) 14617 if (V2.getOpcode() == ISD::SUB && 14618 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14619 V2.getOperand(1) == V1) { 14620 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14621 } 14622 // (x-y, y-x) 14623 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14624 V1.getOperand(0) == V2.getOperand(1) && 14625 V1.getOperand(1) == V2.getOperand(0)) { 14626 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14627 } 14628 } 14629 } 14630 } 14631 14632 break; 14633 case ISD::INTRINSIC_W_CHAIN: 14634 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14635 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14636 if (Subtarget.needsSwapsForVSXMemOps()) { 14637 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14638 default: 14639 break; 14640 case Intrinsic::ppc_vsx_lxvw4x: 14641 case Intrinsic::ppc_vsx_lxvd2x: 14642 return expandVSXLoadForLE(N, DCI); 14643 } 14644 } 14645 break; 14646 case ISD::INTRINSIC_VOID: 14647 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14648 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14649 if (Subtarget.needsSwapsForVSXMemOps()) { 14650 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14651 default: 14652 break; 14653 case Intrinsic::ppc_vsx_stxvw4x: 14654 case Intrinsic::ppc_vsx_stxvd2x: 14655 return expandVSXStoreForLE(N, DCI); 14656 } 14657 } 14658 break; 14659 case ISD::BSWAP: 14660 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14661 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14662 N->getOperand(0).hasOneUse() && 14663 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14664 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14665 N->getValueType(0) == MVT::i64))) { 14666 SDValue Load = N->getOperand(0); 14667 LoadSDNode *LD = cast<LoadSDNode>(Load); 14668 // Create the byte-swapping load. 14669 SDValue Ops[] = { 14670 LD->getChain(), // Chain 14671 LD->getBasePtr(), // Ptr 14672 DAG.getValueType(N->getValueType(0)) // VT 14673 }; 14674 SDValue BSLoad = 14675 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14676 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14677 MVT::i64 : MVT::i32, MVT::Other), 14678 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14679 14680 // If this is an i16 load, insert the truncate. 14681 SDValue ResVal = BSLoad; 14682 if (N->getValueType(0) == MVT::i16) 14683 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14684 14685 // First, combine the bswap away. This makes the value produced by the 14686 // load dead. 14687 DCI.CombineTo(N, ResVal); 14688 14689 // Next, combine the load away, we give it a bogus result value but a real 14690 // chain result. The result value is dead because the bswap is dead. 14691 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14692 14693 // Return N so it doesn't get rechecked! 14694 return SDValue(N, 0); 14695 } 14696 break; 14697 case PPCISD::VCMP: 14698 // If a VCMPo node already exists with exactly the same operands as this 14699 // node, use its result instead of this node (VCMPo computes both a CR6 and 14700 // a normal output). 14701 // 14702 if (!N->getOperand(0).hasOneUse() && 14703 !N->getOperand(1).hasOneUse() && 14704 !N->getOperand(2).hasOneUse()) { 14705 14706 // Scan all of the users of the LHS, looking for VCMPo's that match. 14707 SDNode *VCMPoNode = nullptr; 14708 14709 SDNode *LHSN = N->getOperand(0).getNode(); 14710 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14711 UI != E; ++UI) 14712 if (UI->getOpcode() == PPCISD::VCMPo && 14713 UI->getOperand(1) == N->getOperand(1) && 14714 UI->getOperand(2) == N->getOperand(2) && 14715 UI->getOperand(0) == N->getOperand(0)) { 14716 VCMPoNode = *UI; 14717 break; 14718 } 14719 14720 // If there is no VCMPo node, or if the flag value has a single use, don't 14721 // transform this. 14722 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14723 break; 14724 14725 // Look at the (necessarily single) use of the flag value. If it has a 14726 // chain, this transformation is more complex. Note that multiple things 14727 // could use the value result, which we should ignore. 14728 SDNode *FlagUser = nullptr; 14729 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14730 FlagUser == nullptr; ++UI) { 14731 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14732 SDNode *User = *UI; 14733 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14734 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14735 FlagUser = User; 14736 break; 14737 } 14738 } 14739 } 14740 14741 // If the user is a MFOCRF instruction, we know this is safe. 14742 // Otherwise we give up for right now. 14743 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14744 return SDValue(VCMPoNode, 0); 14745 } 14746 break; 14747 case ISD::BRCOND: { 14748 SDValue Cond = N->getOperand(1); 14749 SDValue Target = N->getOperand(2); 14750 14751 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14752 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14753 Intrinsic::loop_decrement) { 14754 14755 // We now need to make the intrinsic dead (it cannot be instruction 14756 // selected). 14757 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14758 assert(Cond.getNode()->hasOneUse() && 14759 "Counter decrement has more than one use"); 14760 14761 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14762 N->getOperand(0), Target); 14763 } 14764 } 14765 break; 14766 case ISD::BR_CC: { 14767 // If this is a branch on an altivec predicate comparison, lower this so 14768 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14769 // lowering is done pre-legalize, because the legalizer lowers the predicate 14770 // compare down to code that is difficult to reassemble. 14771 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14772 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14773 14774 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14775 // value. If so, pass-through the AND to get to the intrinsic. 14776 if (LHS.getOpcode() == ISD::AND && 14777 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14778 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14779 Intrinsic::loop_decrement && 14780 isa<ConstantSDNode>(LHS.getOperand(1)) && 14781 !isNullConstant(LHS.getOperand(1))) 14782 LHS = LHS.getOperand(0); 14783 14784 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14785 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14786 Intrinsic::loop_decrement && 14787 isa<ConstantSDNode>(RHS)) { 14788 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14789 "Counter decrement comparison is not EQ or NE"); 14790 14791 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14792 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14793 (CC == ISD::SETNE && !Val); 14794 14795 // We now need to make the intrinsic dead (it cannot be instruction 14796 // selected). 14797 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14798 assert(LHS.getNode()->hasOneUse() && 14799 "Counter decrement has more than one use"); 14800 14801 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14802 N->getOperand(0), N->getOperand(4)); 14803 } 14804 14805 int CompareOpc; 14806 bool isDot; 14807 14808 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14809 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14810 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14811 assert(isDot && "Can't compare against a vector result!"); 14812 14813 // If this is a comparison against something other than 0/1, then we know 14814 // that the condition is never/always true. 14815 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14816 if (Val != 0 && Val != 1) { 14817 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14818 return N->getOperand(0); 14819 // Always !=, turn it into an unconditional branch. 14820 return DAG.getNode(ISD::BR, dl, MVT::Other, 14821 N->getOperand(0), N->getOperand(4)); 14822 } 14823 14824 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14825 14826 // Create the PPCISD altivec 'dot' comparison node. 14827 SDValue Ops[] = { 14828 LHS.getOperand(2), // LHS of compare 14829 LHS.getOperand(3), // RHS of compare 14830 DAG.getConstant(CompareOpc, dl, MVT::i32) 14831 }; 14832 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14833 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14834 14835 // Unpack the result based on how the target uses it. 14836 PPC::Predicate CompOpc; 14837 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14838 default: // Can't happen, don't crash on invalid number though. 14839 case 0: // Branch on the value of the EQ bit of CR6. 14840 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14841 break; 14842 case 1: // Branch on the inverted value of the EQ bit of CR6. 14843 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14844 break; 14845 case 2: // Branch on the value of the LT bit of CR6. 14846 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14847 break; 14848 case 3: // Branch on the inverted value of the LT bit of CR6. 14849 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14850 break; 14851 } 14852 14853 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14854 DAG.getConstant(CompOpc, dl, MVT::i32), 14855 DAG.getRegister(PPC::CR6, MVT::i32), 14856 N->getOperand(4), CompNode.getValue(1)); 14857 } 14858 break; 14859 } 14860 case ISD::BUILD_VECTOR: 14861 return DAGCombineBuildVector(N, DCI); 14862 case ISD::ABS: 14863 return combineABS(N, DCI); 14864 case ISD::VSELECT: 14865 return combineVSelect(N, DCI); 14866 } 14867 14868 return SDValue(); 14869 } 14870 14871 SDValue 14872 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14873 SelectionDAG &DAG, 14874 SmallVectorImpl<SDNode *> &Created) const { 14875 // fold (sdiv X, pow2) 14876 EVT VT = N->getValueType(0); 14877 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14878 return SDValue(); 14879 if ((VT != MVT::i32 && VT != MVT::i64) || 14880 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14881 return SDValue(); 14882 14883 SDLoc DL(N); 14884 SDValue N0 = N->getOperand(0); 14885 14886 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14887 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14888 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14889 14890 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14891 Created.push_back(Op.getNode()); 14892 14893 if (IsNegPow2) { 14894 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14895 Created.push_back(Op.getNode()); 14896 } 14897 14898 return Op; 14899 } 14900 14901 //===----------------------------------------------------------------------===// 14902 // Inline Assembly Support 14903 //===----------------------------------------------------------------------===// 14904 14905 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14906 KnownBits &Known, 14907 const APInt &DemandedElts, 14908 const SelectionDAG &DAG, 14909 unsigned Depth) const { 14910 Known.resetAll(); 14911 switch (Op.getOpcode()) { 14912 default: break; 14913 case PPCISD::LBRX: { 14914 // lhbrx is known to have the top bits cleared out. 14915 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14916 Known.Zero = 0xFFFF0000; 14917 break; 14918 } 14919 case ISD::INTRINSIC_WO_CHAIN: { 14920 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14921 default: break; 14922 case Intrinsic::ppc_altivec_vcmpbfp_p: 14923 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14924 case Intrinsic::ppc_altivec_vcmpequb_p: 14925 case Intrinsic::ppc_altivec_vcmpequh_p: 14926 case Intrinsic::ppc_altivec_vcmpequw_p: 14927 case Intrinsic::ppc_altivec_vcmpequd_p: 14928 case Intrinsic::ppc_altivec_vcmpgefp_p: 14929 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14930 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14931 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14932 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14933 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14934 case Intrinsic::ppc_altivec_vcmpgtub_p: 14935 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14936 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14937 case Intrinsic::ppc_altivec_vcmpgtud_p: 14938 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14939 break; 14940 } 14941 } 14942 } 14943 } 14944 14945 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14946 switch (Subtarget.getCPUDirective()) { 14947 default: break; 14948 case PPC::DIR_970: 14949 case PPC::DIR_PWR4: 14950 case PPC::DIR_PWR5: 14951 case PPC::DIR_PWR5X: 14952 case PPC::DIR_PWR6: 14953 case PPC::DIR_PWR6X: 14954 case PPC::DIR_PWR7: 14955 case PPC::DIR_PWR8: 14956 case PPC::DIR_PWR9: 14957 case PPC::DIR_PWR10: 14958 case PPC::DIR_PWR_FUTURE: { 14959 if (!ML) 14960 break; 14961 14962 if (!DisableInnermostLoopAlign32) { 14963 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14964 // so that we can decrease cache misses and branch-prediction misses. 14965 // Actual alignment of the loop will depend on the hotness check and other 14966 // logic in alignBlocks. 14967 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14968 return Align(32); 14969 } 14970 14971 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14972 14973 // For small loops (between 5 and 8 instructions), align to a 32-byte 14974 // boundary so that the entire loop fits in one instruction-cache line. 14975 uint64_t LoopSize = 0; 14976 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14977 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14978 LoopSize += TII->getInstSizeInBytes(*J); 14979 if (LoopSize > 32) 14980 break; 14981 } 14982 14983 if (LoopSize > 16 && LoopSize <= 32) 14984 return Align(32); 14985 14986 break; 14987 } 14988 } 14989 14990 return TargetLowering::getPrefLoopAlignment(ML); 14991 } 14992 14993 /// getConstraintType - Given a constraint, return the type of 14994 /// constraint it is for this target. 14995 PPCTargetLowering::ConstraintType 14996 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14997 if (Constraint.size() == 1) { 14998 switch (Constraint[0]) { 14999 default: break; 15000 case 'b': 15001 case 'r': 15002 case 'f': 15003 case 'd': 15004 case 'v': 15005 case 'y': 15006 return C_RegisterClass; 15007 case 'Z': 15008 // FIXME: While Z does indicate a memory constraint, it specifically 15009 // indicates an r+r address (used in conjunction with the 'y' modifier 15010 // in the replacement string). Currently, we're forcing the base 15011 // register to be r0 in the asm printer (which is interpreted as zero) 15012 // and forming the complete address in the second register. This is 15013 // suboptimal. 15014 return C_Memory; 15015 } 15016 } else if (Constraint == "wc") { // individual CR bits. 15017 return C_RegisterClass; 15018 } else if (Constraint == "wa" || Constraint == "wd" || 15019 Constraint == "wf" || Constraint == "ws" || 15020 Constraint == "wi" || Constraint == "ww") { 15021 return C_RegisterClass; // VSX registers. 15022 } 15023 return TargetLowering::getConstraintType(Constraint); 15024 } 15025 15026 /// Examine constraint type and operand type and determine a weight value. 15027 /// This object must already have been set up with the operand type 15028 /// and the current alternative constraint selected. 15029 TargetLowering::ConstraintWeight 15030 PPCTargetLowering::getSingleConstraintMatchWeight( 15031 AsmOperandInfo &info, const char *constraint) const { 15032 ConstraintWeight weight = CW_Invalid; 15033 Value *CallOperandVal = info.CallOperandVal; 15034 // If we don't have a value, we can't do a match, 15035 // but allow it at the lowest weight. 15036 if (!CallOperandVal) 15037 return CW_Default; 15038 Type *type = CallOperandVal->getType(); 15039 15040 // Look at the constraint type. 15041 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15042 return CW_Register; // an individual CR bit. 15043 else if ((StringRef(constraint) == "wa" || 15044 StringRef(constraint) == "wd" || 15045 StringRef(constraint) == "wf") && 15046 type->isVectorTy()) 15047 return CW_Register; 15048 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15049 return CW_Register; // just hold 64-bit integers data. 15050 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15051 return CW_Register; 15052 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15053 return CW_Register; 15054 15055 switch (*constraint) { 15056 default: 15057 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15058 break; 15059 case 'b': 15060 if (type->isIntegerTy()) 15061 weight = CW_Register; 15062 break; 15063 case 'f': 15064 if (type->isFloatTy()) 15065 weight = CW_Register; 15066 break; 15067 case 'd': 15068 if (type->isDoubleTy()) 15069 weight = CW_Register; 15070 break; 15071 case 'v': 15072 if (type->isVectorTy()) 15073 weight = CW_Register; 15074 break; 15075 case 'y': 15076 weight = CW_Register; 15077 break; 15078 case 'Z': 15079 weight = CW_Memory; 15080 break; 15081 } 15082 return weight; 15083 } 15084 15085 std::pair<unsigned, const TargetRegisterClass *> 15086 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15087 StringRef Constraint, 15088 MVT VT) const { 15089 if (Constraint.size() == 1) { 15090 // GCC RS6000 Constraint Letters 15091 switch (Constraint[0]) { 15092 case 'b': // R1-R31 15093 if (VT == MVT::i64 && Subtarget.isPPC64()) 15094 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15095 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15096 case 'r': // R0-R31 15097 if (VT == MVT::i64 && Subtarget.isPPC64()) 15098 return std::make_pair(0U, &PPC::G8RCRegClass); 15099 return std::make_pair(0U, &PPC::GPRCRegClass); 15100 // 'd' and 'f' constraints are both defined to be "the floating point 15101 // registers", where one is for 32-bit and the other for 64-bit. We don't 15102 // really care overly much here so just give them all the same reg classes. 15103 case 'd': 15104 case 'f': 15105 if (Subtarget.hasSPE()) { 15106 if (VT == MVT::f32 || VT == MVT::i32) 15107 return std::make_pair(0U, &PPC::GPRCRegClass); 15108 if (VT == MVT::f64 || VT == MVT::i64) 15109 return std::make_pair(0U, &PPC::SPERCRegClass); 15110 } else { 15111 if (VT == MVT::f32 || VT == MVT::i32) 15112 return std::make_pair(0U, &PPC::F4RCRegClass); 15113 if (VT == MVT::f64 || VT == MVT::i64) 15114 return std::make_pair(0U, &PPC::F8RCRegClass); 15115 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15116 return std::make_pair(0U, &PPC::QFRCRegClass); 15117 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15118 return std::make_pair(0U, &PPC::QSRCRegClass); 15119 } 15120 break; 15121 case 'v': 15122 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15123 return std::make_pair(0U, &PPC::QFRCRegClass); 15124 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15125 return std::make_pair(0U, &PPC::QSRCRegClass); 15126 if (Subtarget.hasAltivec()) 15127 return std::make_pair(0U, &PPC::VRRCRegClass); 15128 break; 15129 case 'y': // crrc 15130 return std::make_pair(0U, &PPC::CRRCRegClass); 15131 } 15132 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15133 // An individual CR bit. 15134 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15135 } else if ((Constraint == "wa" || Constraint == "wd" || 15136 Constraint == "wf" || Constraint == "wi") && 15137 Subtarget.hasVSX()) { 15138 return std::make_pair(0U, &PPC::VSRCRegClass); 15139 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15140 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15141 return std::make_pair(0U, &PPC::VSSRCRegClass); 15142 else 15143 return std::make_pair(0U, &PPC::VSFRCRegClass); 15144 } 15145 15146 // If we name a VSX register, we can't defer to the base class because it 15147 // will not recognize the correct register (their names will be VSL{0-31} 15148 // and V{0-31} so they won't match). So we match them here. 15149 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15150 int VSNum = atoi(Constraint.data() + 3); 15151 assert(VSNum >= 0 && VSNum <= 63 && 15152 "Attempted to access a vsr out of range"); 15153 if (VSNum < 32) 15154 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15155 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15156 } 15157 std::pair<unsigned, const TargetRegisterClass *> R = 15158 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15159 15160 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15161 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15162 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15163 // register. 15164 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15165 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15166 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15167 PPC::GPRCRegClass.contains(R.first)) 15168 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15169 PPC::sub_32, &PPC::G8RCRegClass), 15170 &PPC::G8RCRegClass); 15171 15172 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15173 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15174 R.first = PPC::CR0; 15175 R.second = &PPC::CRRCRegClass; 15176 } 15177 15178 return R; 15179 } 15180 15181 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15182 /// vector. If it is invalid, don't add anything to Ops. 15183 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15184 std::string &Constraint, 15185 std::vector<SDValue>&Ops, 15186 SelectionDAG &DAG) const { 15187 SDValue Result; 15188 15189 // Only support length 1 constraints. 15190 if (Constraint.length() > 1) return; 15191 15192 char Letter = Constraint[0]; 15193 switch (Letter) { 15194 default: break; 15195 case 'I': 15196 case 'J': 15197 case 'K': 15198 case 'L': 15199 case 'M': 15200 case 'N': 15201 case 'O': 15202 case 'P': { 15203 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15204 if (!CST) return; // Must be an immediate to match. 15205 SDLoc dl(Op); 15206 int64_t Value = CST->getSExtValue(); 15207 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15208 // numbers are printed as such. 15209 switch (Letter) { 15210 default: llvm_unreachable("Unknown constraint letter!"); 15211 case 'I': // "I" is a signed 16-bit constant. 15212 if (isInt<16>(Value)) 15213 Result = DAG.getTargetConstant(Value, dl, TCVT); 15214 break; 15215 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15216 if (isShiftedUInt<16, 16>(Value)) 15217 Result = DAG.getTargetConstant(Value, dl, TCVT); 15218 break; 15219 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15220 if (isShiftedInt<16, 16>(Value)) 15221 Result = DAG.getTargetConstant(Value, dl, TCVT); 15222 break; 15223 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15224 if (isUInt<16>(Value)) 15225 Result = DAG.getTargetConstant(Value, dl, TCVT); 15226 break; 15227 case 'M': // "M" is a constant that is greater than 31. 15228 if (Value > 31) 15229 Result = DAG.getTargetConstant(Value, dl, TCVT); 15230 break; 15231 case 'N': // "N" is a positive constant that is an exact power of two. 15232 if (Value > 0 && isPowerOf2_64(Value)) 15233 Result = DAG.getTargetConstant(Value, dl, TCVT); 15234 break; 15235 case 'O': // "O" is the constant zero. 15236 if (Value == 0) 15237 Result = DAG.getTargetConstant(Value, dl, TCVT); 15238 break; 15239 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15240 if (isInt<16>(-Value)) 15241 Result = DAG.getTargetConstant(Value, dl, TCVT); 15242 break; 15243 } 15244 break; 15245 } 15246 } 15247 15248 if (Result.getNode()) { 15249 Ops.push_back(Result); 15250 return; 15251 } 15252 15253 // Handle standard constraint letters. 15254 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15255 } 15256 15257 // isLegalAddressingMode - Return true if the addressing mode represented 15258 // by AM is legal for this target, for a load/store of the specified type. 15259 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15260 const AddrMode &AM, Type *Ty, 15261 unsigned AS, Instruction *I) const { 15262 // PPC does not allow r+i addressing modes for vectors! 15263 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15264 return false; 15265 15266 // PPC allows a sign-extended 16-bit immediate field. 15267 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15268 return false; 15269 15270 // No global is ever allowed as a base. 15271 if (AM.BaseGV) 15272 return false; 15273 15274 // PPC only support r+r, 15275 switch (AM.Scale) { 15276 case 0: // "r+i" or just "i", depending on HasBaseReg. 15277 break; 15278 case 1: 15279 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15280 return false; 15281 // Otherwise we have r+r or r+i. 15282 break; 15283 case 2: 15284 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15285 return false; 15286 // Allow 2*r as r+r. 15287 break; 15288 default: 15289 // No other scales are supported. 15290 return false; 15291 } 15292 15293 return true; 15294 } 15295 15296 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15297 SelectionDAG &DAG) const { 15298 MachineFunction &MF = DAG.getMachineFunction(); 15299 MachineFrameInfo &MFI = MF.getFrameInfo(); 15300 MFI.setReturnAddressIsTaken(true); 15301 15302 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15303 return SDValue(); 15304 15305 SDLoc dl(Op); 15306 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15307 15308 // Make sure the function does not optimize away the store of the RA to 15309 // the stack. 15310 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15311 FuncInfo->setLRStoreRequired(); 15312 bool isPPC64 = Subtarget.isPPC64(); 15313 auto PtrVT = getPointerTy(MF.getDataLayout()); 15314 15315 if (Depth > 0) { 15316 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15317 SDValue Offset = 15318 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15319 isPPC64 ? MVT::i64 : MVT::i32); 15320 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15321 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15322 MachinePointerInfo()); 15323 } 15324 15325 // Just load the return address off the stack. 15326 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15327 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15328 MachinePointerInfo()); 15329 } 15330 15331 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15332 SelectionDAG &DAG) const { 15333 SDLoc dl(Op); 15334 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15335 15336 MachineFunction &MF = DAG.getMachineFunction(); 15337 MachineFrameInfo &MFI = MF.getFrameInfo(); 15338 MFI.setFrameAddressIsTaken(true); 15339 15340 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15341 bool isPPC64 = PtrVT == MVT::i64; 15342 15343 // Naked functions never have a frame pointer, and so we use r1. For all 15344 // other functions, this decision must be delayed until during PEI. 15345 unsigned FrameReg; 15346 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15347 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15348 else 15349 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15350 15351 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15352 PtrVT); 15353 while (Depth--) 15354 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15355 FrameAddr, MachinePointerInfo()); 15356 return FrameAddr; 15357 } 15358 15359 // FIXME? Maybe this could be a TableGen attribute on some registers and 15360 // this table could be generated automatically from RegInfo. 15361 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15362 const MachineFunction &MF) const { 15363 bool isPPC64 = Subtarget.isPPC64(); 15364 15365 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15366 if (!is64Bit && VT != LLT::scalar(32)) 15367 report_fatal_error("Invalid register global variable type"); 15368 15369 Register Reg = StringSwitch<Register>(RegName) 15370 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15371 .Case("r2", isPPC64 ? Register() : PPC::R2) 15372 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15373 .Default(Register()); 15374 15375 if (Reg) 15376 return Reg; 15377 report_fatal_error("Invalid register name global variable"); 15378 } 15379 15380 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15381 // 32-bit SVR4 ABI access everything as got-indirect. 15382 if (Subtarget.is32BitELFABI()) 15383 return true; 15384 15385 // AIX accesses everything indirectly through the TOC, which is similar to 15386 // the GOT. 15387 if (Subtarget.isAIXABI()) 15388 return true; 15389 15390 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15391 // If it is small or large code model, module locals are accessed 15392 // indirectly by loading their address from .toc/.got. 15393 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15394 return true; 15395 15396 // JumpTable and BlockAddress are accessed as got-indirect. 15397 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15398 return true; 15399 15400 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15401 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15402 15403 return false; 15404 } 15405 15406 bool 15407 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15408 // The PowerPC target isn't yet aware of offsets. 15409 return false; 15410 } 15411 15412 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15413 const CallInst &I, 15414 MachineFunction &MF, 15415 unsigned Intrinsic) const { 15416 switch (Intrinsic) { 15417 case Intrinsic::ppc_qpx_qvlfd: 15418 case Intrinsic::ppc_qpx_qvlfs: 15419 case Intrinsic::ppc_qpx_qvlfcd: 15420 case Intrinsic::ppc_qpx_qvlfcs: 15421 case Intrinsic::ppc_qpx_qvlfiwa: 15422 case Intrinsic::ppc_qpx_qvlfiwz: 15423 case Intrinsic::ppc_altivec_lvx: 15424 case Intrinsic::ppc_altivec_lvxl: 15425 case Intrinsic::ppc_altivec_lvebx: 15426 case Intrinsic::ppc_altivec_lvehx: 15427 case Intrinsic::ppc_altivec_lvewx: 15428 case Intrinsic::ppc_vsx_lxvd2x: 15429 case Intrinsic::ppc_vsx_lxvw4x: { 15430 EVT VT; 15431 switch (Intrinsic) { 15432 case Intrinsic::ppc_altivec_lvebx: 15433 VT = MVT::i8; 15434 break; 15435 case Intrinsic::ppc_altivec_lvehx: 15436 VT = MVT::i16; 15437 break; 15438 case Intrinsic::ppc_altivec_lvewx: 15439 VT = MVT::i32; 15440 break; 15441 case Intrinsic::ppc_vsx_lxvd2x: 15442 VT = MVT::v2f64; 15443 break; 15444 case Intrinsic::ppc_qpx_qvlfd: 15445 VT = MVT::v4f64; 15446 break; 15447 case Intrinsic::ppc_qpx_qvlfs: 15448 VT = MVT::v4f32; 15449 break; 15450 case Intrinsic::ppc_qpx_qvlfcd: 15451 VT = MVT::v2f64; 15452 break; 15453 case Intrinsic::ppc_qpx_qvlfcs: 15454 VT = MVT::v2f32; 15455 break; 15456 default: 15457 VT = MVT::v4i32; 15458 break; 15459 } 15460 15461 Info.opc = ISD::INTRINSIC_W_CHAIN; 15462 Info.memVT = VT; 15463 Info.ptrVal = I.getArgOperand(0); 15464 Info.offset = -VT.getStoreSize()+1; 15465 Info.size = 2*VT.getStoreSize()-1; 15466 Info.align = Align(1); 15467 Info.flags = MachineMemOperand::MOLoad; 15468 return true; 15469 } 15470 case Intrinsic::ppc_qpx_qvlfda: 15471 case Intrinsic::ppc_qpx_qvlfsa: 15472 case Intrinsic::ppc_qpx_qvlfcda: 15473 case Intrinsic::ppc_qpx_qvlfcsa: 15474 case Intrinsic::ppc_qpx_qvlfiwaa: 15475 case Intrinsic::ppc_qpx_qvlfiwza: { 15476 EVT VT; 15477 switch (Intrinsic) { 15478 case Intrinsic::ppc_qpx_qvlfda: 15479 VT = MVT::v4f64; 15480 break; 15481 case Intrinsic::ppc_qpx_qvlfsa: 15482 VT = MVT::v4f32; 15483 break; 15484 case Intrinsic::ppc_qpx_qvlfcda: 15485 VT = MVT::v2f64; 15486 break; 15487 case Intrinsic::ppc_qpx_qvlfcsa: 15488 VT = MVT::v2f32; 15489 break; 15490 default: 15491 VT = MVT::v4i32; 15492 break; 15493 } 15494 15495 Info.opc = ISD::INTRINSIC_W_CHAIN; 15496 Info.memVT = VT; 15497 Info.ptrVal = I.getArgOperand(0); 15498 Info.offset = 0; 15499 Info.size = VT.getStoreSize(); 15500 Info.align = Align(1); 15501 Info.flags = MachineMemOperand::MOLoad; 15502 return true; 15503 } 15504 case Intrinsic::ppc_qpx_qvstfd: 15505 case Intrinsic::ppc_qpx_qvstfs: 15506 case Intrinsic::ppc_qpx_qvstfcd: 15507 case Intrinsic::ppc_qpx_qvstfcs: 15508 case Intrinsic::ppc_qpx_qvstfiw: 15509 case Intrinsic::ppc_altivec_stvx: 15510 case Intrinsic::ppc_altivec_stvxl: 15511 case Intrinsic::ppc_altivec_stvebx: 15512 case Intrinsic::ppc_altivec_stvehx: 15513 case Intrinsic::ppc_altivec_stvewx: 15514 case Intrinsic::ppc_vsx_stxvd2x: 15515 case Intrinsic::ppc_vsx_stxvw4x: { 15516 EVT VT; 15517 switch (Intrinsic) { 15518 case Intrinsic::ppc_altivec_stvebx: 15519 VT = MVT::i8; 15520 break; 15521 case Intrinsic::ppc_altivec_stvehx: 15522 VT = MVT::i16; 15523 break; 15524 case Intrinsic::ppc_altivec_stvewx: 15525 VT = MVT::i32; 15526 break; 15527 case Intrinsic::ppc_vsx_stxvd2x: 15528 VT = MVT::v2f64; 15529 break; 15530 case Intrinsic::ppc_qpx_qvstfd: 15531 VT = MVT::v4f64; 15532 break; 15533 case Intrinsic::ppc_qpx_qvstfs: 15534 VT = MVT::v4f32; 15535 break; 15536 case Intrinsic::ppc_qpx_qvstfcd: 15537 VT = MVT::v2f64; 15538 break; 15539 case Intrinsic::ppc_qpx_qvstfcs: 15540 VT = MVT::v2f32; 15541 break; 15542 default: 15543 VT = MVT::v4i32; 15544 break; 15545 } 15546 15547 Info.opc = ISD::INTRINSIC_VOID; 15548 Info.memVT = VT; 15549 Info.ptrVal = I.getArgOperand(1); 15550 Info.offset = -VT.getStoreSize()+1; 15551 Info.size = 2*VT.getStoreSize()-1; 15552 Info.align = Align(1); 15553 Info.flags = MachineMemOperand::MOStore; 15554 return true; 15555 } 15556 case Intrinsic::ppc_qpx_qvstfda: 15557 case Intrinsic::ppc_qpx_qvstfsa: 15558 case Intrinsic::ppc_qpx_qvstfcda: 15559 case Intrinsic::ppc_qpx_qvstfcsa: 15560 case Intrinsic::ppc_qpx_qvstfiwa: { 15561 EVT VT; 15562 switch (Intrinsic) { 15563 case Intrinsic::ppc_qpx_qvstfda: 15564 VT = MVT::v4f64; 15565 break; 15566 case Intrinsic::ppc_qpx_qvstfsa: 15567 VT = MVT::v4f32; 15568 break; 15569 case Intrinsic::ppc_qpx_qvstfcda: 15570 VT = MVT::v2f64; 15571 break; 15572 case Intrinsic::ppc_qpx_qvstfcsa: 15573 VT = MVT::v2f32; 15574 break; 15575 default: 15576 VT = MVT::v4i32; 15577 break; 15578 } 15579 15580 Info.opc = ISD::INTRINSIC_VOID; 15581 Info.memVT = VT; 15582 Info.ptrVal = I.getArgOperand(1); 15583 Info.offset = 0; 15584 Info.size = VT.getStoreSize(); 15585 Info.align = Align(1); 15586 Info.flags = MachineMemOperand::MOStore; 15587 return true; 15588 } 15589 default: 15590 break; 15591 } 15592 15593 return false; 15594 } 15595 15596 /// It returns EVT::Other if the type should be determined using generic 15597 /// target-independent logic. 15598 EVT PPCTargetLowering::getOptimalMemOpType( 15599 const MemOp &Op, const AttributeList &FuncAttributes) const { 15600 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15601 // When expanding a memset, require at least two QPX instructions to cover 15602 // the cost of loading the value to be stored from the constant pool. 15603 if (Subtarget.hasQPX() && Op.size() >= 32 && 15604 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15605 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15606 return MVT::v4f64; 15607 } 15608 15609 // We should use Altivec/VSX loads and stores when available. For unaligned 15610 // addresses, unaligned VSX loads are only fast starting with the P8. 15611 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15612 (Op.isAligned(Align(16)) || 15613 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15614 return MVT::v4i32; 15615 } 15616 15617 if (Subtarget.isPPC64()) { 15618 return MVT::i64; 15619 } 15620 15621 return MVT::i32; 15622 } 15623 15624 /// Returns true if it is beneficial to convert a load of a constant 15625 /// to just the constant itself. 15626 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15627 Type *Ty) const { 15628 assert(Ty->isIntegerTy()); 15629 15630 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15631 return !(BitSize == 0 || BitSize > 64); 15632 } 15633 15634 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15635 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15636 return false; 15637 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15638 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15639 return NumBits1 == 64 && NumBits2 == 32; 15640 } 15641 15642 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15643 if (!VT1.isInteger() || !VT2.isInteger()) 15644 return false; 15645 unsigned NumBits1 = VT1.getSizeInBits(); 15646 unsigned NumBits2 = VT2.getSizeInBits(); 15647 return NumBits1 == 64 && NumBits2 == 32; 15648 } 15649 15650 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15651 // Generally speaking, zexts are not free, but they are free when they can be 15652 // folded with other operations. 15653 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15654 EVT MemVT = LD->getMemoryVT(); 15655 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15656 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15657 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15658 LD->getExtensionType() == ISD::ZEXTLOAD)) 15659 return true; 15660 } 15661 15662 // FIXME: Add other cases... 15663 // - 32-bit shifts with a zext to i64 15664 // - zext after ctlz, bswap, etc. 15665 // - zext after and by a constant mask 15666 15667 return TargetLowering::isZExtFree(Val, VT2); 15668 } 15669 15670 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15671 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15672 "invalid fpext types"); 15673 // Extending to float128 is not free. 15674 if (DestVT == MVT::f128) 15675 return false; 15676 return true; 15677 } 15678 15679 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15680 return isInt<16>(Imm) || isUInt<16>(Imm); 15681 } 15682 15683 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15684 return isInt<16>(Imm) || isUInt<16>(Imm); 15685 } 15686 15687 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15688 unsigned, 15689 unsigned, 15690 MachineMemOperand::Flags, 15691 bool *Fast) const { 15692 if (DisablePPCUnaligned) 15693 return false; 15694 15695 // PowerPC supports unaligned memory access for simple non-vector types. 15696 // Although accessing unaligned addresses is not as efficient as accessing 15697 // aligned addresses, it is generally more efficient than manual expansion, 15698 // and generally only traps for software emulation when crossing page 15699 // boundaries. 15700 15701 if (!VT.isSimple()) 15702 return false; 15703 15704 if (VT.isFloatingPoint() && !VT.isVector() && 15705 !Subtarget.allowsUnalignedFPAccess()) 15706 return false; 15707 15708 if (VT.getSimpleVT().isVector()) { 15709 if (Subtarget.hasVSX()) { 15710 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15711 VT != MVT::v4f32 && VT != MVT::v4i32) 15712 return false; 15713 } else { 15714 return false; 15715 } 15716 } 15717 15718 if (VT == MVT::ppcf128) 15719 return false; 15720 15721 if (Fast) 15722 *Fast = true; 15723 15724 return true; 15725 } 15726 15727 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15728 EVT VT) const { 15729 return isFMAFasterThanFMulAndFAdd( 15730 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15731 } 15732 15733 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15734 Type *Ty) const { 15735 switch (Ty->getScalarType()->getTypeID()) { 15736 case Type::FloatTyID: 15737 case Type::DoubleTyID: 15738 return true; 15739 case Type::FP128TyID: 15740 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15741 default: 15742 return false; 15743 } 15744 } 15745 15746 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15747 // FIXME: add more patterns which are profitable to hoist. 15748 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15749 if (I->getOpcode() != Instruction::FMul) 15750 return true; 15751 15752 if (!I->hasOneUse()) 15753 return true; 15754 15755 Instruction *User = I->user_back(); 15756 assert(User && "A single use instruction with no uses."); 15757 15758 if (User->getOpcode() != Instruction::FSub && 15759 User->getOpcode() != Instruction::FAdd) 15760 return true; 15761 15762 const TargetOptions &Options = getTargetMachine().Options; 15763 const Function *F = I->getFunction(); 15764 const DataLayout &DL = F->getParent()->getDataLayout(); 15765 Type *Ty = User->getOperand(0)->getType(); 15766 15767 return !( 15768 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15769 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15770 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15771 } 15772 15773 const MCPhysReg * 15774 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15775 // LR is a callee-save register, but we must treat it as clobbered by any call 15776 // site. Hence we include LR in the scratch registers, which are in turn added 15777 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15778 // to CTR, which is used by any indirect call. 15779 static const MCPhysReg ScratchRegs[] = { 15780 PPC::X12, PPC::LR8, PPC::CTR8, 0 15781 }; 15782 15783 return ScratchRegs; 15784 } 15785 15786 Register PPCTargetLowering::getExceptionPointerRegister( 15787 const Constant *PersonalityFn) const { 15788 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15789 } 15790 15791 Register PPCTargetLowering::getExceptionSelectorRegister( 15792 const Constant *PersonalityFn) const { 15793 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15794 } 15795 15796 bool 15797 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15798 EVT VT , unsigned DefinedValues) const { 15799 if (VT == MVT::v2i64) 15800 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15801 15802 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15803 return true; 15804 15805 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15806 } 15807 15808 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15809 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15810 return TargetLowering::getSchedulingPreference(N); 15811 15812 return Sched::ILP; 15813 } 15814 15815 // Create a fast isel object. 15816 FastISel * 15817 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15818 const TargetLibraryInfo *LibInfo) const { 15819 return PPC::createFastISel(FuncInfo, LibInfo); 15820 } 15821 15822 // 'Inverted' means the FMA opcode after negating one multiplicand. 15823 // For example, (fma -a b c) = (fnmsub a b c) 15824 static unsigned invertFMAOpcode(unsigned Opc) { 15825 switch (Opc) { 15826 default: 15827 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15828 case ISD::FMA: 15829 return PPCISD::FNMSUB; 15830 case PPCISD::FNMSUB: 15831 return ISD::FMA; 15832 } 15833 } 15834 15835 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15836 bool LegalOps, bool OptForSize, 15837 NegatibleCost &Cost, 15838 unsigned Depth) const { 15839 if (Depth > SelectionDAG::MaxRecursionDepth) 15840 return SDValue(); 15841 15842 unsigned Opc = Op.getOpcode(); 15843 EVT VT = Op.getValueType(); 15844 SDNodeFlags Flags = Op.getNode()->getFlags(); 15845 15846 switch (Opc) { 15847 case PPCISD::FNMSUB: 15848 // TODO: QPX subtarget is deprecated. No transformation here. 15849 if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX()) 15850 break; 15851 15852 const TargetOptions &Options = getTargetMachine().Options; 15853 SDValue N0 = Op.getOperand(0); 15854 SDValue N1 = Op.getOperand(1); 15855 SDValue N2 = Op.getOperand(2); 15856 SDLoc Loc(Op); 15857 15858 NegatibleCost N2Cost = NegatibleCost::Expensive; 15859 SDValue NegN2 = 15860 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15861 15862 if (!NegN2) 15863 return SDValue(); 15864 15865 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15866 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15867 // These transformations may change sign of zeroes. For example, 15868 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15869 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15870 // Try and choose the cheaper one to negate. 15871 NegatibleCost N0Cost = NegatibleCost::Expensive; 15872 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15873 N0Cost, Depth + 1); 15874 15875 NegatibleCost N1Cost = NegatibleCost::Expensive; 15876 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15877 N1Cost, Depth + 1); 15878 15879 if (NegN0 && N0Cost <= N1Cost) { 15880 Cost = std::min(N0Cost, N2Cost); 15881 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15882 } else if (NegN1) { 15883 Cost = std::min(N1Cost, N2Cost); 15884 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15885 } 15886 } 15887 15888 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15889 if (isOperationLegal(ISD::FMA, VT)) { 15890 Cost = N2Cost; 15891 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15892 } 15893 15894 break; 15895 } 15896 15897 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15898 Cost, Depth); 15899 } 15900 15901 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15902 bool PPCTargetLowering::useLoadStackGuardNode() const { 15903 if (!Subtarget.isTargetLinux()) 15904 return TargetLowering::useLoadStackGuardNode(); 15905 return true; 15906 } 15907 15908 // Override to disable global variable loading on Linux. 15909 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15910 if (!Subtarget.isTargetLinux()) 15911 return TargetLowering::insertSSPDeclarations(M); 15912 } 15913 15914 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15915 bool ForCodeSize) const { 15916 if (!VT.isSimple() || !Subtarget.hasVSX()) 15917 return false; 15918 15919 switch(VT.getSimpleVT().SimpleTy) { 15920 default: 15921 // For FP types that are currently not supported by PPC backend, return 15922 // false. Examples: f16, f80. 15923 return false; 15924 case MVT::f32: 15925 case MVT::f64: 15926 case MVT::ppcf128: 15927 return Imm.isPosZero(); 15928 } 15929 } 15930 15931 // For vector shift operation op, fold 15932 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15933 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15934 SelectionDAG &DAG) { 15935 SDValue N0 = N->getOperand(0); 15936 SDValue N1 = N->getOperand(1); 15937 EVT VT = N0.getValueType(); 15938 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15939 unsigned Opcode = N->getOpcode(); 15940 unsigned TargetOpcode; 15941 15942 switch (Opcode) { 15943 default: 15944 llvm_unreachable("Unexpected shift operation"); 15945 case ISD::SHL: 15946 TargetOpcode = PPCISD::SHL; 15947 break; 15948 case ISD::SRL: 15949 TargetOpcode = PPCISD::SRL; 15950 break; 15951 case ISD::SRA: 15952 TargetOpcode = PPCISD::SRA; 15953 break; 15954 } 15955 15956 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15957 N1->getOpcode() == ISD::AND) 15958 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15959 if (Mask->getZExtValue() == OpSizeInBits - 1) 15960 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15961 15962 return SDValue(); 15963 } 15964 15965 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15966 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15967 return Value; 15968 15969 SDValue N0 = N->getOperand(0); 15970 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15971 if (!Subtarget.isISA3_0() || 15972 N0.getOpcode() != ISD::SIGN_EXTEND || 15973 N0.getOperand(0).getValueType() != MVT::i32 || 15974 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15975 return SDValue(); 15976 15977 // We can't save an operation here if the value is already extended, and 15978 // the existing shift is easier to combine. 15979 SDValue ExtsSrc = N0.getOperand(0); 15980 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15981 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15982 return SDValue(); 15983 15984 SDLoc DL(N0); 15985 SDValue ShiftBy = SDValue(CN1, 0); 15986 // We want the shift amount to be i32 on the extswli, but the shift could 15987 // have an i64. 15988 if (ShiftBy.getValueType() == MVT::i64) 15989 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15990 15991 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15992 ShiftBy); 15993 } 15994 15995 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15996 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15997 return Value; 15998 15999 return SDValue(); 16000 } 16001 16002 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16003 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16004 return Value; 16005 16006 return SDValue(); 16007 } 16008 16009 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16010 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16011 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16012 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16013 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16014 const PPCSubtarget &Subtarget) { 16015 if (!Subtarget.isPPC64()) 16016 return SDValue(); 16017 16018 SDValue LHS = N->getOperand(0); 16019 SDValue RHS = N->getOperand(1); 16020 16021 auto isZextOfCompareWithConstant = [](SDValue Op) { 16022 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16023 Op.getValueType() != MVT::i64) 16024 return false; 16025 16026 SDValue Cmp = Op.getOperand(0); 16027 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16028 Cmp.getOperand(0).getValueType() != MVT::i64) 16029 return false; 16030 16031 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16032 int64_t NegConstant = 0 - Constant->getSExtValue(); 16033 // Due to the limitations of the addi instruction, 16034 // -C is required to be [-32768, 32767]. 16035 return isInt<16>(NegConstant); 16036 } 16037 16038 return false; 16039 }; 16040 16041 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16042 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16043 16044 // If there is a pattern, canonicalize a zext operand to the RHS. 16045 if (LHSHasPattern && !RHSHasPattern) 16046 std::swap(LHS, RHS); 16047 else if (!LHSHasPattern && !RHSHasPattern) 16048 return SDValue(); 16049 16050 SDLoc DL(N); 16051 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16052 SDValue Cmp = RHS.getOperand(0); 16053 SDValue Z = Cmp.getOperand(0); 16054 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16055 16056 assert(Constant && "Constant Should not be a null pointer."); 16057 int64_t NegConstant = 0 - Constant->getSExtValue(); 16058 16059 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16060 default: break; 16061 case ISD::SETNE: { 16062 // when C == 0 16063 // --> addze X, (addic Z, -1).carry 16064 // / 16065 // add X, (zext(setne Z, C))-- 16066 // \ when -32768 <= -C <= 32767 && C != 0 16067 // --> addze X, (addic (addi Z, -C), -1).carry 16068 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16069 DAG.getConstant(NegConstant, DL, MVT::i64)); 16070 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16071 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16072 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16073 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16074 SDValue(Addc.getNode(), 1)); 16075 } 16076 case ISD::SETEQ: { 16077 // when C == 0 16078 // --> addze X, (subfic Z, 0).carry 16079 // / 16080 // add X, (zext(sete Z, C))-- 16081 // \ when -32768 <= -C <= 32767 && C != 0 16082 // --> addze X, (subfic (addi Z, -C), 0).carry 16083 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16084 DAG.getConstant(NegConstant, DL, MVT::i64)); 16085 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16086 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16087 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16088 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16089 SDValue(Subc.getNode(), 1)); 16090 } 16091 } 16092 16093 return SDValue(); 16094 } 16095 16096 // Transform 16097 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16098 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16099 // In this case both C1 and C2 must be known constants. 16100 // C1+C2 must fit into a 34 bit signed integer. 16101 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16102 const PPCSubtarget &Subtarget) { 16103 if (!Subtarget.isUsingPCRelativeCalls()) 16104 return SDValue(); 16105 16106 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16107 // If we find that node try to cast the Global Address and the Constant. 16108 SDValue LHS = N->getOperand(0); 16109 SDValue RHS = N->getOperand(1); 16110 16111 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16112 std::swap(LHS, RHS); 16113 16114 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16115 return SDValue(); 16116 16117 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16118 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16119 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16120 16121 // Check that both casts succeeded. 16122 if (!GSDN || !ConstNode) 16123 return SDValue(); 16124 16125 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16126 SDLoc DL(GSDN); 16127 16128 // The signed int offset needs to fit in 34 bits. 16129 if (!isInt<34>(NewOffset)) 16130 return SDValue(); 16131 16132 // The new global address is a copy of the old global address except 16133 // that it has the updated Offset. 16134 SDValue GA = 16135 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16136 NewOffset, GSDN->getTargetFlags()); 16137 SDValue MatPCRel = 16138 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16139 return MatPCRel; 16140 } 16141 16142 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16143 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16144 return Value; 16145 16146 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16147 return Value; 16148 16149 return SDValue(); 16150 } 16151 16152 // Detect TRUNCATE operations on bitcasts of float128 values. 16153 // What we are looking for here is the situtation where we extract a subset 16154 // of bits from a 128 bit float. 16155 // This can be of two forms: 16156 // 1) BITCAST of f128 feeding TRUNCATE 16157 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16158 // The reason this is required is because we do not have a legal i128 type 16159 // and so we want to prevent having to store the f128 and then reload part 16160 // of it. 16161 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16162 DAGCombinerInfo &DCI) const { 16163 // If we are using CRBits then try that first. 16164 if (Subtarget.useCRBits()) { 16165 // Check if CRBits did anything and return that if it did. 16166 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16167 return CRTruncValue; 16168 } 16169 16170 SDLoc dl(N); 16171 SDValue Op0 = N->getOperand(0); 16172 16173 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16174 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16175 EVT VT = N->getValueType(0); 16176 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16177 return SDValue(); 16178 SDValue Sub = Op0.getOperand(0); 16179 if (Sub.getOpcode() == ISD::SUB) { 16180 SDValue SubOp0 = Sub.getOperand(0); 16181 SDValue SubOp1 = Sub.getOperand(1); 16182 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16183 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16184 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16185 SubOp1.getOperand(0), 16186 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16187 } 16188 } 16189 } 16190 16191 // Looking for a truncate of i128 to i64. 16192 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16193 return SDValue(); 16194 16195 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16196 16197 // SRL feeding TRUNCATE. 16198 if (Op0.getOpcode() == ISD::SRL) { 16199 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16200 // The right shift has to be by 64 bits. 16201 if (!ConstNode || ConstNode->getZExtValue() != 64) 16202 return SDValue(); 16203 16204 // Switch the element number to extract. 16205 EltToExtract = EltToExtract ? 0 : 1; 16206 // Update Op0 past the SRL. 16207 Op0 = Op0.getOperand(0); 16208 } 16209 16210 // BITCAST feeding a TRUNCATE possibly via SRL. 16211 if (Op0.getOpcode() == ISD::BITCAST && 16212 Op0.getValueType() == MVT::i128 && 16213 Op0.getOperand(0).getValueType() == MVT::f128) { 16214 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16215 return DCI.DAG.getNode( 16216 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16217 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16218 } 16219 return SDValue(); 16220 } 16221 16222 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16223 SelectionDAG &DAG = DCI.DAG; 16224 16225 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16226 if (!ConstOpOrElement) 16227 return SDValue(); 16228 16229 // An imul is usually smaller than the alternative sequence for legal type. 16230 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16231 isOperationLegal(ISD::MUL, N->getValueType(0))) 16232 return SDValue(); 16233 16234 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16235 switch (this->Subtarget.getCPUDirective()) { 16236 default: 16237 // TODO: enhance the condition for subtarget before pwr8 16238 return false; 16239 case PPC::DIR_PWR8: 16240 // type mul add shl 16241 // scalar 4 1 1 16242 // vector 7 2 2 16243 return true; 16244 case PPC::DIR_PWR9: 16245 case PPC::DIR_PWR10: 16246 case PPC::DIR_PWR_FUTURE: 16247 // type mul add shl 16248 // scalar 5 2 2 16249 // vector 7 2 2 16250 16251 // The cycle RATIO of related operations are showed as a table above. 16252 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16253 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16254 // are 4, it is always profitable; but for 3 instrs patterns 16255 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16256 // So we should only do it for vector type. 16257 return IsAddOne && IsNeg ? VT.isVector() : true; 16258 } 16259 }; 16260 16261 EVT VT = N->getValueType(0); 16262 SDLoc DL(N); 16263 16264 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16265 bool IsNeg = MulAmt.isNegative(); 16266 APInt MulAmtAbs = MulAmt.abs(); 16267 16268 if ((MulAmtAbs - 1).isPowerOf2()) { 16269 // (mul x, 2^N + 1) => (add (shl x, N), x) 16270 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16271 16272 if (!IsProfitable(IsNeg, true, VT)) 16273 return SDValue(); 16274 16275 SDValue Op0 = N->getOperand(0); 16276 SDValue Op1 = 16277 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16278 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16279 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16280 16281 if (!IsNeg) 16282 return Res; 16283 16284 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16285 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16286 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16287 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16288 16289 if (!IsProfitable(IsNeg, false, VT)) 16290 return SDValue(); 16291 16292 SDValue Op0 = N->getOperand(0); 16293 SDValue Op1 = 16294 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16295 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16296 16297 if (!IsNeg) 16298 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16299 else 16300 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16301 16302 } else { 16303 return SDValue(); 16304 } 16305 } 16306 16307 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16308 // in combiner since we need to check SD flags and other subtarget features. 16309 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16310 DAGCombinerInfo &DCI) const { 16311 SDValue N0 = N->getOperand(0); 16312 SDValue N1 = N->getOperand(1); 16313 SDValue N2 = N->getOperand(2); 16314 SDNodeFlags Flags = N->getFlags(); 16315 EVT VT = N->getValueType(0); 16316 SelectionDAG &DAG = DCI.DAG; 16317 const TargetOptions &Options = getTargetMachine().Options; 16318 unsigned Opc = N->getOpcode(); 16319 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16320 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16321 SDLoc Loc(N); 16322 16323 // TODO: QPX subtarget is deprecated. No transformation here. 16324 if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT)) 16325 return SDValue(); 16326 16327 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16328 // since (fnmsub a b c)=-0 while c-ab=+0. 16329 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16330 return SDValue(); 16331 16332 // (fma (fneg a) b c) => (fnmsub a b c) 16333 // (fnmsub (fneg a) b c) => (fma a b c) 16334 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16335 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16336 16337 // (fma a (fneg b) c) => (fnmsub a b c) 16338 // (fnmsub a (fneg b) c) => (fma a b c) 16339 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16340 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16341 16342 return SDValue(); 16343 } 16344 16345 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16346 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16347 if (!Subtarget.is64BitELFABI()) 16348 return false; 16349 16350 // If not a tail call then no need to proceed. 16351 if (!CI->isTailCall()) 16352 return false; 16353 16354 // If sibling calls have been disabled and tail-calls aren't guaranteed 16355 // there is no reason to duplicate. 16356 auto &TM = getTargetMachine(); 16357 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16358 return false; 16359 16360 // Can't tail call a function called indirectly, or if it has variadic args. 16361 const Function *Callee = CI->getCalledFunction(); 16362 if (!Callee || Callee->isVarArg()) 16363 return false; 16364 16365 // Make sure the callee and caller calling conventions are eligible for tco. 16366 const Function *Caller = CI->getParent()->getParent(); 16367 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16368 CI->getCallingConv())) 16369 return false; 16370 16371 // If the function is local then we have a good chance at tail-calling it 16372 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16373 } 16374 16375 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16376 if (!Subtarget.hasVSX()) 16377 return false; 16378 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16379 return true; 16380 return VT == MVT::f32 || VT == MVT::f64 || 16381 VT == MVT::v4f32 || VT == MVT::v2f64; 16382 } 16383 16384 bool PPCTargetLowering:: 16385 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16386 const Value *Mask = AndI.getOperand(1); 16387 // If the mask is suitable for andi. or andis. we should sink the and. 16388 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16389 // Can't handle constants wider than 64-bits. 16390 if (CI->getBitWidth() > 64) 16391 return false; 16392 int64_t ConstVal = CI->getZExtValue(); 16393 return isUInt<16>(ConstVal) || 16394 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16395 } 16396 16397 // For non-constant masks, we can always use the record-form and. 16398 return true; 16399 } 16400 16401 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16402 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16403 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16404 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16405 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16406 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16407 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16408 assert(Subtarget.hasP9Altivec() && 16409 "Only combine this when P9 altivec supported!"); 16410 EVT VT = N->getValueType(0); 16411 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16412 return SDValue(); 16413 16414 SelectionDAG &DAG = DCI.DAG; 16415 SDLoc dl(N); 16416 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16417 // Even for signed integers, if it's known to be positive (as signed 16418 // integer) due to zero-extended inputs. 16419 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16420 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16421 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16422 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16423 (SubOpcd1 == ISD::ZERO_EXTEND || 16424 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16425 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16426 N->getOperand(0)->getOperand(0), 16427 N->getOperand(0)->getOperand(1), 16428 DAG.getTargetConstant(0, dl, MVT::i32)); 16429 } 16430 16431 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16432 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16433 N->getOperand(0).hasOneUse()) { 16434 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16435 N->getOperand(0)->getOperand(0), 16436 N->getOperand(0)->getOperand(1), 16437 DAG.getTargetConstant(1, dl, MVT::i32)); 16438 } 16439 } 16440 16441 return SDValue(); 16442 } 16443 16444 // For type v4i32/v8ii16/v16i8, transform 16445 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16446 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16447 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16448 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16449 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16450 DAGCombinerInfo &DCI) const { 16451 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16452 assert(Subtarget.hasP9Altivec() && 16453 "Only combine this when P9 altivec supported!"); 16454 16455 SelectionDAG &DAG = DCI.DAG; 16456 SDLoc dl(N); 16457 SDValue Cond = N->getOperand(0); 16458 SDValue TrueOpnd = N->getOperand(1); 16459 SDValue FalseOpnd = N->getOperand(2); 16460 EVT VT = N->getOperand(1).getValueType(); 16461 16462 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16463 FalseOpnd.getOpcode() != ISD::SUB) 16464 return SDValue(); 16465 16466 // ABSD only available for type v4i32/v8i16/v16i8 16467 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16468 return SDValue(); 16469 16470 // At least to save one more dependent computation 16471 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16472 return SDValue(); 16473 16474 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16475 16476 // Can only handle unsigned comparison here 16477 switch (CC) { 16478 default: 16479 return SDValue(); 16480 case ISD::SETUGT: 16481 case ISD::SETUGE: 16482 break; 16483 case ISD::SETULT: 16484 case ISD::SETULE: 16485 std::swap(TrueOpnd, FalseOpnd); 16486 break; 16487 } 16488 16489 SDValue CmpOpnd1 = Cond.getOperand(0); 16490 SDValue CmpOpnd2 = Cond.getOperand(1); 16491 16492 // SETCC CmpOpnd1 CmpOpnd2 cond 16493 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16494 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16495 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16496 TrueOpnd.getOperand(1) == CmpOpnd2 && 16497 FalseOpnd.getOperand(0) == CmpOpnd2 && 16498 FalseOpnd.getOperand(1) == CmpOpnd1) { 16499 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16500 CmpOpnd1, CmpOpnd2, 16501 DAG.getTargetConstant(0, dl, MVT::i32)); 16502 } 16503 16504 return SDValue(); 16505 } 16506