1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/IntrinsicsPowerPC.h" 71 #include "llvm/IR/Module.h" 72 #include "llvm/IR/Type.h" 73 #include "llvm/IR/Use.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/MC/MCContext.h" 76 #include "llvm/MC/MCExpr.h" 77 #include "llvm/MC/MCRegisterInfo.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 122 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 123 124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 125 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 126 127 STATISTIC(NumTailCalls, "Number of tail calls"); 128 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 141 // arguments are at least 4/8 bytes aligned. 142 bool isPPC64 = Subtarget.isPPC64(); 143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 144 145 // Set up the register classes. 146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 147 if (!useSoftFloat()) { 148 if (hasSPE()) { 149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 151 } else { 152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 154 } 155 } 156 157 // Match BITREVERSE to customized fast code sequence in the td file. 158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 160 161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 163 164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 165 for (MVT VT : MVT::integer_valuetypes()) { 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 168 } 169 170 if (Subtarget.isISA3_0()) { 171 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 172 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 174 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 175 } else { 176 // No extending loads from f16 or HW conversions back and forth. 177 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 178 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 179 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 180 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 181 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 182 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 183 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 184 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 185 } 186 187 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 188 189 // PowerPC has pre-inc load and store's. 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 200 if (!Subtarget.hasSPE()) { 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 202 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 205 } 206 207 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 208 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 209 for (MVT VT : ScalarIntVTs) { 210 setOperationAction(ISD::ADDC, VT, Legal); 211 setOperationAction(ISD::ADDE, VT, Legal); 212 setOperationAction(ISD::SUBC, VT, Legal); 213 setOperationAction(ISD::SUBE, VT, Legal); 214 } 215 216 if (Subtarget.useCRBits()) { 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 218 219 if (isPPC64 || Subtarget.hasFPCVT()) { 220 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 221 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 222 isPPC64 ? MVT::i64 : MVT::i32); 223 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 224 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 225 isPPC64 ? MVT::i64 : MVT::i32); 226 } else { 227 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 228 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 229 } 230 231 // PowerPC does not support direct load/store of condition registers. 232 setOperationAction(ISD::LOAD, MVT::i1, Custom); 233 setOperationAction(ISD::STORE, MVT::i1, Custom); 234 235 // FIXME: Remove this once the ANDI glue bug is fixed: 236 if (ANDIGlueBug) 237 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 238 239 for (MVT VT : MVT::integer_valuetypes()) { 240 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 241 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 242 setTruncStoreAction(VT, MVT::i1, Expand); 243 } 244 245 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 246 } 247 248 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 249 // PPC (the libcall is not available). 250 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 251 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 252 253 // We do not currently implement these libm ops for PowerPC. 254 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 259 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 260 261 // PowerPC has no SREM/UREM instructions unless we are on P9 262 // On P9 we may use a hardware instruction to compute the remainder. 263 // The instructions are not legalized directly because in the cases where the 264 // result of both the remainder and the division is required it is more 265 // efficient to compute the remainder from the result of the division rather 266 // than use the remainder instruction. 267 if (Subtarget.isISA3_0()) { 268 setOperationAction(ISD::SREM, MVT::i32, Custom); 269 setOperationAction(ISD::UREM, MVT::i32, Custom); 270 setOperationAction(ISD::SREM, MVT::i64, Custom); 271 setOperationAction(ISD::UREM, MVT::i64, Custom); 272 } else { 273 setOperationAction(ISD::SREM, MVT::i32, Expand); 274 setOperationAction(ISD::UREM, MVT::i32, Expand); 275 setOperationAction(ISD::SREM, MVT::i64, Expand); 276 setOperationAction(ISD::UREM, MVT::i64, Expand); 277 } 278 279 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 280 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 282 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 284 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 286 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 287 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 288 289 // Handle constrained floating-point operations of scalar. 290 // TODO: Handle SPE specific operation. 291 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 295 296 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 300 301 // We don't support sin/cos/sqrt/fmod/pow 302 setOperationAction(ISD::FSIN , MVT::f64, Expand); 303 setOperationAction(ISD::FCOS , MVT::f64, Expand); 304 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 305 setOperationAction(ISD::FREM , MVT::f64, Expand); 306 setOperationAction(ISD::FPOW , MVT::f64, Expand); 307 setOperationAction(ISD::FSIN , MVT::f32, Expand); 308 setOperationAction(ISD::FCOS , MVT::f32, Expand); 309 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 310 setOperationAction(ISD::FREM , MVT::f32, Expand); 311 setOperationAction(ISD::FPOW , MVT::f32, Expand); 312 if (Subtarget.hasSPE()) { 313 setOperationAction(ISD::FMA , MVT::f64, Expand); 314 setOperationAction(ISD::FMA , MVT::f32, Expand); 315 } else { 316 setOperationAction(ISD::FMA , MVT::f64, Legal); 317 setOperationAction(ISD::FMA , MVT::f32, Legal); 318 } 319 320 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 321 322 // If we're enabling GP optimizations, use hardware square root 323 if (!Subtarget.hasFSQRT() && 324 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 325 Subtarget.hasFRE())) 326 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 327 328 if (!Subtarget.hasFSQRT() && 329 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 330 Subtarget.hasFRES())) 331 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 332 333 if (Subtarget.hasFCPSGN()) { 334 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 335 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 336 } else { 337 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 338 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 339 } 340 341 if (Subtarget.hasFPRND()) { 342 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 343 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 344 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 345 setOperationAction(ISD::FROUND, MVT::f64, Legal); 346 347 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 348 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 349 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 350 setOperationAction(ISD::FROUND, MVT::f32, Legal); 351 } 352 353 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 354 // to speed up scalar BSWAP64. 355 // CTPOP or CTTZ were introduced in P8/P9 respectively 356 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 357 if (Subtarget.hasP9Vector()) 358 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 359 else 360 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 361 if (Subtarget.isISA3_0()) { 362 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 363 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 364 } else { 365 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 366 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 367 } 368 369 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 370 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 371 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 372 } else { 373 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 374 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 375 } 376 377 // PowerPC does not have ROTR 378 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 379 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 380 381 if (!Subtarget.useCRBits()) { 382 // PowerPC does not have Select 383 setOperationAction(ISD::SELECT, MVT::i32, Expand); 384 setOperationAction(ISD::SELECT, MVT::i64, Expand); 385 setOperationAction(ISD::SELECT, MVT::f32, Expand); 386 setOperationAction(ISD::SELECT, MVT::f64, Expand); 387 } 388 389 // PowerPC wants to turn select_cc of FP into fsel when possible. 390 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 391 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 392 393 // PowerPC wants to optimize integer setcc a bit 394 if (!Subtarget.useCRBits()) 395 setOperationAction(ISD::SETCC, MVT::i32, Custom); 396 397 // PowerPC does not have BRCOND which requires SetCC 398 if (!Subtarget.useCRBits()) 399 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 400 401 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 402 403 if (Subtarget.hasSPE()) { 404 // SPE has built-in conversions 405 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 406 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 408 } else { 409 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 410 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 411 412 // PowerPC does not have [U|S]INT_TO_FP 413 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 414 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 415 } 416 417 if (Subtarget.hasDirectMove() && isPPC64) { 418 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 419 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 420 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 421 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 422 if (TM.Options.UnsafeFPMath) { 423 setOperationAction(ISD::LRINT, MVT::f64, Legal); 424 setOperationAction(ISD::LRINT, MVT::f32, Legal); 425 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 426 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 427 setOperationAction(ISD::LROUND, MVT::f64, Legal); 428 setOperationAction(ISD::LROUND, MVT::f32, Legal); 429 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 430 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 431 } 432 } else { 433 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 434 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 435 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 436 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 437 } 438 439 // We cannot sextinreg(i1). Expand to shifts. 440 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 441 442 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 443 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 444 // support continuation, user-level threading, and etc.. As a result, no 445 // other SjLj exception interfaces are implemented and please don't build 446 // your own exception handling based on them. 447 // LLVM/Clang supports zero-cost DWARF exception handling. 448 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 449 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 450 451 // We want to legalize GlobalAddress and ConstantPool nodes into the 452 // appropriate instructions to materialize the address. 453 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 454 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 455 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 456 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 457 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 458 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 459 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 460 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 461 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 462 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 463 464 // TRAP is legal. 465 setOperationAction(ISD::TRAP, MVT::Other, Legal); 466 467 // TRAMPOLINE is custom lowered. 468 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 469 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 470 471 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 472 setOperationAction(ISD::VASTART , MVT::Other, Custom); 473 474 if (Subtarget.is64BitELFABI()) { 475 // VAARG always uses double-word chunks, so promote anything smaller. 476 setOperationAction(ISD::VAARG, MVT::i1, Promote); 477 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 478 setOperationAction(ISD::VAARG, MVT::i8, Promote); 479 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 480 setOperationAction(ISD::VAARG, MVT::i16, Promote); 481 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 482 setOperationAction(ISD::VAARG, MVT::i32, Promote); 483 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 484 setOperationAction(ISD::VAARG, MVT::Other, Expand); 485 } else if (Subtarget.is32BitELFABI()) { 486 // VAARG is custom lowered with the 32-bit SVR4 ABI. 487 setOperationAction(ISD::VAARG, MVT::Other, Custom); 488 setOperationAction(ISD::VAARG, MVT::i64, Custom); 489 } else 490 setOperationAction(ISD::VAARG, MVT::Other, Expand); 491 492 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 493 if (Subtarget.is32BitELFABI()) 494 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 495 else 496 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 497 498 // Use the default implementation. 499 setOperationAction(ISD::VAEND , MVT::Other, Expand); 500 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 501 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 502 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 503 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 504 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 505 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 506 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 507 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 508 509 // We want to custom lower some of our intrinsics. 510 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 511 512 // To handle counter-based loop conditions. 513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 514 515 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 516 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 517 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 518 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 519 520 // Comparisons that require checking two conditions. 521 if (Subtarget.hasSPE()) { 522 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 523 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 524 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 525 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 526 } 527 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 528 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 529 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 530 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 531 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 532 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 533 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 534 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 535 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 536 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 537 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 538 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 539 540 if (Subtarget.has64BitSupport()) { 541 // They also have instructions for converting between i64 and fp. 542 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 543 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 544 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 545 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 546 // This is just the low 32 bits of a (signed) fp->i64 conversion. 547 // We cannot do this with Promote because i64 is not a legal type. 548 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 549 550 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 551 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 552 } else { 553 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 554 if (Subtarget.hasSPE()) 555 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 556 else 557 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 558 } 559 560 // With the instructions enabled under FPCVT, we can do everything. 561 if (Subtarget.hasFPCVT()) { 562 if (Subtarget.has64BitSupport()) { 563 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 565 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 566 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 567 } 568 569 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 570 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 571 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 572 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 573 } 574 575 if (Subtarget.use64BitRegs()) { 576 // 64-bit PowerPC implementations can support i64 types directly 577 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 578 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 579 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 580 // 64-bit PowerPC wants to expand i128 shifts itself. 581 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 582 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 583 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 584 } else { 585 // 32-bit PowerPC wants to expand i64 shifts itself. 586 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 587 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 588 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 589 } 590 591 if (Subtarget.hasVSX()) { 592 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 593 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 594 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 595 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 596 } 597 598 if (Subtarget.hasAltivec()) { 599 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 600 setOperationAction(ISD::SADDSAT, VT, Legal); 601 setOperationAction(ISD::SSUBSAT, VT, Legal); 602 setOperationAction(ISD::UADDSAT, VT, Legal); 603 setOperationAction(ISD::USUBSAT, VT, Legal); 604 } 605 // First set operation action for all vector types to expand. Then we 606 // will selectively turn on ones that can be effectively codegen'd. 607 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 608 // add/sub are legal for all supported vector VT's. 609 setOperationAction(ISD::ADD, VT, Legal); 610 setOperationAction(ISD::SUB, VT, Legal); 611 612 // For v2i64, these are only valid with P8Vector. This is corrected after 613 // the loop. 614 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 615 setOperationAction(ISD::SMAX, VT, Legal); 616 setOperationAction(ISD::SMIN, VT, Legal); 617 setOperationAction(ISD::UMAX, VT, Legal); 618 setOperationAction(ISD::UMIN, VT, Legal); 619 } 620 else { 621 setOperationAction(ISD::SMAX, VT, Expand); 622 setOperationAction(ISD::SMIN, VT, Expand); 623 setOperationAction(ISD::UMAX, VT, Expand); 624 setOperationAction(ISD::UMIN, VT, Expand); 625 } 626 627 if (Subtarget.hasVSX()) { 628 setOperationAction(ISD::FMAXNUM, VT, Legal); 629 setOperationAction(ISD::FMINNUM, VT, Legal); 630 } 631 632 // Vector instructions introduced in P8 633 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 634 setOperationAction(ISD::CTPOP, VT, Legal); 635 setOperationAction(ISD::CTLZ, VT, Legal); 636 } 637 else { 638 setOperationAction(ISD::CTPOP, VT, Expand); 639 setOperationAction(ISD::CTLZ, VT, Expand); 640 } 641 642 // Vector instructions introduced in P9 643 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 644 setOperationAction(ISD::CTTZ, VT, Legal); 645 else 646 setOperationAction(ISD::CTTZ, VT, Expand); 647 648 // We promote all shuffles to v16i8. 649 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 650 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 651 652 // We promote all non-typed operations to v4i32. 653 setOperationAction(ISD::AND , VT, Promote); 654 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 655 setOperationAction(ISD::OR , VT, Promote); 656 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 657 setOperationAction(ISD::XOR , VT, Promote); 658 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 659 setOperationAction(ISD::LOAD , VT, Promote); 660 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 661 setOperationAction(ISD::SELECT, VT, Promote); 662 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 663 setOperationAction(ISD::VSELECT, VT, Legal); 664 setOperationAction(ISD::SELECT_CC, VT, Promote); 665 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 666 setOperationAction(ISD::STORE, VT, Promote); 667 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 668 669 // No other operations are legal. 670 setOperationAction(ISD::MUL , VT, Expand); 671 setOperationAction(ISD::SDIV, VT, Expand); 672 setOperationAction(ISD::SREM, VT, Expand); 673 setOperationAction(ISD::UDIV, VT, Expand); 674 setOperationAction(ISD::UREM, VT, Expand); 675 setOperationAction(ISD::FDIV, VT, Expand); 676 setOperationAction(ISD::FREM, VT, Expand); 677 setOperationAction(ISD::FNEG, VT, Expand); 678 setOperationAction(ISD::FSQRT, VT, Expand); 679 setOperationAction(ISD::FLOG, VT, Expand); 680 setOperationAction(ISD::FLOG10, VT, Expand); 681 setOperationAction(ISD::FLOG2, VT, Expand); 682 setOperationAction(ISD::FEXP, VT, Expand); 683 setOperationAction(ISD::FEXP2, VT, Expand); 684 setOperationAction(ISD::FSIN, VT, Expand); 685 setOperationAction(ISD::FCOS, VT, Expand); 686 setOperationAction(ISD::FABS, VT, Expand); 687 setOperationAction(ISD::FFLOOR, VT, Expand); 688 setOperationAction(ISD::FCEIL, VT, Expand); 689 setOperationAction(ISD::FTRUNC, VT, Expand); 690 setOperationAction(ISD::FRINT, VT, Expand); 691 setOperationAction(ISD::FNEARBYINT, VT, Expand); 692 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 693 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 694 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 695 setOperationAction(ISD::MULHU, VT, Expand); 696 setOperationAction(ISD::MULHS, VT, Expand); 697 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 698 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 699 setOperationAction(ISD::UDIVREM, VT, Expand); 700 setOperationAction(ISD::SDIVREM, VT, Expand); 701 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 702 setOperationAction(ISD::FPOW, VT, Expand); 703 setOperationAction(ISD::BSWAP, VT, Expand); 704 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 705 setOperationAction(ISD::ROTL, VT, Expand); 706 setOperationAction(ISD::ROTR, VT, Expand); 707 708 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 709 setTruncStoreAction(VT, InnerVT, Expand); 710 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 711 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 712 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 713 } 714 } 715 if (!Subtarget.hasP8Vector()) { 716 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 717 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 718 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 719 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 720 } 721 722 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 723 setOperationAction(ISD::ABS, VT, Custom); 724 725 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 726 // with merges, splats, etc. 727 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 728 729 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 730 // are cheap, so handle them before they get expanded to scalar. 731 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 732 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 733 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 734 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 735 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 736 737 setOperationAction(ISD::AND , MVT::v4i32, Legal); 738 setOperationAction(ISD::OR , MVT::v4i32, Legal); 739 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 740 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 741 setOperationAction(ISD::SELECT, MVT::v4i32, 742 Subtarget.useCRBits() ? Legal : Expand); 743 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 744 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 745 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 746 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 747 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 748 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 749 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 750 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 751 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 752 753 // Without hasP8Altivec set, v2i64 SMAX isn't available. 754 // But ABS custom lowering requires SMAX support. 755 if (!Subtarget.hasP8Altivec()) 756 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 757 758 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 759 if (Subtarget.hasAltivec()) 760 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 761 setOperationAction(ISD::ROTL, VT, Legal); 762 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 763 if (Subtarget.hasP8Altivec()) 764 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 765 766 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 767 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 768 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 769 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 770 771 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 772 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 773 774 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 775 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 776 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 777 } 778 779 if (Subtarget.hasP8Altivec()) 780 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 781 else 782 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 783 784 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 785 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 786 787 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 788 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 789 790 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 791 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 792 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 793 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 794 795 // Altivec does not contain unordered floating-point compare instructions 796 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 797 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 798 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 799 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 800 801 if (Subtarget.hasVSX()) { 802 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 804 if (Subtarget.hasP8Vector()) { 805 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 806 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 807 } 808 if (Subtarget.hasDirectMove() && isPPC64) { 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 817 } 818 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 819 820 // The nearbyint variants are not allowed to raise the inexact exception 821 // so we can only code-gen them with unsafe math. 822 if (TM.Options.UnsafeFPMath) { 823 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 824 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 825 } 826 827 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 828 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 829 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 830 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 831 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 832 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 833 setOperationAction(ISD::FROUND, MVT::f64, Legal); 834 setOperationAction(ISD::FRINT, MVT::f64, Legal); 835 836 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 837 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 838 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 839 setOperationAction(ISD::FROUND, MVT::f32, Legal); 840 setOperationAction(ISD::FRINT, MVT::f32, Legal); 841 842 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 843 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 844 845 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 846 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 847 848 // Share the Altivec comparison restrictions. 849 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 850 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 851 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 852 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 853 854 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 855 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 856 857 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 858 859 if (Subtarget.hasP8Vector()) 860 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 861 862 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 863 864 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 865 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 866 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 867 868 if (Subtarget.hasP8Altivec()) { 869 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 870 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 871 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 872 873 // 128 bit shifts can be accomplished via 3 instructions for SHL and 874 // SRL, but not for SRA because of the instructions available: 875 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 876 // doing 877 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 878 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 879 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 880 881 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 882 } 883 else { 884 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 885 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 886 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 887 888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 889 890 // VSX v2i64 only supports non-arithmetic operations. 891 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 892 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 893 } 894 895 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 896 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 897 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 898 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 899 900 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 901 902 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 903 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 904 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 905 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 906 907 // Custom handling for partial vectors of integers converted to 908 // floating point. We already have optimal handling for v2i32 through 909 // the DAG combine, so those aren't necessary. 910 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 911 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 912 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 913 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 914 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 915 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 916 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 917 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 918 919 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 920 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 921 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 922 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 923 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 924 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 925 926 if (Subtarget.hasDirectMove()) 927 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 928 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 929 930 // Handle constrained floating-point operations of vector. 931 // The predictor is `hasVSX` because altivec instruction has 932 // no exception but VSX vector instruction has. 933 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 934 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 935 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 936 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 937 938 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 939 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 940 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 941 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 942 943 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 944 } 945 946 if (Subtarget.hasP8Altivec()) { 947 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 948 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 949 } 950 951 if (Subtarget.hasP9Vector()) { 952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 953 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 954 955 // 128 bit shifts can be accomplished via 3 instructions for SHL and 956 // SRL, but not for SRA because of the instructions available: 957 // VS{RL} and VS{RL}O. 958 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 959 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 960 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 961 962 if (EnableQuadPrecision) { 963 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 964 setOperationAction(ISD::FADD, MVT::f128, Legal); 965 setOperationAction(ISD::FSUB, MVT::f128, Legal); 966 setOperationAction(ISD::FDIV, MVT::f128, Legal); 967 setOperationAction(ISD::FMUL, MVT::f128, Legal); 968 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 969 // No extending loads to f128 on PPC. 970 for (MVT FPT : MVT::fp_valuetypes()) 971 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 972 setOperationAction(ISD::FMA, MVT::f128, Legal); 973 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 974 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 975 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 976 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 977 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 978 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 979 980 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 981 setOperationAction(ISD::FRINT, MVT::f128, Legal); 982 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 983 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 984 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 985 setOperationAction(ISD::FROUND, MVT::f128, Legal); 986 987 setOperationAction(ISD::SELECT, MVT::f128, Expand); 988 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 989 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 990 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 991 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 992 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 993 // No implementation for these ops for PowerPC. 994 setOperationAction(ISD::FSIN , MVT::f128, Expand); 995 setOperationAction(ISD::FCOS , MVT::f128, Expand); 996 setOperationAction(ISD::FPOW, MVT::f128, Expand); 997 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 998 setOperationAction(ISD::FREM, MVT::f128, Expand); 999 1000 // Handle constrained floating-point operations of fp128 1001 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1002 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1003 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1004 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1005 } 1006 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1007 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1008 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1009 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1010 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1011 } 1012 1013 if (Subtarget.hasP9Altivec()) { 1014 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1015 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1016 1017 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1018 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1019 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1020 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1021 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1022 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1023 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1024 } 1025 } 1026 1027 if (Subtarget.hasQPX()) { 1028 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1029 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1030 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1031 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1032 1033 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1034 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1035 1036 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1037 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1038 1039 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1040 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1041 1042 if (!Subtarget.useCRBits()) 1043 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1044 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1045 1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1047 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1048 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1049 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1050 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1051 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1052 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1053 1054 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1055 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1056 1057 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1058 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1059 1060 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1061 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1062 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1063 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1064 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1065 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1066 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1067 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1068 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1069 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1070 1071 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1072 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1073 1074 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1075 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1076 1077 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1078 1079 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1080 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1081 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1082 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1083 1084 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1085 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1086 1087 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1088 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1089 1090 if (!Subtarget.useCRBits()) 1091 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1092 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1093 1094 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1095 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1096 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1097 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1098 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1099 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1100 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1101 1102 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1103 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1104 1105 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1106 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1107 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1108 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1109 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1110 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1111 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1112 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1113 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1114 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1115 1116 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1117 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1118 1119 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1120 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1121 1122 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1123 1124 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1125 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1126 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1127 1128 if (!Subtarget.useCRBits()) 1129 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1130 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1131 1132 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1133 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1134 1135 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1136 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1137 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1138 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1139 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1140 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1141 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1142 1143 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1144 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1145 1146 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1147 1148 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1149 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1150 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1151 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1152 1153 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1154 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1155 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1156 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1157 1158 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1159 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1160 1161 // These need to set FE_INEXACT, and so cannot be vectorized here. 1162 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1163 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1164 1165 if (TM.Options.UnsafeFPMath) { 1166 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1167 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1168 1169 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1170 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1171 } else { 1172 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1173 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1174 1175 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1176 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1177 } 1178 1179 // TODO: Handle constrained floating-point operations of v4f64 1180 } 1181 1182 if (Subtarget.has64BitSupport()) 1183 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1184 1185 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1186 1187 if (!isPPC64) { 1188 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1189 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1190 } 1191 1192 setBooleanContents(ZeroOrOneBooleanContent); 1193 1194 if (Subtarget.hasAltivec()) { 1195 // Altivec instructions set fields to all zeros or all ones. 1196 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1197 } 1198 1199 if (!isPPC64) { 1200 // These libcalls are not available in 32-bit. 1201 setLibcallName(RTLIB::SHL_I128, nullptr); 1202 setLibcallName(RTLIB::SRL_I128, nullptr); 1203 setLibcallName(RTLIB::SRA_I128, nullptr); 1204 } 1205 1206 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1207 1208 // We have target-specific dag combine patterns for the following nodes: 1209 setTargetDAGCombine(ISD::ADD); 1210 setTargetDAGCombine(ISD::SHL); 1211 setTargetDAGCombine(ISD::SRA); 1212 setTargetDAGCombine(ISD::SRL); 1213 setTargetDAGCombine(ISD::MUL); 1214 setTargetDAGCombine(ISD::SINT_TO_FP); 1215 setTargetDAGCombine(ISD::BUILD_VECTOR); 1216 if (Subtarget.hasFPCVT()) 1217 setTargetDAGCombine(ISD::UINT_TO_FP); 1218 setTargetDAGCombine(ISD::LOAD); 1219 setTargetDAGCombine(ISD::STORE); 1220 setTargetDAGCombine(ISD::BR_CC); 1221 if (Subtarget.useCRBits()) 1222 setTargetDAGCombine(ISD::BRCOND); 1223 setTargetDAGCombine(ISD::BSWAP); 1224 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1225 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1226 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1227 1228 setTargetDAGCombine(ISD::SIGN_EXTEND); 1229 setTargetDAGCombine(ISD::ZERO_EXTEND); 1230 setTargetDAGCombine(ISD::ANY_EXTEND); 1231 1232 setTargetDAGCombine(ISD::TRUNCATE); 1233 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1234 1235 1236 if (Subtarget.useCRBits()) { 1237 setTargetDAGCombine(ISD::TRUNCATE); 1238 setTargetDAGCombine(ISD::SETCC); 1239 setTargetDAGCombine(ISD::SELECT_CC); 1240 } 1241 1242 // Use reciprocal estimates. 1243 if (TM.Options.UnsafeFPMath) { 1244 setTargetDAGCombine(ISD::FDIV); 1245 setTargetDAGCombine(ISD::FSQRT); 1246 } 1247 1248 if (Subtarget.hasP9Altivec()) { 1249 setTargetDAGCombine(ISD::ABS); 1250 setTargetDAGCombine(ISD::VSELECT); 1251 } 1252 1253 if (EnableQuadPrecision) { 1254 setLibcallName(RTLIB::LOG_F128, "logf128"); 1255 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1256 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1257 setLibcallName(RTLIB::EXP_F128, "expf128"); 1258 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1259 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1260 setLibcallName(RTLIB::COS_F128, "cosf128"); 1261 setLibcallName(RTLIB::POW_F128, "powf128"); 1262 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1263 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1264 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1265 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1266 } 1267 1268 // With 32 condition bits, we don't need to sink (and duplicate) compares 1269 // aggressively in CodeGenPrep. 1270 if (Subtarget.useCRBits()) { 1271 setHasMultipleConditionRegisters(); 1272 setJumpIsExpensive(); 1273 } 1274 1275 setMinFunctionAlignment(Align(4)); 1276 1277 switch (Subtarget.getCPUDirective()) { 1278 default: break; 1279 case PPC::DIR_970: 1280 case PPC::DIR_A2: 1281 case PPC::DIR_E500: 1282 case PPC::DIR_E500mc: 1283 case PPC::DIR_E5500: 1284 case PPC::DIR_PWR4: 1285 case PPC::DIR_PWR5: 1286 case PPC::DIR_PWR5X: 1287 case PPC::DIR_PWR6: 1288 case PPC::DIR_PWR6X: 1289 case PPC::DIR_PWR7: 1290 case PPC::DIR_PWR8: 1291 case PPC::DIR_PWR9: 1292 case PPC::DIR_PWR_FUTURE: 1293 setPrefLoopAlignment(Align(16)); 1294 setPrefFunctionAlignment(Align(16)); 1295 break; 1296 } 1297 1298 if (Subtarget.enableMachineScheduler()) 1299 setSchedulingPreference(Sched::Source); 1300 else 1301 setSchedulingPreference(Sched::Hybrid); 1302 1303 computeRegisterProperties(STI.getRegisterInfo()); 1304 1305 // The Freescale cores do better with aggressive inlining of memcpy and 1306 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1307 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1308 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1309 MaxStoresPerMemset = 32; 1310 MaxStoresPerMemsetOptSize = 16; 1311 MaxStoresPerMemcpy = 32; 1312 MaxStoresPerMemcpyOptSize = 8; 1313 MaxStoresPerMemmove = 32; 1314 MaxStoresPerMemmoveOptSize = 8; 1315 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1316 // The A2 also benefits from (very) aggressive inlining of memcpy and 1317 // friends. The overhead of a the function call, even when warm, can be 1318 // over one hundred cycles. 1319 MaxStoresPerMemset = 128; 1320 MaxStoresPerMemcpy = 128; 1321 MaxStoresPerMemmove = 128; 1322 MaxLoadsPerMemcmp = 128; 1323 } else { 1324 MaxLoadsPerMemcmp = 8; 1325 MaxLoadsPerMemcmpOptSize = 4; 1326 } 1327 } 1328 1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1330 /// the desired ByVal argument alignment. 1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1332 unsigned MaxMaxAlign) { 1333 if (MaxAlign == MaxMaxAlign) 1334 return; 1335 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1336 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1337 MaxAlign = 32; 1338 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1339 MaxAlign = 16; 1340 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1341 unsigned EltAlign = 0; 1342 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1343 if (EltAlign > MaxAlign) 1344 MaxAlign = EltAlign; 1345 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1346 for (auto *EltTy : STy->elements()) { 1347 unsigned EltAlign = 0; 1348 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1349 if (EltAlign > MaxAlign) 1350 MaxAlign = EltAlign; 1351 if (MaxAlign == MaxMaxAlign) 1352 break; 1353 } 1354 } 1355 } 1356 1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1358 /// function arguments in the caller parameter area. 1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1360 const DataLayout &DL) const { 1361 // 16byte and wider vectors are passed on 16byte boundary. 1362 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1363 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1364 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1365 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1366 return Align; 1367 } 1368 1369 bool PPCTargetLowering::useSoftFloat() const { 1370 return Subtarget.useSoftFloat(); 1371 } 1372 1373 bool PPCTargetLowering::hasSPE() const { 1374 return Subtarget.hasSPE(); 1375 } 1376 1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1378 return VT.isScalarInteger(); 1379 } 1380 1381 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1382 switch ((PPCISD::NodeType)Opcode) { 1383 case PPCISD::FIRST_NUMBER: break; 1384 case PPCISD::FSEL: return "PPCISD::FSEL"; 1385 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1386 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1387 case PPCISD::FCFID: return "PPCISD::FCFID"; 1388 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1389 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1390 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1391 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1392 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1393 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1394 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1395 case PPCISD::FP_TO_UINT_IN_VSR: 1396 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1397 case PPCISD::FP_TO_SINT_IN_VSR: 1398 return "PPCISD::FP_TO_SINT_IN_VSR"; 1399 case PPCISD::FRE: return "PPCISD::FRE"; 1400 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1401 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1402 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1403 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1404 case PPCISD::VPERM: return "PPCISD::VPERM"; 1405 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1406 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1407 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1408 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1409 case PPCISD::CMPB: return "PPCISD::CMPB"; 1410 case PPCISD::Hi: return "PPCISD::Hi"; 1411 case PPCISD::Lo: return "PPCISD::Lo"; 1412 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1413 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1414 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1415 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1416 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1417 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1418 case PPCISD::SRL: return "PPCISD::SRL"; 1419 case PPCISD::SRA: return "PPCISD::SRA"; 1420 case PPCISD::SHL: return "PPCISD::SHL"; 1421 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1422 case PPCISD::CALL: return "PPCISD::CALL"; 1423 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1424 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1425 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1426 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1427 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1428 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1429 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1430 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1431 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1432 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1433 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1434 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1435 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1436 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1437 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1438 case PPCISD::ANDI_rec_1_EQ_BIT: 1439 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1440 case PPCISD::ANDI_rec_1_GT_BIT: 1441 return "PPCISD::ANDI_rec_1_GT_BIT"; 1442 case PPCISD::VCMP: return "PPCISD::VCMP"; 1443 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1444 case PPCISD::LBRX: return "PPCISD::LBRX"; 1445 case PPCISD::STBRX: return "PPCISD::STBRX"; 1446 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1447 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1448 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1449 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1450 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1451 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1452 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1453 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1454 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1455 case PPCISD::ST_VSR_SCAL_INT: 1456 return "PPCISD::ST_VSR_SCAL_INT"; 1457 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1458 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1459 case PPCISD::BDZ: return "PPCISD::BDZ"; 1460 case PPCISD::MFFS: return "PPCISD::MFFS"; 1461 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1462 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1463 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1464 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1465 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1466 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1467 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1468 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1469 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1470 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1471 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1472 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1473 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1474 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1475 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1476 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1477 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1478 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1479 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1480 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1481 case PPCISD::SC: return "PPCISD::SC"; 1482 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1483 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1484 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1485 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1486 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1487 case PPCISD::VABSD: return "PPCISD::VABSD"; 1488 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1489 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1490 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1491 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1492 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1493 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1494 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1495 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1496 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1497 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1498 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1499 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1500 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1501 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1502 } 1503 return nullptr; 1504 } 1505 1506 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1507 EVT VT) const { 1508 if (!VT.isVector()) 1509 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1510 1511 if (Subtarget.hasQPX()) 1512 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1513 1514 return VT.changeVectorElementTypeToInteger(); 1515 } 1516 1517 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1518 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1519 return true; 1520 } 1521 1522 //===----------------------------------------------------------------------===// 1523 // Node matching predicates, for use by the tblgen matching code. 1524 //===----------------------------------------------------------------------===// 1525 1526 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1527 static bool isFloatingPointZero(SDValue Op) { 1528 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1529 return CFP->getValueAPF().isZero(); 1530 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1531 // Maybe this has already been legalized into the constant pool? 1532 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1533 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1534 return CFP->getValueAPF().isZero(); 1535 } 1536 return false; 1537 } 1538 1539 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1540 /// true if Op is undef or if it matches the specified value. 1541 static bool isConstantOrUndef(int Op, int Val) { 1542 return Op < 0 || Op == Val; 1543 } 1544 1545 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1546 /// VPKUHUM instruction. 1547 /// The ShuffleKind distinguishes between big-endian operations with 1548 /// two different inputs (0), either-endian operations with two identical 1549 /// inputs (1), and little-endian operations with two different inputs (2). 1550 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1551 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1552 SelectionDAG &DAG) { 1553 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1554 if (ShuffleKind == 0) { 1555 if (IsLE) 1556 return false; 1557 for (unsigned i = 0; i != 16; ++i) 1558 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1559 return false; 1560 } else if (ShuffleKind == 2) { 1561 if (!IsLE) 1562 return false; 1563 for (unsigned i = 0; i != 16; ++i) 1564 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1565 return false; 1566 } else if (ShuffleKind == 1) { 1567 unsigned j = IsLE ? 0 : 1; 1568 for (unsigned i = 0; i != 8; ++i) 1569 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1570 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1571 return false; 1572 } 1573 return true; 1574 } 1575 1576 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1577 /// VPKUWUM instruction. 1578 /// The ShuffleKind distinguishes between big-endian operations with 1579 /// two different inputs (0), either-endian operations with two identical 1580 /// inputs (1), and little-endian operations with two different inputs (2). 1581 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1582 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1583 SelectionDAG &DAG) { 1584 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1585 if (ShuffleKind == 0) { 1586 if (IsLE) 1587 return false; 1588 for (unsigned i = 0; i != 16; i += 2) 1589 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1590 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1591 return false; 1592 } else if (ShuffleKind == 2) { 1593 if (!IsLE) 1594 return false; 1595 for (unsigned i = 0; i != 16; i += 2) 1596 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1597 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1598 return false; 1599 } else if (ShuffleKind == 1) { 1600 unsigned j = IsLE ? 0 : 2; 1601 for (unsigned i = 0; i != 8; i += 2) 1602 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1603 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1604 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1605 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1606 return false; 1607 } 1608 return true; 1609 } 1610 1611 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1612 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1613 /// current subtarget. 1614 /// 1615 /// The ShuffleKind distinguishes between big-endian operations with 1616 /// two different inputs (0), either-endian operations with two identical 1617 /// inputs (1), and little-endian operations with two different inputs (2). 1618 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1619 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1620 SelectionDAG &DAG) { 1621 const PPCSubtarget& Subtarget = 1622 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1623 if (!Subtarget.hasP8Vector()) 1624 return false; 1625 1626 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1627 if (ShuffleKind == 0) { 1628 if (IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; i += 4) 1631 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1632 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1633 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1634 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1635 return false; 1636 } else if (ShuffleKind == 2) { 1637 if (!IsLE) 1638 return false; 1639 for (unsigned i = 0; i != 16; i += 4) 1640 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1641 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1642 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1643 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1644 return false; 1645 } else if (ShuffleKind == 1) { 1646 unsigned j = IsLE ? 0 : 4; 1647 for (unsigned i = 0; i != 8; i += 4) 1648 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1649 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1650 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1651 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1652 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1653 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1654 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1655 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1656 return false; 1657 } 1658 return true; 1659 } 1660 1661 /// isVMerge - Common function, used to match vmrg* shuffles. 1662 /// 1663 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1664 unsigned LHSStart, unsigned RHSStart) { 1665 if (N->getValueType(0) != MVT::v16i8) 1666 return false; 1667 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1668 "Unsupported merge size!"); 1669 1670 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1671 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1672 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1673 LHSStart+j+i*UnitSize) || 1674 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1675 RHSStart+j+i*UnitSize)) 1676 return false; 1677 } 1678 return true; 1679 } 1680 1681 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1682 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1683 /// The ShuffleKind distinguishes between big-endian merges with two 1684 /// different inputs (0), either-endian merges with two identical inputs (1), 1685 /// and little-endian merges with two different inputs (2). For the latter, 1686 /// the input operands are swapped (see PPCInstrAltivec.td). 1687 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1688 unsigned ShuffleKind, SelectionDAG &DAG) { 1689 if (DAG.getDataLayout().isLittleEndian()) { 1690 if (ShuffleKind == 1) // unary 1691 return isVMerge(N, UnitSize, 0, 0); 1692 else if (ShuffleKind == 2) // swapped 1693 return isVMerge(N, UnitSize, 0, 16); 1694 else 1695 return false; 1696 } else { 1697 if (ShuffleKind == 1) // unary 1698 return isVMerge(N, UnitSize, 8, 8); 1699 else if (ShuffleKind == 0) // normal 1700 return isVMerge(N, UnitSize, 8, 24); 1701 else 1702 return false; 1703 } 1704 } 1705 1706 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1707 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1708 /// The ShuffleKind distinguishes between big-endian merges with two 1709 /// different inputs (0), either-endian merges with two identical inputs (1), 1710 /// and little-endian merges with two different inputs (2). For the latter, 1711 /// the input operands are swapped (see PPCInstrAltivec.td). 1712 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1713 unsigned ShuffleKind, SelectionDAG &DAG) { 1714 if (DAG.getDataLayout().isLittleEndian()) { 1715 if (ShuffleKind == 1) // unary 1716 return isVMerge(N, UnitSize, 8, 8); 1717 else if (ShuffleKind == 2) // swapped 1718 return isVMerge(N, UnitSize, 8, 24); 1719 else 1720 return false; 1721 } else { 1722 if (ShuffleKind == 1) // unary 1723 return isVMerge(N, UnitSize, 0, 0); 1724 else if (ShuffleKind == 0) // normal 1725 return isVMerge(N, UnitSize, 0, 16); 1726 else 1727 return false; 1728 } 1729 } 1730 1731 /** 1732 * Common function used to match vmrgew and vmrgow shuffles 1733 * 1734 * The indexOffset determines whether to look for even or odd words in 1735 * the shuffle mask. This is based on the of the endianness of the target 1736 * machine. 1737 * - Little Endian: 1738 * - Use offset of 0 to check for odd elements 1739 * - Use offset of 4 to check for even elements 1740 * - Big Endian: 1741 * - Use offset of 0 to check for even elements 1742 * - Use offset of 4 to check for odd elements 1743 * A detailed description of the vector element ordering for little endian and 1744 * big endian can be found at 1745 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1746 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1747 * compiler differences mean to you 1748 * 1749 * The mask to the shuffle vector instruction specifies the indices of the 1750 * elements from the two input vectors to place in the result. The elements are 1751 * numbered in array-access order, starting with the first vector. These vectors 1752 * are always of type v16i8, thus each vector will contain 16 elements of size 1753 * 8. More info on the shuffle vector can be found in the 1754 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1755 * Language Reference. 1756 * 1757 * The RHSStartValue indicates whether the same input vectors are used (unary) 1758 * or two different input vectors are used, based on the following: 1759 * - If the instruction uses the same vector for both inputs, the range of the 1760 * indices will be 0 to 15. In this case, the RHSStart value passed should 1761 * be 0. 1762 * - If the instruction has two different vectors then the range of the 1763 * indices will be 0 to 31. In this case, the RHSStart value passed should 1764 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1765 * to 31 specify elements in the second vector). 1766 * 1767 * \param[in] N The shuffle vector SD Node to analyze 1768 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1769 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1770 * vector to the shuffle_vector instruction 1771 * \return true iff this shuffle vector represents an even or odd word merge 1772 */ 1773 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1774 unsigned RHSStartValue) { 1775 if (N->getValueType(0) != MVT::v16i8) 1776 return false; 1777 1778 for (unsigned i = 0; i < 2; ++i) 1779 for (unsigned j = 0; j < 4; ++j) 1780 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1781 i*RHSStartValue+j+IndexOffset) || 1782 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1783 i*RHSStartValue+j+IndexOffset+8)) 1784 return false; 1785 return true; 1786 } 1787 1788 /** 1789 * Determine if the specified shuffle mask is suitable for the vmrgew or 1790 * vmrgow instructions. 1791 * 1792 * \param[in] N The shuffle vector SD Node to analyze 1793 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1794 * \param[in] ShuffleKind Identify the type of merge: 1795 * - 0 = big-endian merge with two different inputs; 1796 * - 1 = either-endian merge with two identical inputs; 1797 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1798 * little-endian merges). 1799 * \param[in] DAG The current SelectionDAG 1800 * \return true iff this shuffle mask 1801 */ 1802 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1803 unsigned ShuffleKind, SelectionDAG &DAG) { 1804 if (DAG.getDataLayout().isLittleEndian()) { 1805 unsigned indexOffset = CheckEven ? 4 : 0; 1806 if (ShuffleKind == 1) // Unary 1807 return isVMerge(N, indexOffset, 0); 1808 else if (ShuffleKind == 2) // swapped 1809 return isVMerge(N, indexOffset, 16); 1810 else 1811 return false; 1812 } 1813 else { 1814 unsigned indexOffset = CheckEven ? 0 : 4; 1815 if (ShuffleKind == 1) // Unary 1816 return isVMerge(N, indexOffset, 0); 1817 else if (ShuffleKind == 0) // Normal 1818 return isVMerge(N, indexOffset, 16); 1819 else 1820 return false; 1821 } 1822 return false; 1823 } 1824 1825 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1826 /// amount, otherwise return -1. 1827 /// The ShuffleKind distinguishes between big-endian operations with two 1828 /// different inputs (0), either-endian operations with two identical inputs 1829 /// (1), and little-endian operations with two different inputs (2). For the 1830 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1831 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1832 SelectionDAG &DAG) { 1833 if (N->getValueType(0) != MVT::v16i8) 1834 return -1; 1835 1836 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1837 1838 // Find the first non-undef value in the shuffle mask. 1839 unsigned i; 1840 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1841 /*search*/; 1842 1843 if (i == 16) return -1; // all undef. 1844 1845 // Otherwise, check to see if the rest of the elements are consecutively 1846 // numbered from this value. 1847 unsigned ShiftAmt = SVOp->getMaskElt(i); 1848 if (ShiftAmt < i) return -1; 1849 1850 ShiftAmt -= i; 1851 bool isLE = DAG.getDataLayout().isLittleEndian(); 1852 1853 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1854 // Check the rest of the elements to see if they are consecutive. 1855 for (++i; i != 16; ++i) 1856 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1857 return -1; 1858 } else if (ShuffleKind == 1) { 1859 // Check the rest of the elements to see if they are consecutive. 1860 for (++i; i != 16; ++i) 1861 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1862 return -1; 1863 } else 1864 return -1; 1865 1866 if (isLE) 1867 ShiftAmt = 16 - ShiftAmt; 1868 1869 return ShiftAmt; 1870 } 1871 1872 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1873 /// specifies a splat of a single element that is suitable for input to 1874 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1875 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1876 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1877 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1878 1879 // The consecutive indices need to specify an element, not part of two 1880 // different elements. So abandon ship early if this isn't the case. 1881 if (N->getMaskElt(0) % EltSize != 0) 1882 return false; 1883 1884 // This is a splat operation if each element of the permute is the same, and 1885 // if the value doesn't reference the second vector. 1886 unsigned ElementBase = N->getMaskElt(0); 1887 1888 // FIXME: Handle UNDEF elements too! 1889 if (ElementBase >= 16) 1890 return false; 1891 1892 // Check that the indices are consecutive, in the case of a multi-byte element 1893 // splatted with a v16i8 mask. 1894 for (unsigned i = 1; i != EltSize; ++i) 1895 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1896 return false; 1897 1898 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1899 if (N->getMaskElt(i) < 0) continue; 1900 for (unsigned j = 0; j != EltSize; ++j) 1901 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1902 return false; 1903 } 1904 return true; 1905 } 1906 1907 /// Check that the mask is shuffling N byte elements. Within each N byte 1908 /// element of the mask, the indices could be either in increasing or 1909 /// decreasing order as long as they are consecutive. 1910 /// \param[in] N the shuffle vector SD Node to analyze 1911 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1912 /// Word/DoubleWord/QuadWord). 1913 /// \param[in] StepLen the delta indices number among the N byte element, if 1914 /// the mask is in increasing/decreasing order then it is 1/-1. 1915 /// \return true iff the mask is shuffling N byte elements. 1916 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1917 int StepLen) { 1918 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1919 "Unexpected element width."); 1920 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1921 1922 unsigned NumOfElem = 16 / Width; 1923 unsigned MaskVal[16]; // Width is never greater than 16 1924 for (unsigned i = 0; i < NumOfElem; ++i) { 1925 MaskVal[0] = N->getMaskElt(i * Width); 1926 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1927 return false; 1928 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1929 return false; 1930 } 1931 1932 for (unsigned int j = 1; j < Width; ++j) { 1933 MaskVal[j] = N->getMaskElt(i * Width + j); 1934 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1935 return false; 1936 } 1937 } 1938 } 1939 1940 return true; 1941 } 1942 1943 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1944 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1945 if (!isNByteElemShuffleMask(N, 4, 1)) 1946 return false; 1947 1948 // Now we look at mask elements 0,4,8,12 1949 unsigned M0 = N->getMaskElt(0) / 4; 1950 unsigned M1 = N->getMaskElt(4) / 4; 1951 unsigned M2 = N->getMaskElt(8) / 4; 1952 unsigned M3 = N->getMaskElt(12) / 4; 1953 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1954 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1955 1956 // Below, let H and L be arbitrary elements of the shuffle mask 1957 // where H is in the range [4,7] and L is in the range [0,3]. 1958 // H, 1, 2, 3 or L, 5, 6, 7 1959 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1960 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1961 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1962 InsertAtByte = IsLE ? 12 : 0; 1963 Swap = M0 < 4; 1964 return true; 1965 } 1966 // 0, H, 2, 3 or 4, L, 6, 7 1967 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1968 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1969 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1970 InsertAtByte = IsLE ? 8 : 4; 1971 Swap = M1 < 4; 1972 return true; 1973 } 1974 // 0, 1, H, 3 or 4, 5, L, 7 1975 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1976 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1977 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1978 InsertAtByte = IsLE ? 4 : 8; 1979 Swap = M2 < 4; 1980 return true; 1981 } 1982 // 0, 1, 2, H or 4, 5, 6, L 1983 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1984 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1985 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1986 InsertAtByte = IsLE ? 0 : 12; 1987 Swap = M3 < 4; 1988 return true; 1989 } 1990 1991 // If both vector operands for the shuffle are the same vector, the mask will 1992 // contain only elements from the first one and the second one will be undef. 1993 if (N->getOperand(1).isUndef()) { 1994 ShiftElts = 0; 1995 Swap = true; 1996 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1997 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1998 InsertAtByte = IsLE ? 12 : 0; 1999 return true; 2000 } 2001 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2002 InsertAtByte = IsLE ? 8 : 4; 2003 return true; 2004 } 2005 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2006 InsertAtByte = IsLE ? 4 : 8; 2007 return true; 2008 } 2009 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2010 InsertAtByte = IsLE ? 0 : 12; 2011 return true; 2012 } 2013 } 2014 2015 return false; 2016 } 2017 2018 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2019 bool &Swap, bool IsLE) { 2020 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2021 // Ensure each byte index of the word is consecutive. 2022 if (!isNByteElemShuffleMask(N, 4, 1)) 2023 return false; 2024 2025 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2026 unsigned M0 = N->getMaskElt(0) / 4; 2027 unsigned M1 = N->getMaskElt(4) / 4; 2028 unsigned M2 = N->getMaskElt(8) / 4; 2029 unsigned M3 = N->getMaskElt(12) / 4; 2030 2031 // If both vector operands for the shuffle are the same vector, the mask will 2032 // contain only elements from the first one and the second one will be undef. 2033 if (N->getOperand(1).isUndef()) { 2034 assert(M0 < 4 && "Indexing into an undef vector?"); 2035 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2036 return false; 2037 2038 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2039 Swap = false; 2040 return true; 2041 } 2042 2043 // Ensure each word index of the ShuffleVector Mask is consecutive. 2044 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2045 return false; 2046 2047 if (IsLE) { 2048 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2049 // Input vectors don't need to be swapped if the leading element 2050 // of the result is one of the 3 left elements of the second vector 2051 // (or if there is no shift to be done at all). 2052 Swap = false; 2053 ShiftElts = (8 - M0) % 8; 2054 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2055 // Input vectors need to be swapped if the leading element 2056 // of the result is one of the 3 left elements of the first vector 2057 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2058 Swap = true; 2059 ShiftElts = (4 - M0) % 4; 2060 } 2061 2062 return true; 2063 } else { // BE 2064 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2065 // Input vectors don't need to be swapped if the leading element 2066 // of the result is one of the 4 elements of the first vector. 2067 Swap = false; 2068 ShiftElts = M0; 2069 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2070 // Input vectors need to be swapped if the leading element 2071 // of the result is one of the 4 elements of the right vector. 2072 Swap = true; 2073 ShiftElts = M0 - 4; 2074 } 2075 2076 return true; 2077 } 2078 } 2079 2080 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2081 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2082 2083 if (!isNByteElemShuffleMask(N, Width, -1)) 2084 return false; 2085 2086 for (int i = 0; i < 16; i += Width) 2087 if (N->getMaskElt(i) != i + Width - 1) 2088 return false; 2089 2090 return true; 2091 } 2092 2093 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2094 return isXXBRShuffleMaskHelper(N, 2); 2095 } 2096 2097 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2098 return isXXBRShuffleMaskHelper(N, 4); 2099 } 2100 2101 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2102 return isXXBRShuffleMaskHelper(N, 8); 2103 } 2104 2105 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2106 return isXXBRShuffleMaskHelper(N, 16); 2107 } 2108 2109 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2110 /// if the inputs to the instruction should be swapped and set \p DM to the 2111 /// value for the immediate. 2112 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2113 /// AND element 0 of the result comes from the first input (LE) or second input 2114 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2115 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2116 /// mask. 2117 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2118 bool &Swap, bool IsLE) { 2119 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2120 2121 // Ensure each byte index of the double word is consecutive. 2122 if (!isNByteElemShuffleMask(N, 8, 1)) 2123 return false; 2124 2125 unsigned M0 = N->getMaskElt(0) / 8; 2126 unsigned M1 = N->getMaskElt(8) / 8; 2127 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2128 2129 // If both vector operands for the shuffle are the same vector, the mask will 2130 // contain only elements from the first one and the second one will be undef. 2131 if (N->getOperand(1).isUndef()) { 2132 if ((M0 | M1) < 2) { 2133 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2134 Swap = false; 2135 return true; 2136 } else 2137 return false; 2138 } 2139 2140 if (IsLE) { 2141 if (M0 > 1 && M1 < 2) { 2142 Swap = false; 2143 } else if (M0 < 2 && M1 > 1) { 2144 M0 = (M0 + 2) % 4; 2145 M1 = (M1 + 2) % 4; 2146 Swap = true; 2147 } else 2148 return false; 2149 2150 // Note: if control flow comes here that means Swap is already set above 2151 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2152 return true; 2153 } else { // BE 2154 if (M0 < 2 && M1 > 1) { 2155 Swap = false; 2156 } else if (M0 > 1 && M1 < 2) { 2157 M0 = (M0 + 2) % 4; 2158 M1 = (M1 + 2) % 4; 2159 Swap = true; 2160 } else 2161 return false; 2162 2163 // Note: if control flow comes here that means Swap is already set above 2164 DM = (M0 << 1) + (M1 & 1); 2165 return true; 2166 } 2167 } 2168 2169 2170 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2171 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2172 /// elements are counted from the left of the vector register). 2173 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2174 SelectionDAG &DAG) { 2175 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2176 assert(isSplatShuffleMask(SVOp, EltSize)); 2177 if (DAG.getDataLayout().isLittleEndian()) 2178 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2179 else 2180 return SVOp->getMaskElt(0) / EltSize; 2181 } 2182 2183 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2184 /// by using a vspltis[bhw] instruction of the specified element size, return 2185 /// the constant being splatted. The ByteSize field indicates the number of 2186 /// bytes of each element [124] -> [bhw]. 2187 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2188 SDValue OpVal(nullptr, 0); 2189 2190 // If ByteSize of the splat is bigger than the element size of the 2191 // build_vector, then we have a case where we are checking for a splat where 2192 // multiple elements of the buildvector are folded together into a single 2193 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2194 unsigned EltSize = 16/N->getNumOperands(); 2195 if (EltSize < ByteSize) { 2196 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2197 SDValue UniquedVals[4]; 2198 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2199 2200 // See if all of the elements in the buildvector agree across. 2201 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2202 if (N->getOperand(i).isUndef()) continue; 2203 // If the element isn't a constant, bail fully out. 2204 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2205 2206 if (!UniquedVals[i&(Multiple-1)].getNode()) 2207 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2208 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2209 return SDValue(); // no match. 2210 } 2211 2212 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2213 // either constant or undef values that are identical for each chunk. See 2214 // if these chunks can form into a larger vspltis*. 2215 2216 // Check to see if all of the leading entries are either 0 or -1. If 2217 // neither, then this won't fit into the immediate field. 2218 bool LeadingZero = true; 2219 bool LeadingOnes = true; 2220 for (unsigned i = 0; i != Multiple-1; ++i) { 2221 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2222 2223 LeadingZero &= isNullConstant(UniquedVals[i]); 2224 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2225 } 2226 // Finally, check the least significant entry. 2227 if (LeadingZero) { 2228 if (!UniquedVals[Multiple-1].getNode()) 2229 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2230 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2231 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2232 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2233 } 2234 if (LeadingOnes) { 2235 if (!UniquedVals[Multiple-1].getNode()) 2236 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2237 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2238 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2239 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2240 } 2241 2242 return SDValue(); 2243 } 2244 2245 // Check to see if this buildvec has a single non-undef value in its elements. 2246 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2247 if (N->getOperand(i).isUndef()) continue; 2248 if (!OpVal.getNode()) 2249 OpVal = N->getOperand(i); 2250 else if (OpVal != N->getOperand(i)) 2251 return SDValue(); 2252 } 2253 2254 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2255 2256 unsigned ValSizeInBytes = EltSize; 2257 uint64_t Value = 0; 2258 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2259 Value = CN->getZExtValue(); 2260 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2261 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2262 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2263 } 2264 2265 // If the splat value is larger than the element value, then we can never do 2266 // this splat. The only case that we could fit the replicated bits into our 2267 // immediate field for would be zero, and we prefer to use vxor for it. 2268 if (ValSizeInBytes < ByteSize) return SDValue(); 2269 2270 // If the element value is larger than the splat value, check if it consists 2271 // of a repeated bit pattern of size ByteSize. 2272 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2273 return SDValue(); 2274 2275 // Properly sign extend the value. 2276 int MaskVal = SignExtend32(Value, ByteSize * 8); 2277 2278 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2279 if (MaskVal == 0) return SDValue(); 2280 2281 // Finally, if this value fits in a 5 bit sext field, return it 2282 if (SignExtend32<5>(MaskVal) == MaskVal) 2283 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2284 return SDValue(); 2285 } 2286 2287 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2288 /// amount, otherwise return -1. 2289 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2290 EVT VT = N->getValueType(0); 2291 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2292 return -1; 2293 2294 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2295 2296 // Find the first non-undef value in the shuffle mask. 2297 unsigned i; 2298 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2299 /*search*/; 2300 2301 if (i == 4) return -1; // all undef. 2302 2303 // Otherwise, check to see if the rest of the elements are consecutively 2304 // numbered from this value. 2305 unsigned ShiftAmt = SVOp->getMaskElt(i); 2306 if (ShiftAmt < i) return -1; 2307 ShiftAmt -= i; 2308 2309 // Check the rest of the elements to see if they are consecutive. 2310 for (++i; i != 4; ++i) 2311 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2312 return -1; 2313 2314 return ShiftAmt; 2315 } 2316 2317 //===----------------------------------------------------------------------===// 2318 // Addressing Mode Selection 2319 //===----------------------------------------------------------------------===// 2320 2321 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2322 /// or 64-bit immediate, and if the value can be accurately represented as a 2323 /// sign extension from a 16-bit value. If so, this returns true and the 2324 /// immediate. 2325 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2326 if (!isa<ConstantSDNode>(N)) 2327 return false; 2328 2329 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2330 if (N->getValueType(0) == MVT::i32) 2331 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2332 else 2333 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2334 } 2335 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2336 return isIntS16Immediate(Op.getNode(), Imm); 2337 } 2338 2339 2340 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2341 /// be represented as an indexed [r+r] operation. 2342 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2343 SDValue &Index, 2344 SelectionDAG &DAG) const { 2345 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2346 UI != E; ++UI) { 2347 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2348 if (Memop->getMemoryVT() == MVT::f64) { 2349 Base = N.getOperand(0); 2350 Index = N.getOperand(1); 2351 return true; 2352 } 2353 } 2354 } 2355 return false; 2356 } 2357 2358 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2359 /// can be represented as an indexed [r+r] operation. Returns false if it 2360 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2361 /// non-zero and N can be represented by a base register plus a signed 16-bit 2362 /// displacement, make a more precise judgement by checking (displacement % \p 2363 /// EncodingAlignment). 2364 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2365 SDValue &Index, SelectionDAG &DAG, 2366 unsigned EncodingAlignment) const { 2367 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2368 // a [pc+imm]. 2369 if (SelectAddressPCRel(N, Base)) 2370 return false; 2371 2372 int16_t imm = 0; 2373 if (N.getOpcode() == ISD::ADD) { 2374 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2375 // SPE load/store can only handle 8-bit offsets. 2376 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2377 return true; 2378 if (isIntS16Immediate(N.getOperand(1), imm) && 2379 (!EncodingAlignment || !(imm % EncodingAlignment))) 2380 return false; // r+i 2381 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2382 return false; // r+i 2383 2384 Base = N.getOperand(0); 2385 Index = N.getOperand(1); 2386 return true; 2387 } else if (N.getOpcode() == ISD::OR) { 2388 if (isIntS16Immediate(N.getOperand(1), imm) && 2389 (!EncodingAlignment || !(imm % EncodingAlignment))) 2390 return false; // r+i can fold it if we can. 2391 2392 // If this is an or of disjoint bitfields, we can codegen this as an add 2393 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2394 // disjoint. 2395 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2396 2397 if (LHSKnown.Zero.getBoolValue()) { 2398 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2399 // If all of the bits are known zero on the LHS or RHS, the add won't 2400 // carry. 2401 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2402 Base = N.getOperand(0); 2403 Index = N.getOperand(1); 2404 return true; 2405 } 2406 } 2407 } 2408 2409 return false; 2410 } 2411 2412 // If we happen to be doing an i64 load or store into a stack slot that has 2413 // less than a 4-byte alignment, then the frame-index elimination may need to 2414 // use an indexed load or store instruction (because the offset may not be a 2415 // multiple of 4). The extra register needed to hold the offset comes from the 2416 // register scavenger, and it is possible that the scavenger will need to use 2417 // an emergency spill slot. As a result, we need to make sure that a spill slot 2418 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2419 // stack slot. 2420 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2421 // FIXME: This does not handle the LWA case. 2422 if (VT != MVT::i64) 2423 return; 2424 2425 // NOTE: We'll exclude negative FIs here, which come from argument 2426 // lowering, because there are no known test cases triggering this problem 2427 // using packed structures (or similar). We can remove this exclusion if 2428 // we find such a test case. The reason why this is so test-case driven is 2429 // because this entire 'fixup' is only to prevent crashes (from the 2430 // register scavenger) on not-really-valid inputs. For example, if we have: 2431 // %a = alloca i1 2432 // %b = bitcast i1* %a to i64* 2433 // store i64* a, i64 b 2434 // then the store should really be marked as 'align 1', but is not. If it 2435 // were marked as 'align 1' then the indexed form would have been 2436 // instruction-selected initially, and the problem this 'fixup' is preventing 2437 // won't happen regardless. 2438 if (FrameIdx < 0) 2439 return; 2440 2441 MachineFunction &MF = DAG.getMachineFunction(); 2442 MachineFrameInfo &MFI = MF.getFrameInfo(); 2443 2444 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2445 return; 2446 2447 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2448 FuncInfo->setHasNonRISpills(); 2449 } 2450 2451 /// Returns true if the address N can be represented by a base register plus 2452 /// a signed 16-bit displacement [r+imm], and if it is not better 2453 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2454 /// displacements that are multiples of that value. 2455 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2456 SDValue &Base, 2457 SelectionDAG &DAG, 2458 unsigned EncodingAlignment) const { 2459 // FIXME dl should come from parent load or store, not from address 2460 SDLoc dl(N); 2461 2462 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2463 // a [pc+imm]. 2464 if (SelectAddressPCRel(N, Base)) 2465 return false; 2466 2467 // If this can be more profitably realized as r+r, fail. 2468 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2469 return false; 2470 2471 if (N.getOpcode() == ISD::ADD) { 2472 int16_t imm = 0; 2473 if (isIntS16Immediate(N.getOperand(1), imm) && 2474 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2475 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2476 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2477 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2478 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2479 } else { 2480 Base = N.getOperand(0); 2481 } 2482 return true; // [r+i] 2483 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2484 // Match LOAD (ADD (X, Lo(G))). 2485 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2486 && "Cannot handle constant offsets yet!"); 2487 Disp = N.getOperand(1).getOperand(0); // The global address. 2488 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2489 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2490 Disp.getOpcode() == ISD::TargetConstantPool || 2491 Disp.getOpcode() == ISD::TargetJumpTable); 2492 Base = N.getOperand(0); 2493 return true; // [&g+r] 2494 } 2495 } else if (N.getOpcode() == ISD::OR) { 2496 int16_t imm = 0; 2497 if (isIntS16Immediate(N.getOperand(1), imm) && 2498 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2499 // If this is an or of disjoint bitfields, we can codegen this as an add 2500 // (for better address arithmetic) if the LHS and RHS of the OR are 2501 // provably disjoint. 2502 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2503 2504 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2505 // If all of the bits are known zero on the LHS or RHS, the add won't 2506 // carry. 2507 if (FrameIndexSDNode *FI = 2508 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2509 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2510 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2511 } else { 2512 Base = N.getOperand(0); 2513 } 2514 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2515 return true; 2516 } 2517 } 2518 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2519 // Loading from a constant address. 2520 2521 // If this address fits entirely in a 16-bit sext immediate field, codegen 2522 // this as "d, 0" 2523 int16_t Imm; 2524 if (isIntS16Immediate(CN, Imm) && 2525 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2526 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2527 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2528 CN->getValueType(0)); 2529 return true; 2530 } 2531 2532 // Handle 32-bit sext immediates with LIS + addr mode. 2533 if ((CN->getValueType(0) == MVT::i32 || 2534 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2535 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2536 int Addr = (int)CN->getZExtValue(); 2537 2538 // Otherwise, break this down into an LIS + disp. 2539 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2540 2541 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2542 MVT::i32); 2543 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2544 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2545 return true; 2546 } 2547 } 2548 2549 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2550 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2551 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2552 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2553 } else 2554 Base = N; 2555 return true; // [r+0] 2556 } 2557 2558 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2559 /// represented as an indexed [r+r] operation. 2560 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2561 SDValue &Index, 2562 SelectionDAG &DAG) const { 2563 // Check to see if we can easily represent this as an [r+r] address. This 2564 // will fail if it thinks that the address is more profitably represented as 2565 // reg+imm, e.g. where imm = 0. 2566 if (SelectAddressRegReg(N, Base, Index, DAG)) 2567 return true; 2568 2569 // If the address is the result of an add, we will utilize the fact that the 2570 // address calculation includes an implicit add. However, we can reduce 2571 // register pressure if we do not materialize a constant just for use as the 2572 // index register. We only get rid of the add if it is not an add of a 2573 // value and a 16-bit signed constant and both have a single use. 2574 int16_t imm = 0; 2575 if (N.getOpcode() == ISD::ADD && 2576 (!isIntS16Immediate(N.getOperand(1), imm) || 2577 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2578 Base = N.getOperand(0); 2579 Index = N.getOperand(1); 2580 return true; 2581 } 2582 2583 // Otherwise, do it the hard way, using R0 as the base register. 2584 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2585 N.getValueType()); 2586 Index = N; 2587 return true; 2588 } 2589 2590 /// Returns true if this address is a PC Relative address. 2591 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2592 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2593 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2594 // This is a materialize PC Relative node. Always select this as PC Relative. 2595 Base = N; 2596 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2597 return true; 2598 if (ConstantPoolSDNode *CPN = dyn_cast<ConstantPoolSDNode>(N)) 2599 if (CPN->getTargetFlags() & PPCII::MO_PCREL_FLAG) 2600 return true; 2601 if (GlobalAddressSDNode *GAN = dyn_cast<GlobalAddressSDNode>(N)) 2602 if (GAN->getTargetFlags() & PPCII::MO_PCREL_FLAG) 2603 return true; 2604 return false; 2605 } 2606 2607 /// Returns true if we should use a direct load into vector instruction 2608 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2609 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2610 2611 // If there are any other uses other than scalar to vector, then we should 2612 // keep it as a scalar load -> direct move pattern to prevent multiple 2613 // loads. 2614 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2615 if (!LD) 2616 return false; 2617 2618 EVT MemVT = LD->getMemoryVT(); 2619 if (!MemVT.isSimple()) 2620 return false; 2621 switch(MemVT.getSimpleVT().SimpleTy) { 2622 case MVT::i64: 2623 break; 2624 case MVT::i32: 2625 if (!ST.hasP8Vector()) 2626 return false; 2627 break; 2628 case MVT::i16: 2629 case MVT::i8: 2630 if (!ST.hasP9Vector()) 2631 return false; 2632 break; 2633 default: 2634 return false; 2635 } 2636 2637 SDValue LoadedVal(N, 0); 2638 if (!LoadedVal.hasOneUse()) 2639 return false; 2640 2641 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2642 UI != UE; ++UI) 2643 if (UI.getUse().get().getResNo() == 0 && 2644 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2645 return false; 2646 2647 return true; 2648 } 2649 2650 /// getPreIndexedAddressParts - returns true by value, base pointer and 2651 /// offset pointer and addressing mode by reference if the node's address 2652 /// can be legally represented as pre-indexed load / store address. 2653 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2654 SDValue &Offset, 2655 ISD::MemIndexedMode &AM, 2656 SelectionDAG &DAG) const { 2657 if (DisablePPCPreinc) return false; 2658 2659 bool isLoad = true; 2660 SDValue Ptr; 2661 EVT VT; 2662 unsigned Alignment; 2663 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2664 Ptr = LD->getBasePtr(); 2665 VT = LD->getMemoryVT(); 2666 Alignment = LD->getAlignment(); 2667 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2668 Ptr = ST->getBasePtr(); 2669 VT = ST->getMemoryVT(); 2670 Alignment = ST->getAlignment(); 2671 isLoad = false; 2672 } else 2673 return false; 2674 2675 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2676 // instructions because we can fold these into a more efficient instruction 2677 // instead, (such as LXSD). 2678 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2679 return false; 2680 } 2681 2682 // PowerPC doesn't have preinc load/store instructions for vectors (except 2683 // for QPX, which does have preinc r+r forms). 2684 if (VT.isVector()) { 2685 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2686 return false; 2687 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2688 AM = ISD::PRE_INC; 2689 return true; 2690 } 2691 } 2692 2693 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2694 // Common code will reject creating a pre-inc form if the base pointer 2695 // is a frame index, or if N is a store and the base pointer is either 2696 // the same as or a predecessor of the value being stored. Check for 2697 // those situations here, and try with swapped Base/Offset instead. 2698 bool Swap = false; 2699 2700 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2701 Swap = true; 2702 else if (!isLoad) { 2703 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2704 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2705 Swap = true; 2706 } 2707 2708 if (Swap) 2709 std::swap(Base, Offset); 2710 2711 AM = ISD::PRE_INC; 2712 return true; 2713 } 2714 2715 // LDU/STU can only handle immediates that are a multiple of 4. 2716 if (VT != MVT::i64) { 2717 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2718 return false; 2719 } else { 2720 // LDU/STU need an address with at least 4-byte alignment. 2721 if (Alignment < 4) 2722 return false; 2723 2724 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2725 return false; 2726 } 2727 2728 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2729 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2730 // sext i32 to i64 when addr mode is r+i. 2731 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2732 LD->getExtensionType() == ISD::SEXTLOAD && 2733 isa<ConstantSDNode>(Offset)) 2734 return false; 2735 } 2736 2737 AM = ISD::PRE_INC; 2738 return true; 2739 } 2740 2741 //===----------------------------------------------------------------------===// 2742 // LowerOperation implementation 2743 //===----------------------------------------------------------------------===// 2744 2745 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2746 /// and LoOpFlags to the target MO flags. 2747 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2748 unsigned &HiOpFlags, unsigned &LoOpFlags, 2749 const GlobalValue *GV = nullptr) { 2750 HiOpFlags = PPCII::MO_HA; 2751 LoOpFlags = PPCII::MO_LO; 2752 2753 // Don't use the pic base if not in PIC relocation model. 2754 if (IsPIC) { 2755 HiOpFlags |= PPCII::MO_PIC_FLAG; 2756 LoOpFlags |= PPCII::MO_PIC_FLAG; 2757 } 2758 } 2759 2760 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2761 SelectionDAG &DAG) { 2762 SDLoc DL(HiPart); 2763 EVT PtrVT = HiPart.getValueType(); 2764 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2765 2766 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2767 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2768 2769 // With PIC, the first instruction is actually "GR+hi(&G)". 2770 if (isPIC) 2771 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2772 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2773 2774 // Generate non-pic code that has direct accesses to the constant pool. 2775 // The address of the global is just (hi(&g)+lo(&g)). 2776 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2777 } 2778 2779 static void setUsesTOCBasePtr(MachineFunction &MF) { 2780 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2781 FuncInfo->setUsesTOCBasePtr(); 2782 } 2783 2784 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2785 setUsesTOCBasePtr(DAG.getMachineFunction()); 2786 } 2787 2788 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2789 SDValue GA) const { 2790 const bool Is64Bit = Subtarget.isPPC64(); 2791 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2792 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2793 : Subtarget.isAIXABI() 2794 ? DAG.getRegister(PPC::R2, VT) 2795 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2796 SDValue Ops[] = { GA, Reg }; 2797 return DAG.getMemIntrinsicNode( 2798 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2799 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2800 MachineMemOperand::MOLoad); 2801 } 2802 2803 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2804 SelectionDAG &DAG) const { 2805 EVT PtrVT = Op.getValueType(); 2806 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2807 const Constant *C = CP->getConstVal(); 2808 2809 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2810 // The actual address of the GlobalValue is stored in the TOC. 2811 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2812 if (Subtarget.hasPCRelativeMemops()) { 2813 SDLoc DL(CP); 2814 EVT Ty = getPointerTy(DAG.getDataLayout()); 2815 SDValue ConstPool = DAG.getTargetConstantPool(C, Ty, 2816 CP->getAlignment(), 2817 CP->getOffset(), 2818 PPCII::MO_PCREL_FLAG); 2819 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2820 } 2821 setUsesTOCBasePtr(DAG); 2822 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2823 return getTOCEntry(DAG, SDLoc(CP), GA); 2824 } 2825 2826 unsigned MOHiFlag, MOLoFlag; 2827 bool IsPIC = isPositionIndependent(); 2828 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2829 2830 if (IsPIC && Subtarget.isSVR4ABI()) { 2831 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2832 PPCII::MO_PIC_FLAG); 2833 return getTOCEntry(DAG, SDLoc(CP), GA); 2834 } 2835 2836 SDValue CPIHi = 2837 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2838 SDValue CPILo = 2839 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2840 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2841 } 2842 2843 // For 64-bit PowerPC, prefer the more compact relative encodings. 2844 // This trades 32 bits per jump table entry for one or two instructions 2845 // on the jump site. 2846 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2847 if (isJumpTableRelative()) 2848 return MachineJumpTableInfo::EK_LabelDifference32; 2849 2850 return TargetLowering::getJumpTableEncoding(); 2851 } 2852 2853 bool PPCTargetLowering::isJumpTableRelative() const { 2854 if (UseAbsoluteJumpTables) 2855 return false; 2856 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2857 return true; 2858 return TargetLowering::isJumpTableRelative(); 2859 } 2860 2861 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2862 SelectionDAG &DAG) const { 2863 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2864 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2865 2866 switch (getTargetMachine().getCodeModel()) { 2867 case CodeModel::Small: 2868 case CodeModel::Medium: 2869 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2870 default: 2871 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2872 getPointerTy(DAG.getDataLayout())); 2873 } 2874 } 2875 2876 const MCExpr * 2877 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2878 unsigned JTI, 2879 MCContext &Ctx) const { 2880 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2881 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2882 2883 switch (getTargetMachine().getCodeModel()) { 2884 case CodeModel::Small: 2885 case CodeModel::Medium: 2886 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2887 default: 2888 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2889 } 2890 } 2891 2892 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2893 EVT PtrVT = Op.getValueType(); 2894 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2895 2896 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2897 // The actual address of the GlobalValue is stored in the TOC. 2898 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2899 setUsesTOCBasePtr(DAG); 2900 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2901 return getTOCEntry(DAG, SDLoc(JT), GA); 2902 } 2903 2904 unsigned MOHiFlag, MOLoFlag; 2905 bool IsPIC = isPositionIndependent(); 2906 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2907 2908 if (IsPIC && Subtarget.isSVR4ABI()) { 2909 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2910 PPCII::MO_PIC_FLAG); 2911 return getTOCEntry(DAG, SDLoc(GA), GA); 2912 } 2913 2914 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2915 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2916 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2917 } 2918 2919 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2920 SelectionDAG &DAG) const { 2921 EVT PtrVT = Op.getValueType(); 2922 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2923 const BlockAddress *BA = BASDN->getBlockAddress(); 2924 2925 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2926 // The actual BlockAddress is stored in the TOC. 2927 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2928 setUsesTOCBasePtr(DAG); 2929 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2930 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2931 } 2932 2933 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2934 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2935 return getTOCEntry( 2936 DAG, SDLoc(BASDN), 2937 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2938 2939 unsigned MOHiFlag, MOLoFlag; 2940 bool IsPIC = isPositionIndependent(); 2941 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2942 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2943 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2944 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2945 } 2946 2947 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2948 SelectionDAG &DAG) const { 2949 // FIXME: TLS addresses currently use medium model code sequences, 2950 // which is the most useful form. Eventually support for small and 2951 // large models could be added if users need it, at the cost of 2952 // additional complexity. 2953 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2954 if (DAG.getTarget().useEmulatedTLS()) 2955 return LowerToTLSEmulatedModel(GA, DAG); 2956 2957 SDLoc dl(GA); 2958 const GlobalValue *GV = GA->getGlobal(); 2959 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2960 bool is64bit = Subtarget.isPPC64(); 2961 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2962 PICLevel::Level picLevel = M->getPICLevel(); 2963 2964 const TargetMachine &TM = getTargetMachine(); 2965 TLSModel::Model Model = TM.getTLSModel(GV); 2966 2967 if (Model == TLSModel::LocalExec) { 2968 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2969 PPCII::MO_TPREL_HA); 2970 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2971 PPCII::MO_TPREL_LO); 2972 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2973 : DAG.getRegister(PPC::R2, MVT::i32); 2974 2975 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2976 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2977 } 2978 2979 if (Model == TLSModel::InitialExec) { 2980 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2981 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2982 PPCII::MO_TLS); 2983 SDValue GOTPtr; 2984 if (is64bit) { 2985 setUsesTOCBasePtr(DAG); 2986 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2987 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2988 PtrVT, GOTReg, TGA); 2989 } else { 2990 if (!TM.isPositionIndependent()) 2991 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2992 else if (picLevel == PICLevel::SmallPIC) 2993 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2994 else 2995 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2996 } 2997 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2998 PtrVT, TGA, GOTPtr); 2999 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3000 } 3001 3002 if (Model == TLSModel::GeneralDynamic) { 3003 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3004 SDValue GOTPtr; 3005 if (is64bit) { 3006 setUsesTOCBasePtr(DAG); 3007 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3008 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3009 GOTReg, TGA); 3010 } else { 3011 if (picLevel == PICLevel::SmallPIC) 3012 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3013 else 3014 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3015 } 3016 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3017 GOTPtr, TGA, TGA); 3018 } 3019 3020 if (Model == TLSModel::LocalDynamic) { 3021 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3022 SDValue GOTPtr; 3023 if (is64bit) { 3024 setUsesTOCBasePtr(DAG); 3025 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3026 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3027 GOTReg, TGA); 3028 } else { 3029 if (picLevel == PICLevel::SmallPIC) 3030 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3031 else 3032 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3033 } 3034 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3035 PtrVT, GOTPtr, TGA, TGA); 3036 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3037 PtrVT, TLSAddr, TGA); 3038 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3039 } 3040 3041 llvm_unreachable("Unknown TLS model!"); 3042 } 3043 3044 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3045 SelectionDAG &DAG) const { 3046 EVT PtrVT = Op.getValueType(); 3047 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3048 SDLoc DL(GSDN); 3049 const GlobalValue *GV = GSDN->getGlobal(); 3050 3051 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3052 // The actual address of the GlobalValue is stored in the TOC. 3053 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3054 if (!isAccessedAsGotIndirect(Op) && Subtarget.isUsingPCRelativeCalls()) { 3055 EVT Ty = getPointerTy(DAG.getDataLayout()); 3056 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3057 PPCII::MO_PCREL_FLAG); 3058 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3059 } 3060 setUsesTOCBasePtr(DAG); 3061 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3062 return getTOCEntry(DAG, DL, GA); 3063 } 3064 3065 unsigned MOHiFlag, MOLoFlag; 3066 bool IsPIC = isPositionIndependent(); 3067 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3068 3069 if (IsPIC && Subtarget.isSVR4ABI()) { 3070 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3071 GSDN->getOffset(), 3072 PPCII::MO_PIC_FLAG); 3073 return getTOCEntry(DAG, DL, GA); 3074 } 3075 3076 SDValue GAHi = 3077 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3078 SDValue GALo = 3079 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3080 3081 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3082 } 3083 3084 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3085 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3086 SDLoc dl(Op); 3087 3088 if (Op.getValueType() == MVT::v2i64) { 3089 // When the operands themselves are v2i64 values, we need to do something 3090 // special because VSX has no underlying comparison operations for these. 3091 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3092 // Equality can be handled by casting to the legal type for Altivec 3093 // comparisons, everything else needs to be expanded. 3094 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3095 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3096 DAG.getSetCC(dl, MVT::v4i32, 3097 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3098 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3099 CC)); 3100 } 3101 3102 return SDValue(); 3103 } 3104 3105 // We handle most of these in the usual way. 3106 return Op; 3107 } 3108 3109 // If we're comparing for equality to zero, expose the fact that this is 3110 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3111 // fold the new nodes. 3112 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3113 return V; 3114 3115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3116 // Leave comparisons against 0 and -1 alone for now, since they're usually 3117 // optimized. FIXME: revisit this when we can custom lower all setcc 3118 // optimizations. 3119 if (C->isAllOnesValue() || C->isNullValue()) 3120 return SDValue(); 3121 } 3122 3123 // If we have an integer seteq/setne, turn it into a compare against zero 3124 // by xor'ing the rhs with the lhs, which is faster than setting a 3125 // condition register, reading it back out, and masking the correct bit. The 3126 // normal approach here uses sub to do this instead of xor. Using xor exposes 3127 // the result to other bit-twiddling opportunities. 3128 EVT LHSVT = Op.getOperand(0).getValueType(); 3129 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3130 EVT VT = Op.getValueType(); 3131 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3132 Op.getOperand(1)); 3133 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3134 } 3135 return SDValue(); 3136 } 3137 3138 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3139 SDNode *Node = Op.getNode(); 3140 EVT VT = Node->getValueType(0); 3141 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3142 SDValue InChain = Node->getOperand(0); 3143 SDValue VAListPtr = Node->getOperand(1); 3144 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3145 SDLoc dl(Node); 3146 3147 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3148 3149 // gpr_index 3150 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3151 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3152 InChain = GprIndex.getValue(1); 3153 3154 if (VT == MVT::i64) { 3155 // Check if GprIndex is even 3156 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3157 DAG.getConstant(1, dl, MVT::i32)); 3158 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3159 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3160 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3161 DAG.getConstant(1, dl, MVT::i32)); 3162 // Align GprIndex to be even if it isn't 3163 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3164 GprIndex); 3165 } 3166 3167 // fpr index is 1 byte after gpr 3168 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3169 DAG.getConstant(1, dl, MVT::i32)); 3170 3171 // fpr 3172 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3173 FprPtr, MachinePointerInfo(SV), MVT::i8); 3174 InChain = FprIndex.getValue(1); 3175 3176 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3177 DAG.getConstant(8, dl, MVT::i32)); 3178 3179 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3180 DAG.getConstant(4, dl, MVT::i32)); 3181 3182 // areas 3183 SDValue OverflowArea = 3184 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3185 InChain = OverflowArea.getValue(1); 3186 3187 SDValue RegSaveArea = 3188 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3189 InChain = RegSaveArea.getValue(1); 3190 3191 // select overflow_area if index > 8 3192 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3193 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3194 3195 // adjustment constant gpr_index * 4/8 3196 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3197 VT.isInteger() ? GprIndex : FprIndex, 3198 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3199 MVT::i32)); 3200 3201 // OurReg = RegSaveArea + RegConstant 3202 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3203 RegConstant); 3204 3205 // Floating types are 32 bytes into RegSaveArea 3206 if (VT.isFloatingPoint()) 3207 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3208 DAG.getConstant(32, dl, MVT::i32)); 3209 3210 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3211 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3212 VT.isInteger() ? GprIndex : FprIndex, 3213 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3214 MVT::i32)); 3215 3216 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3217 VT.isInteger() ? VAListPtr : FprPtr, 3218 MachinePointerInfo(SV), MVT::i8); 3219 3220 // determine if we should load from reg_save_area or overflow_area 3221 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3222 3223 // increase overflow_area by 4/8 if gpr/fpr > 8 3224 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3225 DAG.getConstant(VT.isInteger() ? 4 : 8, 3226 dl, MVT::i32)); 3227 3228 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3229 OverflowAreaPlusN); 3230 3231 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3232 MachinePointerInfo(), MVT::i32); 3233 3234 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3235 } 3236 3237 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3238 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3239 3240 // We have to copy the entire va_list struct: 3241 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3242 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3243 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3244 false, true, false, MachinePointerInfo(), 3245 MachinePointerInfo()); 3246 } 3247 3248 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3249 SelectionDAG &DAG) const { 3250 if (Subtarget.isAIXABI()) 3251 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3252 3253 return Op.getOperand(0); 3254 } 3255 3256 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3257 SelectionDAG &DAG) const { 3258 if (Subtarget.isAIXABI()) 3259 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3260 3261 SDValue Chain = Op.getOperand(0); 3262 SDValue Trmp = Op.getOperand(1); // trampoline 3263 SDValue FPtr = Op.getOperand(2); // nested function 3264 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3265 SDLoc dl(Op); 3266 3267 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3268 bool isPPC64 = (PtrVT == MVT::i64); 3269 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3270 3271 TargetLowering::ArgListTy Args; 3272 TargetLowering::ArgListEntry Entry; 3273 3274 Entry.Ty = IntPtrTy; 3275 Entry.Node = Trmp; Args.push_back(Entry); 3276 3277 // TrampSize == (isPPC64 ? 48 : 40); 3278 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3279 isPPC64 ? MVT::i64 : MVT::i32); 3280 Args.push_back(Entry); 3281 3282 Entry.Node = FPtr; Args.push_back(Entry); 3283 Entry.Node = Nest; Args.push_back(Entry); 3284 3285 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3286 TargetLowering::CallLoweringInfo CLI(DAG); 3287 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3288 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3289 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3290 3291 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3292 return CallResult.second; 3293 } 3294 3295 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3296 MachineFunction &MF = DAG.getMachineFunction(); 3297 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3298 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3299 3300 SDLoc dl(Op); 3301 3302 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3303 // vastart just stores the address of the VarArgsFrameIndex slot into the 3304 // memory location argument. 3305 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3306 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3307 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3308 MachinePointerInfo(SV)); 3309 } 3310 3311 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3312 // We suppose the given va_list is already allocated. 3313 // 3314 // typedef struct { 3315 // char gpr; /* index into the array of 8 GPRs 3316 // * stored in the register save area 3317 // * gpr=0 corresponds to r3, 3318 // * gpr=1 to r4, etc. 3319 // */ 3320 // char fpr; /* index into the array of 8 FPRs 3321 // * stored in the register save area 3322 // * fpr=0 corresponds to f1, 3323 // * fpr=1 to f2, etc. 3324 // */ 3325 // char *overflow_arg_area; 3326 // /* location on stack that holds 3327 // * the next overflow argument 3328 // */ 3329 // char *reg_save_area; 3330 // /* where r3:r10 and f1:f8 (if saved) 3331 // * are stored 3332 // */ 3333 // } va_list[1]; 3334 3335 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3336 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3337 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3338 PtrVT); 3339 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3340 PtrVT); 3341 3342 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3343 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3344 3345 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3346 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3347 3348 uint64_t FPROffset = 1; 3349 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3350 3351 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3352 3353 // Store first byte : number of int regs 3354 SDValue firstStore = 3355 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3356 MachinePointerInfo(SV), MVT::i8); 3357 uint64_t nextOffset = FPROffset; 3358 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3359 ConstFPROffset); 3360 3361 // Store second byte : number of float regs 3362 SDValue secondStore = 3363 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3364 MachinePointerInfo(SV, nextOffset), MVT::i8); 3365 nextOffset += StackOffset; 3366 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3367 3368 // Store second word : arguments given on stack 3369 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3370 MachinePointerInfo(SV, nextOffset)); 3371 nextOffset += FrameOffset; 3372 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3373 3374 // Store third word : arguments given in registers 3375 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3376 MachinePointerInfo(SV, nextOffset)); 3377 } 3378 3379 /// FPR - The set of FP registers that should be allocated for arguments 3380 /// on Darwin and AIX. 3381 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3382 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3383 PPC::F11, PPC::F12, PPC::F13}; 3384 3385 /// QFPR - The set of QPX registers that should be allocated for arguments. 3386 static const MCPhysReg QFPR[] = { 3387 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3388 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3389 3390 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3391 /// the stack. 3392 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3393 unsigned PtrByteSize) { 3394 unsigned ArgSize = ArgVT.getStoreSize(); 3395 if (Flags.isByVal()) 3396 ArgSize = Flags.getByValSize(); 3397 3398 // Round up to multiples of the pointer size, except for array members, 3399 // which are always packed. 3400 if (!Flags.isInConsecutiveRegs()) 3401 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3402 3403 return ArgSize; 3404 } 3405 3406 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3407 /// on the stack. 3408 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3409 ISD::ArgFlagsTy Flags, 3410 unsigned PtrByteSize) { 3411 Align Alignment(PtrByteSize); 3412 3413 // Altivec parameters are padded to a 16 byte boundary. 3414 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3415 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3416 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3417 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3418 Alignment = Align(16); 3419 // QPX vector types stored in double-precision are padded to a 32 byte 3420 // boundary. 3421 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3422 Alignment = Align(32); 3423 3424 // ByVal parameters are aligned as requested. 3425 if (Flags.isByVal()) { 3426 auto BVAlign = Flags.getNonZeroByValAlign(); 3427 if (BVAlign > PtrByteSize) { 3428 if (BVAlign.value() % PtrByteSize != 0) 3429 llvm_unreachable( 3430 "ByVal alignment is not a multiple of the pointer size"); 3431 3432 Alignment = BVAlign; 3433 } 3434 } 3435 3436 // Array members are always packed to their original alignment. 3437 if (Flags.isInConsecutiveRegs()) { 3438 // If the array member was split into multiple registers, the first 3439 // needs to be aligned to the size of the full type. (Except for 3440 // ppcf128, which is only aligned as its f64 components.) 3441 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3442 Alignment = Align(OrigVT.getStoreSize()); 3443 else 3444 Alignment = Align(ArgVT.getStoreSize()); 3445 } 3446 3447 return Alignment; 3448 } 3449 3450 /// CalculateStackSlotUsed - Return whether this argument will use its 3451 /// stack slot (instead of being passed in registers). ArgOffset, 3452 /// AvailableFPRs, and AvailableVRs must hold the current argument 3453 /// position, and will be updated to account for this argument. 3454 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3455 ISD::ArgFlagsTy Flags, 3456 unsigned PtrByteSize, 3457 unsigned LinkageSize, 3458 unsigned ParamAreaSize, 3459 unsigned &ArgOffset, 3460 unsigned &AvailableFPRs, 3461 unsigned &AvailableVRs, bool HasQPX) { 3462 bool UseMemory = false; 3463 3464 // Respect alignment of argument on the stack. 3465 Align Alignment = 3466 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3467 ArgOffset = alignTo(ArgOffset, Alignment); 3468 // If there's no space left in the argument save area, we must 3469 // use memory (this check also catches zero-sized arguments). 3470 if (ArgOffset >= LinkageSize + ParamAreaSize) 3471 UseMemory = true; 3472 3473 // Allocate argument on the stack. 3474 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3475 if (Flags.isInConsecutiveRegsLast()) 3476 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3477 // If we overran the argument save area, we must use memory 3478 // (this check catches arguments passed partially in memory) 3479 if (ArgOffset > LinkageSize + ParamAreaSize) 3480 UseMemory = true; 3481 3482 // However, if the argument is actually passed in an FPR or a VR, 3483 // we don't use memory after all. 3484 if (!Flags.isByVal()) { 3485 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3486 // QPX registers overlap with the scalar FP registers. 3487 (HasQPX && (ArgVT == MVT::v4f32 || 3488 ArgVT == MVT::v4f64 || 3489 ArgVT == MVT::v4i1))) 3490 if (AvailableFPRs > 0) { 3491 --AvailableFPRs; 3492 return false; 3493 } 3494 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3495 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3496 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3497 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3498 if (AvailableVRs > 0) { 3499 --AvailableVRs; 3500 return false; 3501 } 3502 } 3503 3504 return UseMemory; 3505 } 3506 3507 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3508 /// ensure minimum alignment required for target. 3509 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3510 unsigned NumBytes) { 3511 return alignTo(NumBytes, Lowering->getStackAlign()); 3512 } 3513 3514 SDValue PPCTargetLowering::LowerFormalArguments( 3515 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3516 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3517 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3518 if (Subtarget.isAIXABI()) 3519 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3520 InVals); 3521 if (Subtarget.is64BitELFABI()) 3522 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3523 InVals); 3524 if (Subtarget.is32BitELFABI()) 3525 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3526 InVals); 3527 3528 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3529 InVals); 3530 } 3531 3532 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3533 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3534 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3535 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3536 3537 // 32-bit SVR4 ABI Stack Frame Layout: 3538 // +-----------------------------------+ 3539 // +--> | Back chain | 3540 // | +-----------------------------------+ 3541 // | | Floating-point register save area | 3542 // | +-----------------------------------+ 3543 // | | General register save area | 3544 // | +-----------------------------------+ 3545 // | | CR save word | 3546 // | +-----------------------------------+ 3547 // | | VRSAVE save word | 3548 // | +-----------------------------------+ 3549 // | | Alignment padding | 3550 // | +-----------------------------------+ 3551 // | | Vector register save area | 3552 // | +-----------------------------------+ 3553 // | | Local variable space | 3554 // | +-----------------------------------+ 3555 // | | Parameter list area | 3556 // | +-----------------------------------+ 3557 // | | LR save word | 3558 // | +-----------------------------------+ 3559 // SP--> +--- | Back chain | 3560 // +-----------------------------------+ 3561 // 3562 // Specifications: 3563 // System V Application Binary Interface PowerPC Processor Supplement 3564 // AltiVec Technology Programming Interface Manual 3565 3566 MachineFunction &MF = DAG.getMachineFunction(); 3567 MachineFrameInfo &MFI = MF.getFrameInfo(); 3568 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3569 3570 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3571 // Potential tail calls could cause overwriting of argument stack slots. 3572 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3573 (CallConv == CallingConv::Fast)); 3574 unsigned PtrByteSize = 4; 3575 3576 // Assign locations to all of the incoming arguments. 3577 SmallVector<CCValAssign, 16> ArgLocs; 3578 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3579 *DAG.getContext()); 3580 3581 // Reserve space for the linkage area on the stack. 3582 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3583 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3584 if (useSoftFloat()) 3585 CCInfo.PreAnalyzeFormalArguments(Ins); 3586 3587 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3588 CCInfo.clearWasPPCF128(); 3589 3590 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3591 CCValAssign &VA = ArgLocs[i]; 3592 3593 // Arguments stored in registers. 3594 if (VA.isRegLoc()) { 3595 const TargetRegisterClass *RC; 3596 EVT ValVT = VA.getValVT(); 3597 3598 switch (ValVT.getSimpleVT().SimpleTy) { 3599 default: 3600 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3601 case MVT::i1: 3602 case MVT::i32: 3603 RC = &PPC::GPRCRegClass; 3604 break; 3605 case MVT::f32: 3606 if (Subtarget.hasP8Vector()) 3607 RC = &PPC::VSSRCRegClass; 3608 else if (Subtarget.hasSPE()) 3609 RC = &PPC::GPRCRegClass; 3610 else 3611 RC = &PPC::F4RCRegClass; 3612 break; 3613 case MVT::f64: 3614 if (Subtarget.hasVSX()) 3615 RC = &PPC::VSFRCRegClass; 3616 else if (Subtarget.hasSPE()) 3617 // SPE passes doubles in GPR pairs. 3618 RC = &PPC::GPRCRegClass; 3619 else 3620 RC = &PPC::F8RCRegClass; 3621 break; 3622 case MVT::v16i8: 3623 case MVT::v8i16: 3624 case MVT::v4i32: 3625 RC = &PPC::VRRCRegClass; 3626 break; 3627 case MVT::v4f32: 3628 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3629 break; 3630 case MVT::v2f64: 3631 case MVT::v2i64: 3632 RC = &PPC::VRRCRegClass; 3633 break; 3634 case MVT::v4f64: 3635 RC = &PPC::QFRCRegClass; 3636 break; 3637 case MVT::v4i1: 3638 RC = &PPC::QBRCRegClass; 3639 break; 3640 } 3641 3642 SDValue ArgValue; 3643 // Transform the arguments stored in physical registers into 3644 // virtual ones. 3645 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3646 assert(i + 1 < e && "No second half of double precision argument"); 3647 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3648 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3649 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3650 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3651 if (!Subtarget.isLittleEndian()) 3652 std::swap (ArgValueLo, ArgValueHi); 3653 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3654 ArgValueHi); 3655 } else { 3656 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3657 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3658 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3659 if (ValVT == MVT::i1) 3660 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3661 } 3662 3663 InVals.push_back(ArgValue); 3664 } else { 3665 // Argument stored in memory. 3666 assert(VA.isMemLoc()); 3667 3668 // Get the extended size of the argument type in stack 3669 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3670 // Get the actual size of the argument type 3671 unsigned ObjSize = VA.getValVT().getStoreSize(); 3672 unsigned ArgOffset = VA.getLocMemOffset(); 3673 // Stack objects in PPC32 are right justified. 3674 ArgOffset += ArgSize - ObjSize; 3675 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3676 3677 // Create load nodes to retrieve arguments from the stack. 3678 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3679 InVals.push_back( 3680 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3681 } 3682 } 3683 3684 // Assign locations to all of the incoming aggregate by value arguments. 3685 // Aggregates passed by value are stored in the local variable space of the 3686 // caller's stack frame, right above the parameter list area. 3687 SmallVector<CCValAssign, 16> ByValArgLocs; 3688 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3689 ByValArgLocs, *DAG.getContext()); 3690 3691 // Reserve stack space for the allocations in CCInfo. 3692 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3693 3694 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3695 3696 // Area that is at least reserved in the caller of this function. 3697 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3698 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3699 3700 // Set the size that is at least reserved in caller of this function. Tail 3701 // call optimized function's reserved stack space needs to be aligned so that 3702 // taking the difference between two stack areas will result in an aligned 3703 // stack. 3704 MinReservedArea = 3705 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3706 FuncInfo->setMinReservedArea(MinReservedArea); 3707 3708 SmallVector<SDValue, 8> MemOps; 3709 3710 // If the function takes variable number of arguments, make a frame index for 3711 // the start of the first vararg value... for expansion of llvm.va_start. 3712 if (isVarArg) { 3713 static const MCPhysReg GPArgRegs[] = { 3714 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3715 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3716 }; 3717 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3718 3719 static const MCPhysReg FPArgRegs[] = { 3720 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3721 PPC::F8 3722 }; 3723 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3724 3725 if (useSoftFloat() || hasSPE()) 3726 NumFPArgRegs = 0; 3727 3728 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3729 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3730 3731 // Make room for NumGPArgRegs and NumFPArgRegs. 3732 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3733 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3734 3735 FuncInfo->setVarArgsStackOffset( 3736 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3737 CCInfo.getNextStackOffset(), true)); 3738 3739 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3740 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3741 3742 // The fixed integer arguments of a variadic function are stored to the 3743 // VarArgsFrameIndex on the stack so that they may be loaded by 3744 // dereferencing the result of va_next. 3745 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3746 // Get an existing live-in vreg, or add a new one. 3747 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3748 if (!VReg) 3749 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3750 3751 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3752 SDValue Store = 3753 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3754 MemOps.push_back(Store); 3755 // Increment the address by four for the next argument to store 3756 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3757 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3758 } 3759 3760 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3761 // is set. 3762 // The double arguments are stored to the VarArgsFrameIndex 3763 // on the stack. 3764 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3765 // Get an existing live-in vreg, or add a new one. 3766 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3767 if (!VReg) 3768 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3769 3770 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3771 SDValue Store = 3772 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3773 MemOps.push_back(Store); 3774 // Increment the address by eight for the next argument to store 3775 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3776 PtrVT); 3777 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3778 } 3779 } 3780 3781 if (!MemOps.empty()) 3782 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3783 3784 return Chain; 3785 } 3786 3787 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3788 // value to MVT::i64 and then truncate to the correct register size. 3789 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3790 EVT ObjectVT, SelectionDAG &DAG, 3791 SDValue ArgVal, 3792 const SDLoc &dl) const { 3793 if (Flags.isSExt()) 3794 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3795 DAG.getValueType(ObjectVT)); 3796 else if (Flags.isZExt()) 3797 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3798 DAG.getValueType(ObjectVT)); 3799 3800 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3801 } 3802 3803 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3804 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3805 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3806 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3807 // TODO: add description of PPC stack frame format, or at least some docs. 3808 // 3809 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3810 bool isLittleEndian = Subtarget.isLittleEndian(); 3811 MachineFunction &MF = DAG.getMachineFunction(); 3812 MachineFrameInfo &MFI = MF.getFrameInfo(); 3813 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3814 3815 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3816 "fastcc not supported on varargs functions"); 3817 3818 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3819 // Potential tail calls could cause overwriting of argument stack slots. 3820 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3821 (CallConv == CallingConv::Fast)); 3822 unsigned PtrByteSize = 8; 3823 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3824 3825 static const MCPhysReg GPR[] = { 3826 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3827 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3828 }; 3829 static const MCPhysReg VR[] = { 3830 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3831 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3832 }; 3833 3834 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3835 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3836 const unsigned Num_VR_Regs = array_lengthof(VR); 3837 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3838 3839 // Do a first pass over the arguments to determine whether the ABI 3840 // guarantees that our caller has allocated the parameter save area 3841 // on its stack frame. In the ELFv1 ABI, this is always the case; 3842 // in the ELFv2 ABI, it is true if this is a vararg function or if 3843 // any parameter is located in a stack slot. 3844 3845 bool HasParameterArea = !isELFv2ABI || isVarArg; 3846 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3847 unsigned NumBytes = LinkageSize; 3848 unsigned AvailableFPRs = Num_FPR_Regs; 3849 unsigned AvailableVRs = Num_VR_Regs; 3850 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3851 if (Ins[i].Flags.isNest()) 3852 continue; 3853 3854 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3855 PtrByteSize, LinkageSize, ParamAreaSize, 3856 NumBytes, AvailableFPRs, AvailableVRs, 3857 Subtarget.hasQPX())) 3858 HasParameterArea = true; 3859 } 3860 3861 // Add DAG nodes to load the arguments or copy them out of registers. On 3862 // entry to a function on PPC, the arguments start after the linkage area, 3863 // although the first ones are often in registers. 3864 3865 unsigned ArgOffset = LinkageSize; 3866 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3867 unsigned &QFPR_idx = FPR_idx; 3868 SmallVector<SDValue, 8> MemOps; 3869 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3870 unsigned CurArgIdx = 0; 3871 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3872 SDValue ArgVal; 3873 bool needsLoad = false; 3874 EVT ObjectVT = Ins[ArgNo].VT; 3875 EVT OrigVT = Ins[ArgNo].ArgVT; 3876 unsigned ObjSize = ObjectVT.getStoreSize(); 3877 unsigned ArgSize = ObjSize; 3878 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3879 if (Ins[ArgNo].isOrigArg()) { 3880 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3881 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3882 } 3883 // We re-align the argument offset for each argument, except when using the 3884 // fast calling convention, when we need to make sure we do that only when 3885 // we'll actually use a stack slot. 3886 unsigned CurArgOffset; 3887 Align Alignment; 3888 auto ComputeArgOffset = [&]() { 3889 /* Respect alignment of argument on the stack. */ 3890 Alignment = 3891 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3892 ArgOffset = alignTo(ArgOffset, Alignment); 3893 CurArgOffset = ArgOffset; 3894 }; 3895 3896 if (CallConv != CallingConv::Fast) { 3897 ComputeArgOffset(); 3898 3899 /* Compute GPR index associated with argument offset. */ 3900 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3901 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3902 } 3903 3904 // FIXME the codegen can be much improved in some cases. 3905 // We do not have to keep everything in memory. 3906 if (Flags.isByVal()) { 3907 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3908 3909 if (CallConv == CallingConv::Fast) 3910 ComputeArgOffset(); 3911 3912 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3913 ObjSize = Flags.getByValSize(); 3914 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3915 // Empty aggregate parameters do not take up registers. Examples: 3916 // struct { } a; 3917 // union { } b; 3918 // int c[0]; 3919 // etc. However, we have to provide a place-holder in InVals, so 3920 // pretend we have an 8-byte item at the current address for that 3921 // purpose. 3922 if (!ObjSize) { 3923 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3924 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3925 InVals.push_back(FIN); 3926 continue; 3927 } 3928 3929 // Create a stack object covering all stack doublewords occupied 3930 // by the argument. If the argument is (fully or partially) on 3931 // the stack, or if the argument is fully in registers but the 3932 // caller has allocated the parameter save anyway, we can refer 3933 // directly to the caller's stack frame. Otherwise, create a 3934 // local copy in our own frame. 3935 int FI; 3936 if (HasParameterArea || 3937 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3938 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3939 else 3940 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3941 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3942 3943 // Handle aggregates smaller than 8 bytes. 3944 if (ObjSize < PtrByteSize) { 3945 // The value of the object is its address, which differs from the 3946 // address of the enclosing doubleword on big-endian systems. 3947 SDValue Arg = FIN; 3948 if (!isLittleEndian) { 3949 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3950 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3951 } 3952 InVals.push_back(Arg); 3953 3954 if (GPR_idx != Num_GPR_Regs) { 3955 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3956 FuncInfo->addLiveInAttr(VReg, Flags); 3957 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3958 SDValue Store; 3959 3960 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3961 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3962 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3963 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3964 MachinePointerInfo(&*FuncArg), ObjType); 3965 } else { 3966 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3967 // store the whole register as-is to the parameter save area 3968 // slot. 3969 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3970 MachinePointerInfo(&*FuncArg)); 3971 } 3972 3973 MemOps.push_back(Store); 3974 } 3975 // Whether we copied from a register or not, advance the offset 3976 // into the parameter save area by a full doubleword. 3977 ArgOffset += PtrByteSize; 3978 continue; 3979 } 3980 3981 // The value of the object is its address, which is the address of 3982 // its first stack doubleword. 3983 InVals.push_back(FIN); 3984 3985 // Store whatever pieces of the object are in registers to memory. 3986 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3987 if (GPR_idx == Num_GPR_Regs) 3988 break; 3989 3990 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3991 FuncInfo->addLiveInAttr(VReg, Flags); 3992 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3993 SDValue Addr = FIN; 3994 if (j) { 3995 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3996 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3997 } 3998 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3999 MachinePointerInfo(&*FuncArg, j)); 4000 MemOps.push_back(Store); 4001 ++GPR_idx; 4002 } 4003 ArgOffset += ArgSize; 4004 continue; 4005 } 4006 4007 switch (ObjectVT.getSimpleVT().SimpleTy) { 4008 default: llvm_unreachable("Unhandled argument type!"); 4009 case MVT::i1: 4010 case MVT::i32: 4011 case MVT::i64: 4012 if (Flags.isNest()) { 4013 // The 'nest' parameter, if any, is passed in R11. 4014 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4015 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4016 4017 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4018 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4019 4020 break; 4021 } 4022 4023 // These can be scalar arguments or elements of an integer array type 4024 // passed directly. Clang may use those instead of "byval" aggregate 4025 // types to avoid forcing arguments to memory unnecessarily. 4026 if (GPR_idx != Num_GPR_Regs) { 4027 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4028 FuncInfo->addLiveInAttr(VReg, Flags); 4029 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4030 4031 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4032 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4033 // value to MVT::i64 and then truncate to the correct register size. 4034 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4035 } else { 4036 if (CallConv == CallingConv::Fast) 4037 ComputeArgOffset(); 4038 4039 needsLoad = true; 4040 ArgSize = PtrByteSize; 4041 } 4042 if (CallConv != CallingConv::Fast || needsLoad) 4043 ArgOffset += 8; 4044 break; 4045 4046 case MVT::f32: 4047 case MVT::f64: 4048 // These can be scalar arguments or elements of a float array type 4049 // passed directly. The latter are used to implement ELFv2 homogenous 4050 // float aggregates. 4051 if (FPR_idx != Num_FPR_Regs) { 4052 unsigned VReg; 4053 4054 if (ObjectVT == MVT::f32) 4055 VReg = MF.addLiveIn(FPR[FPR_idx], 4056 Subtarget.hasP8Vector() 4057 ? &PPC::VSSRCRegClass 4058 : &PPC::F4RCRegClass); 4059 else 4060 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4061 ? &PPC::VSFRCRegClass 4062 : &PPC::F8RCRegClass); 4063 4064 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4065 ++FPR_idx; 4066 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4067 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4068 // once we support fp <-> gpr moves. 4069 4070 // This can only ever happen in the presence of f32 array types, 4071 // since otherwise we never run out of FPRs before running out 4072 // of GPRs. 4073 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4074 FuncInfo->addLiveInAttr(VReg, Flags); 4075 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4076 4077 if (ObjectVT == MVT::f32) { 4078 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4079 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4080 DAG.getConstant(32, dl, MVT::i32)); 4081 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4082 } 4083 4084 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4085 } else { 4086 if (CallConv == CallingConv::Fast) 4087 ComputeArgOffset(); 4088 4089 needsLoad = true; 4090 } 4091 4092 // When passing an array of floats, the array occupies consecutive 4093 // space in the argument area; only round up to the next doubleword 4094 // at the end of the array. Otherwise, each float takes 8 bytes. 4095 if (CallConv != CallingConv::Fast || needsLoad) { 4096 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4097 ArgOffset += ArgSize; 4098 if (Flags.isInConsecutiveRegsLast()) 4099 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4100 } 4101 break; 4102 case MVT::v4f32: 4103 case MVT::v4i32: 4104 case MVT::v8i16: 4105 case MVT::v16i8: 4106 case MVT::v2f64: 4107 case MVT::v2i64: 4108 case MVT::v1i128: 4109 case MVT::f128: 4110 if (!Subtarget.hasQPX()) { 4111 // These can be scalar arguments or elements of a vector array type 4112 // passed directly. The latter are used to implement ELFv2 homogenous 4113 // vector aggregates. 4114 if (VR_idx != Num_VR_Regs) { 4115 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4116 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4117 ++VR_idx; 4118 } else { 4119 if (CallConv == CallingConv::Fast) 4120 ComputeArgOffset(); 4121 needsLoad = true; 4122 } 4123 if (CallConv != CallingConv::Fast || needsLoad) 4124 ArgOffset += 16; 4125 break; 4126 } // not QPX 4127 4128 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4129 "Invalid QPX parameter type"); 4130 LLVM_FALLTHROUGH; 4131 4132 case MVT::v4f64: 4133 case MVT::v4i1: 4134 // QPX vectors are treated like their scalar floating-point subregisters 4135 // (except that they're larger). 4136 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4137 if (QFPR_idx != Num_QFPR_Regs) { 4138 const TargetRegisterClass *RC; 4139 switch (ObjectVT.getSimpleVT().SimpleTy) { 4140 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4141 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4142 default: RC = &PPC::QBRCRegClass; break; 4143 } 4144 4145 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4146 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4147 ++QFPR_idx; 4148 } else { 4149 if (CallConv == CallingConv::Fast) 4150 ComputeArgOffset(); 4151 needsLoad = true; 4152 } 4153 if (CallConv != CallingConv::Fast || needsLoad) 4154 ArgOffset += Sz; 4155 break; 4156 } 4157 4158 // We need to load the argument to a virtual register if we determined 4159 // above that we ran out of physical registers of the appropriate type. 4160 if (needsLoad) { 4161 if (ObjSize < ArgSize && !isLittleEndian) 4162 CurArgOffset += ArgSize - ObjSize; 4163 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4164 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4165 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4166 } 4167 4168 InVals.push_back(ArgVal); 4169 } 4170 4171 // Area that is at least reserved in the caller of this function. 4172 unsigned MinReservedArea; 4173 if (HasParameterArea) 4174 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4175 else 4176 MinReservedArea = LinkageSize; 4177 4178 // Set the size that is at least reserved in caller of this function. Tail 4179 // call optimized functions' reserved stack space needs to be aligned so that 4180 // taking the difference between two stack areas will result in an aligned 4181 // stack. 4182 MinReservedArea = 4183 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4184 FuncInfo->setMinReservedArea(MinReservedArea); 4185 4186 // If the function takes variable number of arguments, make a frame index for 4187 // the start of the first vararg value... for expansion of llvm.va_start. 4188 if (isVarArg) { 4189 int Depth = ArgOffset; 4190 4191 FuncInfo->setVarArgsFrameIndex( 4192 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4193 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4194 4195 // If this function is vararg, store any remaining integer argument regs 4196 // to their spots on the stack so that they may be loaded by dereferencing 4197 // the result of va_next. 4198 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4199 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4200 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4201 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4202 SDValue Store = 4203 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4204 MemOps.push_back(Store); 4205 // Increment the address by four for the next argument to store 4206 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4207 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4208 } 4209 } 4210 4211 if (!MemOps.empty()) 4212 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4213 4214 return Chain; 4215 } 4216 4217 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4218 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4219 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4220 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4221 // TODO: add description of PPC stack frame format, or at least some docs. 4222 // 4223 MachineFunction &MF = DAG.getMachineFunction(); 4224 MachineFrameInfo &MFI = MF.getFrameInfo(); 4225 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4226 4227 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4228 bool isPPC64 = PtrVT == MVT::i64; 4229 // Potential tail calls could cause overwriting of argument stack slots. 4230 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4231 (CallConv == CallingConv::Fast)); 4232 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4233 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4234 unsigned ArgOffset = LinkageSize; 4235 // Area that is at least reserved in caller of this function. 4236 unsigned MinReservedArea = ArgOffset; 4237 4238 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4239 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4240 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4241 }; 4242 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4243 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4244 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4245 }; 4246 static const MCPhysReg VR[] = { 4247 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4248 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4249 }; 4250 4251 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4252 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4253 const unsigned Num_VR_Regs = array_lengthof( VR); 4254 4255 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4256 4257 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4258 4259 // In 32-bit non-varargs functions, the stack space for vectors is after the 4260 // stack space for non-vectors. We do not use this space unless we have 4261 // too many vectors to fit in registers, something that only occurs in 4262 // constructed examples:), but we have to walk the arglist to figure 4263 // that out...for the pathological case, compute VecArgOffset as the 4264 // start of the vector parameter area. Computing VecArgOffset is the 4265 // entire point of the following loop. 4266 unsigned VecArgOffset = ArgOffset; 4267 if (!isVarArg && !isPPC64) { 4268 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4269 ++ArgNo) { 4270 EVT ObjectVT = Ins[ArgNo].VT; 4271 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4272 4273 if (Flags.isByVal()) { 4274 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4275 unsigned ObjSize = Flags.getByValSize(); 4276 unsigned ArgSize = 4277 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4278 VecArgOffset += ArgSize; 4279 continue; 4280 } 4281 4282 switch(ObjectVT.getSimpleVT().SimpleTy) { 4283 default: llvm_unreachable("Unhandled argument type!"); 4284 case MVT::i1: 4285 case MVT::i32: 4286 case MVT::f32: 4287 VecArgOffset += 4; 4288 break; 4289 case MVT::i64: // PPC64 4290 case MVT::f64: 4291 // FIXME: We are guaranteed to be !isPPC64 at this point. 4292 // Does MVT::i64 apply? 4293 VecArgOffset += 8; 4294 break; 4295 case MVT::v4f32: 4296 case MVT::v4i32: 4297 case MVT::v8i16: 4298 case MVT::v16i8: 4299 // Nothing to do, we're only looking at Nonvector args here. 4300 break; 4301 } 4302 } 4303 } 4304 // We've found where the vector parameter area in memory is. Skip the 4305 // first 12 parameters; these don't use that memory. 4306 VecArgOffset = ((VecArgOffset+15)/16)*16; 4307 VecArgOffset += 12*16; 4308 4309 // Add DAG nodes to load the arguments or copy them out of registers. On 4310 // entry to a function on PPC, the arguments start after the linkage area, 4311 // although the first ones are often in registers. 4312 4313 SmallVector<SDValue, 8> MemOps; 4314 unsigned nAltivecParamsAtEnd = 0; 4315 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4316 unsigned CurArgIdx = 0; 4317 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4318 SDValue ArgVal; 4319 bool needsLoad = false; 4320 EVT ObjectVT = Ins[ArgNo].VT; 4321 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4322 unsigned ArgSize = ObjSize; 4323 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4324 if (Ins[ArgNo].isOrigArg()) { 4325 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4326 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4327 } 4328 unsigned CurArgOffset = ArgOffset; 4329 4330 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4331 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4332 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4333 if (isVarArg || isPPC64) { 4334 MinReservedArea = ((MinReservedArea+15)/16)*16; 4335 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4336 Flags, 4337 PtrByteSize); 4338 } else nAltivecParamsAtEnd++; 4339 } else 4340 // Calculate min reserved area. 4341 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4342 Flags, 4343 PtrByteSize); 4344 4345 // FIXME the codegen can be much improved in some cases. 4346 // We do not have to keep everything in memory. 4347 if (Flags.isByVal()) { 4348 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4349 4350 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4351 ObjSize = Flags.getByValSize(); 4352 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4353 // Objects of size 1 and 2 are right justified, everything else is 4354 // left justified. This means the memory address is adjusted forwards. 4355 if (ObjSize==1 || ObjSize==2) { 4356 CurArgOffset = CurArgOffset + (4 - ObjSize); 4357 } 4358 // The value of the object is its address. 4359 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4360 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4361 InVals.push_back(FIN); 4362 if (ObjSize==1 || ObjSize==2) { 4363 if (GPR_idx != Num_GPR_Regs) { 4364 unsigned VReg; 4365 if (isPPC64) 4366 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4367 else 4368 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4369 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4370 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4371 SDValue Store = 4372 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4373 MachinePointerInfo(&*FuncArg), ObjType); 4374 MemOps.push_back(Store); 4375 ++GPR_idx; 4376 } 4377 4378 ArgOffset += PtrByteSize; 4379 4380 continue; 4381 } 4382 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4383 // Store whatever pieces of the object are in registers 4384 // to memory. ArgOffset will be the address of the beginning 4385 // of the object. 4386 if (GPR_idx != Num_GPR_Regs) { 4387 unsigned VReg; 4388 if (isPPC64) 4389 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4390 else 4391 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4392 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4393 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4394 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4395 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4396 MachinePointerInfo(&*FuncArg, j)); 4397 MemOps.push_back(Store); 4398 ++GPR_idx; 4399 ArgOffset += PtrByteSize; 4400 } else { 4401 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4402 break; 4403 } 4404 } 4405 continue; 4406 } 4407 4408 switch (ObjectVT.getSimpleVT().SimpleTy) { 4409 default: llvm_unreachable("Unhandled argument type!"); 4410 case MVT::i1: 4411 case MVT::i32: 4412 if (!isPPC64) { 4413 if (GPR_idx != Num_GPR_Regs) { 4414 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4415 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4416 4417 if (ObjectVT == MVT::i1) 4418 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4419 4420 ++GPR_idx; 4421 } else { 4422 needsLoad = true; 4423 ArgSize = PtrByteSize; 4424 } 4425 // All int arguments reserve stack space in the Darwin ABI. 4426 ArgOffset += PtrByteSize; 4427 break; 4428 } 4429 LLVM_FALLTHROUGH; 4430 case MVT::i64: // PPC64 4431 if (GPR_idx != Num_GPR_Regs) { 4432 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4433 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4434 4435 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4436 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4437 // value to MVT::i64 and then truncate to the correct register size. 4438 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4439 4440 ++GPR_idx; 4441 } else { 4442 needsLoad = true; 4443 ArgSize = PtrByteSize; 4444 } 4445 // All int arguments reserve stack space in the Darwin ABI. 4446 ArgOffset += 8; 4447 break; 4448 4449 case MVT::f32: 4450 case MVT::f64: 4451 // Every 4 bytes of argument space consumes one of the GPRs available for 4452 // argument passing. 4453 if (GPR_idx != Num_GPR_Regs) { 4454 ++GPR_idx; 4455 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4456 ++GPR_idx; 4457 } 4458 if (FPR_idx != Num_FPR_Regs) { 4459 unsigned VReg; 4460 4461 if (ObjectVT == MVT::f32) 4462 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4463 else 4464 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4465 4466 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4467 ++FPR_idx; 4468 } else { 4469 needsLoad = true; 4470 } 4471 4472 // All FP arguments reserve stack space in the Darwin ABI. 4473 ArgOffset += isPPC64 ? 8 : ObjSize; 4474 break; 4475 case MVT::v4f32: 4476 case MVT::v4i32: 4477 case MVT::v8i16: 4478 case MVT::v16i8: 4479 // Note that vector arguments in registers don't reserve stack space, 4480 // except in varargs functions. 4481 if (VR_idx != Num_VR_Regs) { 4482 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4483 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4484 if (isVarArg) { 4485 while ((ArgOffset % 16) != 0) { 4486 ArgOffset += PtrByteSize; 4487 if (GPR_idx != Num_GPR_Regs) 4488 GPR_idx++; 4489 } 4490 ArgOffset += 16; 4491 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4492 } 4493 ++VR_idx; 4494 } else { 4495 if (!isVarArg && !isPPC64) { 4496 // Vectors go after all the nonvectors. 4497 CurArgOffset = VecArgOffset; 4498 VecArgOffset += 16; 4499 } else { 4500 // Vectors are aligned. 4501 ArgOffset = ((ArgOffset+15)/16)*16; 4502 CurArgOffset = ArgOffset; 4503 ArgOffset += 16; 4504 } 4505 needsLoad = true; 4506 } 4507 break; 4508 } 4509 4510 // We need to load the argument to a virtual register if we determined above 4511 // that we ran out of physical registers of the appropriate type. 4512 if (needsLoad) { 4513 int FI = MFI.CreateFixedObject(ObjSize, 4514 CurArgOffset + (ArgSize - ObjSize), 4515 isImmutable); 4516 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4517 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4518 } 4519 4520 InVals.push_back(ArgVal); 4521 } 4522 4523 // Allow for Altivec parameters at the end, if needed. 4524 if (nAltivecParamsAtEnd) { 4525 MinReservedArea = ((MinReservedArea+15)/16)*16; 4526 MinReservedArea += 16*nAltivecParamsAtEnd; 4527 } 4528 4529 // Area that is at least reserved in the caller of this function. 4530 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4531 4532 // Set the size that is at least reserved in caller of this function. Tail 4533 // call optimized functions' reserved stack space needs to be aligned so that 4534 // taking the difference between two stack areas will result in an aligned 4535 // stack. 4536 MinReservedArea = 4537 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4538 FuncInfo->setMinReservedArea(MinReservedArea); 4539 4540 // If the function takes variable number of arguments, make a frame index for 4541 // the start of the first vararg value... for expansion of llvm.va_start. 4542 if (isVarArg) { 4543 int Depth = ArgOffset; 4544 4545 FuncInfo->setVarArgsFrameIndex( 4546 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4547 Depth, true)); 4548 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4549 4550 // If this function is vararg, store any remaining integer argument regs 4551 // to their spots on the stack so that they may be loaded by dereferencing 4552 // the result of va_next. 4553 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4554 unsigned VReg; 4555 4556 if (isPPC64) 4557 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4558 else 4559 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4560 4561 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4562 SDValue Store = 4563 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4564 MemOps.push_back(Store); 4565 // Increment the address by four for the next argument to store 4566 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4567 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4568 } 4569 } 4570 4571 if (!MemOps.empty()) 4572 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4573 4574 return Chain; 4575 } 4576 4577 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4578 /// adjusted to accommodate the arguments for the tailcall. 4579 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4580 unsigned ParamSize) { 4581 4582 if (!isTailCall) return 0; 4583 4584 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4585 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4586 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4587 // Remember only if the new adjustment is bigger. 4588 if (SPDiff < FI->getTailCallSPDelta()) 4589 FI->setTailCallSPDelta(SPDiff); 4590 4591 return SPDiff; 4592 } 4593 4594 static bool isFunctionGlobalAddress(SDValue Callee); 4595 4596 static bool 4597 callsShareTOCBase(const Function *Caller, SDValue Callee, 4598 const TargetMachine &TM) { 4599 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4600 // don't have enough information to determine if the caller and calle share 4601 // the same TOC base, so we have to pessimistically assume they don't for 4602 // correctness. 4603 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4604 if (!G) 4605 return false; 4606 4607 const GlobalValue *GV = G->getGlobal(); 4608 // The medium and large code models are expected to provide a sufficiently 4609 // large TOC to provide all data addressing needs of a module with a 4610 // single TOC. Since each module will be addressed with a single TOC then we 4611 // only need to check that caller and callee don't cross dso boundaries. 4612 if (CodeModel::Medium == TM.getCodeModel() || 4613 CodeModel::Large == TM.getCodeModel()) 4614 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4615 4616 // Otherwise we need to ensure callee and caller are in the same section, 4617 // since the linker may allocate multiple TOCs, and we don't know which 4618 // sections will belong to the same TOC base. 4619 4620 if (!GV->isStrongDefinitionForLinker()) 4621 return false; 4622 4623 // Any explicitly-specified sections and section prefixes must also match. 4624 // Also, if we're using -ffunction-sections, then each function is always in 4625 // a different section (the same is true for COMDAT functions). 4626 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4627 GV->getSection() != Caller->getSection()) 4628 return false; 4629 if (const auto *F = dyn_cast<Function>(GV)) { 4630 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4631 return false; 4632 } 4633 4634 // If the callee might be interposed, then we can't assume the ultimate call 4635 // target will be in the same section. Even in cases where we can assume that 4636 // interposition won't happen, in any case where the linker might insert a 4637 // stub to allow for interposition, we must generate code as though 4638 // interposition might occur. To understand why this matters, consider a 4639 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4640 // in the same section, but a is in a different module (i.e. has a different 4641 // TOC base pointer). If the linker allows for interposition between b and c, 4642 // then it will generate a stub for the call edge between b and c which will 4643 // save the TOC pointer into the designated stack slot allocated by b. If we 4644 // return true here, and therefore allow a tail call between b and c, that 4645 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4646 // pointer into the stack slot allocated by a (where the a -> b stub saved 4647 // a's TOC base pointer). If we're not considering a tail call, but rather, 4648 // whether a nop is needed after the call instruction in b, because the linker 4649 // will insert a stub, it might complain about a missing nop if we omit it 4650 // (although many don't complain in this case). 4651 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4652 return false; 4653 4654 return true; 4655 } 4656 4657 static bool 4658 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4659 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4660 assert(Subtarget.is64BitELFABI()); 4661 4662 const unsigned PtrByteSize = 8; 4663 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4664 4665 static const MCPhysReg GPR[] = { 4666 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4667 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4668 }; 4669 static const MCPhysReg VR[] = { 4670 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4671 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4672 }; 4673 4674 const unsigned NumGPRs = array_lengthof(GPR); 4675 const unsigned NumFPRs = 13; 4676 const unsigned NumVRs = array_lengthof(VR); 4677 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4678 4679 unsigned NumBytes = LinkageSize; 4680 unsigned AvailableFPRs = NumFPRs; 4681 unsigned AvailableVRs = NumVRs; 4682 4683 for (const ISD::OutputArg& Param : Outs) { 4684 if (Param.Flags.isNest()) continue; 4685 4686 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4687 PtrByteSize, LinkageSize, ParamAreaSize, 4688 NumBytes, AvailableFPRs, AvailableVRs, 4689 Subtarget.hasQPX())) 4690 return true; 4691 } 4692 return false; 4693 } 4694 4695 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4696 if (CB.arg_size() != CallerFn->arg_size()) 4697 return false; 4698 4699 auto CalleeArgIter = CB.arg_begin(); 4700 auto CalleeArgEnd = CB.arg_end(); 4701 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4702 4703 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4704 const Value* CalleeArg = *CalleeArgIter; 4705 const Value* CallerArg = &(*CallerArgIter); 4706 if (CalleeArg == CallerArg) 4707 continue; 4708 4709 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4710 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4711 // } 4712 // 1st argument of callee is undef and has the same type as caller. 4713 if (CalleeArg->getType() == CallerArg->getType() && 4714 isa<UndefValue>(CalleeArg)) 4715 continue; 4716 4717 return false; 4718 } 4719 4720 return true; 4721 } 4722 4723 // Returns true if TCO is possible between the callers and callees 4724 // calling conventions. 4725 static bool 4726 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4727 CallingConv::ID CalleeCC) { 4728 // Tail calls are possible with fastcc and ccc. 4729 auto isTailCallableCC = [] (CallingConv::ID CC){ 4730 return CC == CallingConv::C || CC == CallingConv::Fast; 4731 }; 4732 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4733 return false; 4734 4735 // We can safely tail call both fastcc and ccc callees from a c calling 4736 // convention caller. If the caller is fastcc, we may have less stack space 4737 // than a non-fastcc caller with the same signature so disable tail-calls in 4738 // that case. 4739 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4740 } 4741 4742 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4743 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4744 const SmallVectorImpl<ISD::OutputArg> &Outs, 4745 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4746 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4747 4748 // FIXME: Tail calls are currently disabled when using PC Relative addressing. 4749 // The issue is that PC Relative is only partially implemented and so there 4750 // is currently a mix of functions that require the TOC and functions that do 4751 // not require it. If we have A calls B calls C and both A and B require the 4752 // TOC and C does not and is marked as clobbering R2 then it is not safe for 4753 // B to tail call C. Since we do not have the information of whether or not 4754 // a funciton needs to use the TOC here in this function we need to be 4755 // conservatively safe and disable all tail calls for now. 4756 if (Subtarget.isUsingPCRelativeCalls()) return false; 4757 4758 if (DisableSCO && !TailCallOpt) return false; 4759 4760 // Variadic argument functions are not supported. 4761 if (isVarArg) return false; 4762 4763 auto &Caller = DAG.getMachineFunction().getFunction(); 4764 // Check that the calling conventions are compatible for tco. 4765 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4766 return false; 4767 4768 // Caller contains any byval parameter is not supported. 4769 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4770 return false; 4771 4772 // Callee contains any byval parameter is not supported, too. 4773 // Note: This is a quick work around, because in some cases, e.g. 4774 // caller's stack size > callee's stack size, we are still able to apply 4775 // sibling call optimization. For example, gcc is able to do SCO for caller1 4776 // in the following example, but not for caller2. 4777 // struct test { 4778 // long int a; 4779 // char ary[56]; 4780 // } gTest; 4781 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4782 // b->a = v.a; 4783 // return 0; 4784 // } 4785 // void caller1(struct test a, struct test c, struct test *b) { 4786 // callee(gTest, b); } 4787 // void caller2(struct test *b) { callee(gTest, b); } 4788 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4789 return false; 4790 4791 // If callee and caller use different calling conventions, we cannot pass 4792 // parameters on stack since offsets for the parameter area may be different. 4793 if (Caller.getCallingConv() != CalleeCC && 4794 needStackSlotPassParameters(Subtarget, Outs)) 4795 return false; 4796 4797 // No TCO/SCO on indirect call because Caller have to restore its TOC 4798 if (!isFunctionGlobalAddress(Callee) && 4799 !isa<ExternalSymbolSDNode>(Callee)) 4800 return false; 4801 4802 // If the caller and callee potentially have different TOC bases then we 4803 // cannot tail call since we need to restore the TOC pointer after the call. 4804 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4805 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4806 return false; 4807 4808 // TCO allows altering callee ABI, so we don't have to check further. 4809 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4810 return true; 4811 4812 if (DisableSCO) return false; 4813 4814 // If callee use the same argument list that caller is using, then we can 4815 // apply SCO on this case. If it is not, then we need to check if callee needs 4816 // stack for passing arguments. 4817 assert(CB && "Expected to have a CallBase!"); 4818 if (!hasSameArgumentList(&Caller, *CB) && 4819 needStackSlotPassParameters(Subtarget, Outs)) { 4820 return false; 4821 } 4822 4823 return true; 4824 } 4825 4826 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4827 /// for tail call optimization. Targets which want to do tail call 4828 /// optimization should implement this function. 4829 bool 4830 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4831 CallingConv::ID CalleeCC, 4832 bool isVarArg, 4833 const SmallVectorImpl<ISD::InputArg> &Ins, 4834 SelectionDAG& DAG) const { 4835 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4836 return false; 4837 4838 // Variable argument functions are not supported. 4839 if (isVarArg) 4840 return false; 4841 4842 MachineFunction &MF = DAG.getMachineFunction(); 4843 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4844 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4845 // Functions containing by val parameters are not supported. 4846 for (unsigned i = 0; i != Ins.size(); i++) { 4847 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4848 if (Flags.isByVal()) return false; 4849 } 4850 4851 // Non-PIC/GOT tail calls are supported. 4852 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4853 return true; 4854 4855 // At the moment we can only do local tail calls (in same module, hidden 4856 // or protected) if we are generating PIC. 4857 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4858 return G->getGlobal()->hasHiddenVisibility() 4859 || G->getGlobal()->hasProtectedVisibility(); 4860 } 4861 4862 return false; 4863 } 4864 4865 /// isCallCompatibleAddress - Return the immediate to use if the specified 4866 /// 32-bit value is representable in the immediate field of a BxA instruction. 4867 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4868 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4869 if (!C) return nullptr; 4870 4871 int Addr = C->getZExtValue(); 4872 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4873 SignExtend32<26>(Addr) != Addr) 4874 return nullptr; // Top 6 bits have to be sext of immediate. 4875 4876 return DAG 4877 .getConstant( 4878 (int)C->getZExtValue() >> 2, SDLoc(Op), 4879 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4880 .getNode(); 4881 } 4882 4883 namespace { 4884 4885 struct TailCallArgumentInfo { 4886 SDValue Arg; 4887 SDValue FrameIdxOp; 4888 int FrameIdx = 0; 4889 4890 TailCallArgumentInfo() = default; 4891 }; 4892 4893 } // end anonymous namespace 4894 4895 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4896 static void StoreTailCallArgumentsToStackSlot( 4897 SelectionDAG &DAG, SDValue Chain, 4898 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4899 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4900 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4901 SDValue Arg = TailCallArgs[i].Arg; 4902 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4903 int FI = TailCallArgs[i].FrameIdx; 4904 // Store relative to framepointer. 4905 MemOpChains.push_back(DAG.getStore( 4906 Chain, dl, Arg, FIN, 4907 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4908 } 4909 } 4910 4911 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4912 /// the appropriate stack slot for the tail call optimized function call. 4913 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4914 SDValue OldRetAddr, SDValue OldFP, 4915 int SPDiff, const SDLoc &dl) { 4916 if (SPDiff) { 4917 // Calculate the new stack slot for the return address. 4918 MachineFunction &MF = DAG.getMachineFunction(); 4919 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4920 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4921 bool isPPC64 = Subtarget.isPPC64(); 4922 int SlotSize = isPPC64 ? 8 : 4; 4923 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4924 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4925 NewRetAddrLoc, true); 4926 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4927 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4928 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4929 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4930 } 4931 return Chain; 4932 } 4933 4934 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4935 /// the position of the argument. 4936 static void 4937 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4938 SDValue Arg, int SPDiff, unsigned ArgOffset, 4939 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4940 int Offset = ArgOffset + SPDiff; 4941 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4942 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4943 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4944 SDValue FIN = DAG.getFrameIndex(FI, VT); 4945 TailCallArgumentInfo Info; 4946 Info.Arg = Arg; 4947 Info.FrameIdxOp = FIN; 4948 Info.FrameIdx = FI; 4949 TailCallArguments.push_back(Info); 4950 } 4951 4952 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4953 /// stack slot. Returns the chain as result and the loaded frame pointers in 4954 /// LROpOut/FPOpout. Used when tail calling. 4955 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4956 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4957 SDValue &FPOpOut, const SDLoc &dl) const { 4958 if (SPDiff) { 4959 // Load the LR and FP stack slot for later adjusting. 4960 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4961 LROpOut = getReturnAddrFrameIndex(DAG); 4962 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4963 Chain = SDValue(LROpOut.getNode(), 1); 4964 } 4965 return Chain; 4966 } 4967 4968 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4969 /// by "Src" to address "Dst" of size "Size". Alignment information is 4970 /// specified by the specific parameter attribute. The copy will be passed as 4971 /// a byval function parameter. 4972 /// Sometimes what we are copying is the end of a larger object, the part that 4973 /// does not fit in registers. 4974 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4975 SDValue Chain, ISD::ArgFlagsTy Flags, 4976 SelectionDAG &DAG, const SDLoc &dl) { 4977 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4978 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4979 Flags.getNonZeroByValAlign(), false, false, false, 4980 MachinePointerInfo(), MachinePointerInfo()); 4981 } 4982 4983 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4984 /// tail calls. 4985 static void LowerMemOpCallTo( 4986 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4987 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4988 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4989 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4990 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4991 if (!isTailCall) { 4992 if (isVector) { 4993 SDValue StackPtr; 4994 if (isPPC64) 4995 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4996 else 4997 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4998 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4999 DAG.getConstant(ArgOffset, dl, PtrVT)); 5000 } 5001 MemOpChains.push_back( 5002 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5003 // Calculate and remember argument location. 5004 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5005 TailCallArguments); 5006 } 5007 5008 static void 5009 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5010 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5011 SDValue FPOp, 5012 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5013 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5014 // might overwrite each other in case of tail call optimization. 5015 SmallVector<SDValue, 8> MemOpChains2; 5016 // Do not flag preceding copytoreg stuff together with the following stuff. 5017 InFlag = SDValue(); 5018 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5019 MemOpChains2, dl); 5020 if (!MemOpChains2.empty()) 5021 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5022 5023 // Store the return address to the appropriate stack slot. 5024 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5025 5026 // Emit callseq_end just before tailcall node. 5027 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5028 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5029 InFlag = Chain.getValue(1); 5030 } 5031 5032 // Is this global address that of a function that can be called by name? (as 5033 // opposed to something that must hold a descriptor for an indirect call). 5034 static bool isFunctionGlobalAddress(SDValue Callee) { 5035 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5036 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5037 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5038 return false; 5039 5040 return G->getGlobal()->getValueType()->isFunctionTy(); 5041 } 5042 5043 return false; 5044 } 5045 5046 SDValue PPCTargetLowering::LowerCallResult( 5047 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5048 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5049 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5050 SmallVector<CCValAssign, 16> RVLocs; 5051 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5052 *DAG.getContext()); 5053 5054 CCRetInfo.AnalyzeCallResult( 5055 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5056 ? RetCC_PPC_Cold 5057 : RetCC_PPC); 5058 5059 // Copy all of the result registers out of their specified physreg. 5060 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5061 CCValAssign &VA = RVLocs[i]; 5062 assert(VA.isRegLoc() && "Can only return in registers!"); 5063 5064 SDValue Val; 5065 5066 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5067 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5068 InFlag); 5069 Chain = Lo.getValue(1); 5070 InFlag = Lo.getValue(2); 5071 VA = RVLocs[++i]; // skip ahead to next loc 5072 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5073 InFlag); 5074 Chain = Hi.getValue(1); 5075 InFlag = Hi.getValue(2); 5076 if (!Subtarget.isLittleEndian()) 5077 std::swap (Lo, Hi); 5078 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5079 } else { 5080 Val = DAG.getCopyFromReg(Chain, dl, 5081 VA.getLocReg(), VA.getLocVT(), InFlag); 5082 Chain = Val.getValue(1); 5083 InFlag = Val.getValue(2); 5084 } 5085 5086 switch (VA.getLocInfo()) { 5087 default: llvm_unreachable("Unknown loc info!"); 5088 case CCValAssign::Full: break; 5089 case CCValAssign::AExt: 5090 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5091 break; 5092 case CCValAssign::ZExt: 5093 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5094 DAG.getValueType(VA.getValVT())); 5095 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5096 break; 5097 case CCValAssign::SExt: 5098 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5099 DAG.getValueType(VA.getValVT())); 5100 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5101 break; 5102 } 5103 5104 InVals.push_back(Val); 5105 } 5106 5107 return Chain; 5108 } 5109 5110 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5111 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5112 // PatchPoint calls are not indirect. 5113 if (isPatchPoint) 5114 return false; 5115 5116 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5117 return false; 5118 5119 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5120 // becuase the immediate function pointer points to a descriptor instead of 5121 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5122 // pointer immediate points to the global entry point, while the BLA would 5123 // need to jump to the local entry point (see rL211174). 5124 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5125 isBLACompatibleAddress(Callee, DAG)) 5126 return false; 5127 5128 return true; 5129 } 5130 5131 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5132 const Function &Caller, 5133 const SDValue &Callee, 5134 const PPCSubtarget &Subtarget, 5135 const TargetMachine &TM) { 5136 if (CFlags.IsTailCall) 5137 return PPCISD::TC_RETURN; 5138 5139 // This is a call through a function pointer. 5140 if (CFlags.IsIndirect) { 5141 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5142 // indirect calls. The save of the caller's TOC pointer to the stack will be 5143 // inserted into the DAG as part of call lowering. The restore of the TOC 5144 // pointer is modeled by using a pseudo instruction for the call opcode that 5145 // represents the 2 instruction sequence of an indirect branch and link, 5146 // immediately followed by a load of the TOC pointer from the the stack save 5147 // slot into gpr2. 5148 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5149 return PPCISD::BCTRL_LOAD_TOC; 5150 5151 // An indirect call that does not need a TOC restore. 5152 return PPCISD::BCTRL; 5153 } 5154 5155 // FIXME: At this moment indirect calls are treated ahead of the 5156 // PC Relative condition because binaries can still contain a possible 5157 // mix of functions that use a TOC and functions that do not use a TOC. 5158 // Once the PC Relative feature is complete this condition should be moved 5159 // up ahead of the indirect calls and should return a PPCISD::BCTRL for 5160 // that case. 5161 if (Subtarget.isUsingPCRelativeCalls()) { 5162 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5163 return PPCISD::CALL_NOTOC; 5164 } 5165 5166 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5167 // immediately following the call instruction if the caller and callee may 5168 // have different TOC bases. At link time if the linker determines the calls 5169 // may not share a TOC base, the call is redirected to a trampoline inserted 5170 // by the linker. The trampoline will (among other things) save the callers 5171 // TOC pointer at an ABI designated offset in the linkage area and the linker 5172 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5173 // into gpr2. 5174 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5175 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5176 : PPCISD::CALL_NOP; 5177 5178 return PPCISD::CALL; 5179 } 5180 5181 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5182 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5183 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5184 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5185 return SDValue(Dest, 0); 5186 5187 // Returns true if the callee is local, and false otherwise. 5188 auto isLocalCallee = [&]() { 5189 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5190 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5191 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5192 5193 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5194 !dyn_cast_or_null<GlobalIFunc>(GV); 5195 }; 5196 5197 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5198 // a static relocation model causes some versions of GNU LD (2.17.50, at 5199 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5200 // built with secure-PLT. 5201 bool UsePlt = 5202 Subtarget.is32BitELFABI() && !isLocalCallee() && 5203 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5204 5205 // On AIX, direct function calls reference the symbol for the function's 5206 // entry point, which is named by prepending a "." before the function's 5207 // C-linkage name. 5208 const auto getAIXFuncEntryPointSymbolSDNode = 5209 [&](StringRef FuncName, bool IsDeclaration, 5210 const XCOFF::StorageClass &SC) { 5211 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5212 5213 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5214 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5215 5216 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5217 // On AIX, an undefined symbol needs to be associated with a 5218 // MCSectionXCOFF to get the correct storage mapping class. 5219 // In this case, XCOFF::XMC_PR. 5220 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5221 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5222 SectionKind::getMetadata()); 5223 S->setRepresentedCsect(Sec); 5224 } 5225 5226 MVT PtrVT = 5227 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5228 return DAG.getMCSymbol(S, PtrVT); 5229 }; 5230 5231 if (isFunctionGlobalAddress(Callee)) { 5232 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5233 const GlobalValue *GV = G->getGlobal(); 5234 5235 if (!Subtarget.isAIXABI()) 5236 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5237 UsePlt ? PPCII::MO_PLT : 0); 5238 5239 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5240 const GlobalObject *GO = cast<GlobalObject>(GV); 5241 const XCOFF::StorageClass SC = 5242 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5243 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5244 SC); 5245 } 5246 5247 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5248 const char *SymName = S->getSymbol(); 5249 if (!Subtarget.isAIXABI()) 5250 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5251 UsePlt ? PPCII::MO_PLT : 0); 5252 5253 // If there exists a user-declared function whose name is the same as the 5254 // ExternalSymbol's, then we pick up the user-declared version. 5255 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5256 if (const Function *F = 5257 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5258 const XCOFF::StorageClass SC = 5259 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5260 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5261 SC); 5262 } 5263 5264 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5265 } 5266 5267 // No transformation needed. 5268 assert(Callee.getNode() && "What no callee?"); 5269 return Callee; 5270 } 5271 5272 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5273 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5274 "Expected a CALLSEQ_STARTSDNode."); 5275 5276 // The last operand is the chain, except when the node has glue. If the node 5277 // has glue, then the last operand is the glue, and the chain is the second 5278 // last operand. 5279 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5280 if (LastValue.getValueType() != MVT::Glue) 5281 return LastValue; 5282 5283 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5284 } 5285 5286 // Creates the node that moves a functions address into the count register 5287 // to prepare for an indirect call instruction. 5288 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5289 SDValue &Glue, SDValue &Chain, 5290 const SDLoc &dl) { 5291 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5292 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5293 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5294 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5295 // The glue is the second value produced. 5296 Glue = Chain.getValue(1); 5297 } 5298 5299 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5300 SDValue &Glue, SDValue &Chain, 5301 SDValue CallSeqStart, 5302 const CallBase *CB, const SDLoc &dl, 5303 bool hasNest, 5304 const PPCSubtarget &Subtarget) { 5305 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5306 // entry point, but to the function descriptor (the function entry point 5307 // address is part of the function descriptor though). 5308 // The function descriptor is a three doubleword structure with the 5309 // following fields: function entry point, TOC base address and 5310 // environment pointer. 5311 // Thus for a call through a function pointer, the following actions need 5312 // to be performed: 5313 // 1. Save the TOC of the caller in the TOC save area of its stack 5314 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5315 // 2. Load the address of the function entry point from the function 5316 // descriptor. 5317 // 3. Load the TOC of the callee from the function descriptor into r2. 5318 // 4. Load the environment pointer from the function descriptor into 5319 // r11. 5320 // 5. Branch to the function entry point address. 5321 // 6. On return of the callee, the TOC of the caller needs to be 5322 // restored (this is done in FinishCall()). 5323 // 5324 // The loads are scheduled at the beginning of the call sequence, and the 5325 // register copies are flagged together to ensure that no other 5326 // operations can be scheduled in between. E.g. without flagging the 5327 // copies together, a TOC access in the caller could be scheduled between 5328 // the assignment of the callee TOC and the branch to the callee, which leads 5329 // to incorrect code. 5330 5331 // Start by loading the function address from the descriptor. 5332 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5333 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5334 ? (MachineMemOperand::MODereferenceable | 5335 MachineMemOperand::MOInvariant) 5336 : MachineMemOperand::MONone; 5337 5338 MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr); 5339 5340 // Registers used in building the DAG. 5341 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5342 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5343 5344 // Offsets of descriptor members. 5345 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5346 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5347 5348 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5349 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5350 5351 // One load for the functions entry point address. 5352 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5353 Alignment, MMOFlags); 5354 5355 // One for loading the TOC anchor for the module that contains the called 5356 // function. 5357 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5358 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5359 SDValue TOCPtr = 5360 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5361 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5362 5363 // One for loading the environment pointer. 5364 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5365 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5366 SDValue LoadEnvPtr = 5367 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5368 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5369 5370 5371 // Then copy the newly loaded TOC anchor to the TOC pointer. 5372 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5373 Chain = TOCVal.getValue(0); 5374 Glue = TOCVal.getValue(1); 5375 5376 // If the function call has an explicit 'nest' parameter, it takes the 5377 // place of the environment pointer. 5378 assert((!hasNest || !Subtarget.isAIXABI()) && 5379 "Nest parameter is not supported on AIX."); 5380 if (!hasNest) { 5381 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5382 Chain = EnvVal.getValue(0); 5383 Glue = EnvVal.getValue(1); 5384 } 5385 5386 // The rest of the indirect call sequence is the same as the non-descriptor 5387 // DAG. 5388 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5389 } 5390 5391 static void 5392 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5393 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5394 SelectionDAG &DAG, 5395 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5396 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5397 const PPCSubtarget &Subtarget) { 5398 const bool IsPPC64 = Subtarget.isPPC64(); 5399 // MVT for a general purpose register. 5400 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5401 5402 // First operand is always the chain. 5403 Ops.push_back(Chain); 5404 5405 // If it's a direct call pass the callee as the second operand. 5406 if (!CFlags.IsIndirect) 5407 Ops.push_back(Callee); 5408 else { 5409 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5410 5411 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5412 // on the stack (this would have been done in `LowerCall_64SVR4` or 5413 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5414 // represents both the indirect branch and a load that restores the TOC 5415 // pointer from the linkage area. The operand for the TOC restore is an add 5416 // of the TOC save offset to the stack pointer. This must be the second 5417 // operand: after the chain input but before any other variadic arguments. 5418 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5419 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5420 5421 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5422 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5423 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5424 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5425 Ops.push_back(AddTOC); 5426 } 5427 5428 // Add the register used for the environment pointer. 5429 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5430 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5431 RegVT)); 5432 5433 5434 // Add CTR register as callee so a bctr can be emitted later. 5435 if (CFlags.IsTailCall) 5436 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5437 } 5438 5439 // If this is a tail call add stack pointer delta. 5440 if (CFlags.IsTailCall) 5441 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5442 5443 // Add argument registers to the end of the list so that they are known live 5444 // into the call. 5445 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5446 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5447 RegsToPass[i].second.getValueType())); 5448 5449 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5450 // no way to mark dependencies as implicit here. 5451 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5452 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5453 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5454 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5455 5456 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5457 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5458 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5459 5460 // Add a register mask operand representing the call-preserved registers. 5461 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5462 const uint32_t *Mask = 5463 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5464 assert(Mask && "Missing call preserved mask for calling convention"); 5465 Ops.push_back(DAG.getRegisterMask(Mask)); 5466 5467 // If the glue is valid, it is the last operand. 5468 if (Glue.getNode()) 5469 Ops.push_back(Glue); 5470 } 5471 5472 SDValue PPCTargetLowering::FinishCall( 5473 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5474 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5475 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5476 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5477 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5478 5479 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5480 Subtarget.isAIXABI()) 5481 setUsesTOCBasePtr(DAG); 5482 5483 unsigned CallOpc = 5484 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5485 Subtarget, DAG.getTarget()); 5486 5487 if (!CFlags.IsIndirect) 5488 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5489 else if (Subtarget.usesFunctionDescriptors()) 5490 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5491 dl, CFlags.HasNest, Subtarget); 5492 else 5493 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5494 5495 // Build the operand list for the call instruction. 5496 SmallVector<SDValue, 8> Ops; 5497 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5498 SPDiff, Subtarget); 5499 5500 // Emit tail call. 5501 if (CFlags.IsTailCall) { 5502 assert(((Callee.getOpcode() == ISD::Register && 5503 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5504 Callee.getOpcode() == ISD::TargetExternalSymbol || 5505 Callee.getOpcode() == ISD::TargetGlobalAddress || 5506 isa<ConstantSDNode>(Callee)) && 5507 "Expecting a global address, external symbol, absolute value or " 5508 "register"); 5509 assert(CallOpc == PPCISD::TC_RETURN && 5510 "Unexpected call opcode for a tail call."); 5511 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5512 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5513 } 5514 5515 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5516 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5517 Glue = Chain.getValue(1); 5518 5519 // When performing tail call optimization the callee pops its arguments off 5520 // the stack. Account for this here so these bytes can be pushed back on in 5521 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5522 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5523 getTargetMachine().Options.GuaranteedTailCallOpt) 5524 ? NumBytes 5525 : 0; 5526 5527 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5528 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5529 Glue, dl); 5530 Glue = Chain.getValue(1); 5531 5532 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5533 DAG, InVals); 5534 } 5535 5536 SDValue 5537 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5538 SmallVectorImpl<SDValue> &InVals) const { 5539 SelectionDAG &DAG = CLI.DAG; 5540 SDLoc &dl = CLI.DL; 5541 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5542 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5543 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5544 SDValue Chain = CLI.Chain; 5545 SDValue Callee = CLI.Callee; 5546 bool &isTailCall = CLI.IsTailCall; 5547 CallingConv::ID CallConv = CLI.CallConv; 5548 bool isVarArg = CLI.IsVarArg; 5549 bool isPatchPoint = CLI.IsPatchPoint; 5550 const CallBase *CB = CLI.CB; 5551 5552 if (isTailCall) { 5553 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5554 isTailCall = false; 5555 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5556 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5557 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5558 else 5559 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5560 Ins, DAG); 5561 if (isTailCall) { 5562 ++NumTailCalls; 5563 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5564 ++NumSiblingCalls; 5565 5566 assert(isa<GlobalAddressSDNode>(Callee) && 5567 "Callee should be an llvm::Function object."); 5568 LLVM_DEBUG( 5569 const GlobalValue *GV = 5570 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5571 const unsigned Width = 5572 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5573 dbgs() << "TCO caller: " 5574 << left_justify(DAG.getMachineFunction().getName(), Width) 5575 << ", callee linkage: " << GV->getVisibility() << ", " 5576 << GV->getLinkage() << "\n"); 5577 } 5578 } 5579 5580 if (!isTailCall && CB && CB->isMustTailCall()) 5581 report_fatal_error("failed to perform tail call elimination on a call " 5582 "site marked musttail"); 5583 5584 // When long calls (i.e. indirect calls) are always used, calls are always 5585 // made via function pointer. If we have a function name, first translate it 5586 // into a pointer. 5587 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5588 !isTailCall) 5589 Callee = LowerGlobalAddress(Callee, DAG); 5590 5591 CallFlags CFlags( 5592 CallConv, isTailCall, isVarArg, isPatchPoint, 5593 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5594 // hasNest 5595 Subtarget.is64BitELFABI() && 5596 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5597 5598 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5599 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5600 InVals, CB); 5601 5602 if (Subtarget.isSVR4ABI()) 5603 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5604 InVals, CB); 5605 5606 if (Subtarget.isAIXABI()) 5607 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5608 InVals, CB); 5609 5610 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5611 InVals, CB); 5612 } 5613 5614 SDValue PPCTargetLowering::LowerCall_32SVR4( 5615 SDValue Chain, SDValue Callee, CallFlags CFlags, 5616 const SmallVectorImpl<ISD::OutputArg> &Outs, 5617 const SmallVectorImpl<SDValue> &OutVals, 5618 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5619 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5620 const CallBase *CB) const { 5621 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5622 // of the 32-bit SVR4 ABI stack frame layout. 5623 5624 const CallingConv::ID CallConv = CFlags.CallConv; 5625 const bool IsVarArg = CFlags.IsVarArg; 5626 const bool IsTailCall = CFlags.IsTailCall; 5627 5628 assert((CallConv == CallingConv::C || 5629 CallConv == CallingConv::Cold || 5630 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5631 5632 unsigned PtrByteSize = 4; 5633 5634 MachineFunction &MF = DAG.getMachineFunction(); 5635 5636 // Mark this function as potentially containing a function that contains a 5637 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5638 // and restoring the callers stack pointer in this functions epilog. This is 5639 // done because by tail calling the called function might overwrite the value 5640 // in this function's (MF) stack pointer stack slot 0(SP). 5641 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5642 CallConv == CallingConv::Fast) 5643 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5644 5645 // Count how many bytes are to be pushed on the stack, including the linkage 5646 // area, parameter list area and the part of the local variable space which 5647 // contains copies of aggregates which are passed by value. 5648 5649 // Assign locations to all of the outgoing arguments. 5650 SmallVector<CCValAssign, 16> ArgLocs; 5651 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5652 5653 // Reserve space for the linkage area on the stack. 5654 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5655 PtrByteSize); 5656 if (useSoftFloat()) 5657 CCInfo.PreAnalyzeCallOperands(Outs); 5658 5659 if (IsVarArg) { 5660 // Handle fixed and variable vector arguments differently. 5661 // Fixed vector arguments go into registers as long as registers are 5662 // available. Variable vector arguments always go into memory. 5663 unsigned NumArgs = Outs.size(); 5664 5665 for (unsigned i = 0; i != NumArgs; ++i) { 5666 MVT ArgVT = Outs[i].VT; 5667 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5668 bool Result; 5669 5670 if (Outs[i].IsFixed) { 5671 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5672 CCInfo); 5673 } else { 5674 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5675 ArgFlags, CCInfo); 5676 } 5677 5678 if (Result) { 5679 #ifndef NDEBUG 5680 errs() << "Call operand #" << i << " has unhandled type " 5681 << EVT(ArgVT).getEVTString() << "\n"; 5682 #endif 5683 llvm_unreachable(nullptr); 5684 } 5685 } 5686 } else { 5687 // All arguments are treated the same. 5688 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5689 } 5690 CCInfo.clearWasPPCF128(); 5691 5692 // Assign locations to all of the outgoing aggregate by value arguments. 5693 SmallVector<CCValAssign, 16> ByValArgLocs; 5694 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5695 5696 // Reserve stack space for the allocations in CCInfo. 5697 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5698 5699 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5700 5701 // Size of the linkage area, parameter list area and the part of the local 5702 // space variable where copies of aggregates which are passed by value are 5703 // stored. 5704 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5705 5706 // Calculate by how many bytes the stack has to be adjusted in case of tail 5707 // call optimization. 5708 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5709 5710 // Adjust the stack pointer for the new arguments... 5711 // These operations are automatically eliminated by the prolog/epilog pass 5712 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5713 SDValue CallSeqStart = Chain; 5714 5715 // Load the return address and frame pointer so it can be moved somewhere else 5716 // later. 5717 SDValue LROp, FPOp; 5718 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5719 5720 // Set up a copy of the stack pointer for use loading and storing any 5721 // arguments that may not fit in the registers available for argument 5722 // passing. 5723 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5724 5725 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5726 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5727 SmallVector<SDValue, 8> MemOpChains; 5728 5729 bool seenFloatArg = false; 5730 // Walk the register/memloc assignments, inserting copies/loads. 5731 // i - Tracks the index into the list of registers allocated for the call 5732 // RealArgIdx - Tracks the index into the list of actual function arguments 5733 // j - Tracks the index into the list of byval arguments 5734 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5735 i != e; 5736 ++i, ++RealArgIdx) { 5737 CCValAssign &VA = ArgLocs[i]; 5738 SDValue Arg = OutVals[RealArgIdx]; 5739 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5740 5741 if (Flags.isByVal()) { 5742 // Argument is an aggregate which is passed by value, thus we need to 5743 // create a copy of it in the local variable space of the current stack 5744 // frame (which is the stack frame of the caller) and pass the address of 5745 // this copy to the callee. 5746 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5747 CCValAssign &ByValVA = ByValArgLocs[j++]; 5748 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5749 5750 // Memory reserved in the local variable space of the callers stack frame. 5751 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5752 5753 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5754 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5755 StackPtr, PtrOff); 5756 5757 // Create a copy of the argument in the local area of the current 5758 // stack frame. 5759 SDValue MemcpyCall = 5760 CreateCopyOfByValArgument(Arg, PtrOff, 5761 CallSeqStart.getNode()->getOperand(0), 5762 Flags, DAG, dl); 5763 5764 // This must go outside the CALLSEQ_START..END. 5765 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5766 SDLoc(MemcpyCall)); 5767 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5768 NewCallSeqStart.getNode()); 5769 Chain = CallSeqStart = NewCallSeqStart; 5770 5771 // Pass the address of the aggregate copy on the stack either in a 5772 // physical register or in the parameter list area of the current stack 5773 // frame to the callee. 5774 Arg = PtrOff; 5775 } 5776 5777 // When useCRBits() is true, there can be i1 arguments. 5778 // It is because getRegisterType(MVT::i1) => MVT::i1, 5779 // and for other integer types getRegisterType() => MVT::i32. 5780 // Extend i1 and ensure callee will get i32. 5781 if (Arg.getValueType() == MVT::i1) 5782 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5783 dl, MVT::i32, Arg); 5784 5785 if (VA.isRegLoc()) { 5786 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5787 // Put argument in a physical register. 5788 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5789 bool IsLE = Subtarget.isLittleEndian(); 5790 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5791 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5792 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5793 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5794 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5795 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5796 SVal.getValue(0))); 5797 } else 5798 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5799 } else { 5800 // Put argument in the parameter list area of the current stack frame. 5801 assert(VA.isMemLoc()); 5802 unsigned LocMemOffset = VA.getLocMemOffset(); 5803 5804 if (!IsTailCall) { 5805 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5806 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5807 StackPtr, PtrOff); 5808 5809 MemOpChains.push_back( 5810 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5811 } else { 5812 // Calculate and remember argument location. 5813 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5814 TailCallArguments); 5815 } 5816 } 5817 } 5818 5819 if (!MemOpChains.empty()) 5820 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5821 5822 // Build a sequence of copy-to-reg nodes chained together with token chain 5823 // and flag operands which copy the outgoing args into the appropriate regs. 5824 SDValue InFlag; 5825 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5826 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5827 RegsToPass[i].second, InFlag); 5828 InFlag = Chain.getValue(1); 5829 } 5830 5831 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5832 // registers. 5833 if (IsVarArg) { 5834 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5835 SDValue Ops[] = { Chain, InFlag }; 5836 5837 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5838 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5839 5840 InFlag = Chain.getValue(1); 5841 } 5842 5843 if (IsTailCall) 5844 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5845 TailCallArguments); 5846 5847 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5848 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5849 } 5850 5851 // Copy an argument into memory, being careful to do this outside the 5852 // call sequence for the call to which the argument belongs. 5853 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5854 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5855 SelectionDAG &DAG, const SDLoc &dl) const { 5856 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5857 CallSeqStart.getNode()->getOperand(0), 5858 Flags, DAG, dl); 5859 // The MEMCPY must go outside the CALLSEQ_START..END. 5860 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5861 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5862 SDLoc(MemcpyCall)); 5863 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5864 NewCallSeqStart.getNode()); 5865 return NewCallSeqStart; 5866 } 5867 5868 SDValue PPCTargetLowering::LowerCall_64SVR4( 5869 SDValue Chain, SDValue Callee, CallFlags CFlags, 5870 const SmallVectorImpl<ISD::OutputArg> &Outs, 5871 const SmallVectorImpl<SDValue> &OutVals, 5872 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5873 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5874 const CallBase *CB) const { 5875 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5876 bool isLittleEndian = Subtarget.isLittleEndian(); 5877 unsigned NumOps = Outs.size(); 5878 bool IsSibCall = false; 5879 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5880 5881 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5882 unsigned PtrByteSize = 8; 5883 5884 MachineFunction &MF = DAG.getMachineFunction(); 5885 5886 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5887 IsSibCall = true; 5888 5889 // Mark this function as potentially containing a function that contains a 5890 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5891 // and restoring the callers stack pointer in this functions epilog. This is 5892 // done because by tail calling the called function might overwrite the value 5893 // in this function's (MF) stack pointer stack slot 0(SP). 5894 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5895 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5896 5897 assert(!(IsFastCall && CFlags.IsVarArg) && 5898 "fastcc not supported on varargs functions"); 5899 5900 // Count how many bytes are to be pushed on the stack, including the linkage 5901 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5902 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5903 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5904 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5905 unsigned NumBytes = LinkageSize; 5906 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5907 unsigned &QFPR_idx = FPR_idx; 5908 5909 static const MCPhysReg GPR[] = { 5910 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5911 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5912 }; 5913 static const MCPhysReg VR[] = { 5914 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5915 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5916 }; 5917 5918 const unsigned NumGPRs = array_lengthof(GPR); 5919 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5920 const unsigned NumVRs = array_lengthof(VR); 5921 const unsigned NumQFPRs = NumFPRs; 5922 5923 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5924 // can be passed to the callee in registers. 5925 // For the fast calling convention, there is another check below. 5926 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5927 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5928 if (!HasParameterArea) { 5929 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5930 unsigned AvailableFPRs = NumFPRs; 5931 unsigned AvailableVRs = NumVRs; 5932 unsigned NumBytesTmp = NumBytes; 5933 for (unsigned i = 0; i != NumOps; ++i) { 5934 if (Outs[i].Flags.isNest()) continue; 5935 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5936 PtrByteSize, LinkageSize, ParamAreaSize, 5937 NumBytesTmp, AvailableFPRs, AvailableVRs, 5938 Subtarget.hasQPX())) 5939 HasParameterArea = true; 5940 } 5941 } 5942 5943 // When using the fast calling convention, we don't provide backing for 5944 // arguments that will be in registers. 5945 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5946 5947 // Avoid allocating parameter area for fastcc functions if all the arguments 5948 // can be passed in the registers. 5949 if (IsFastCall) 5950 HasParameterArea = false; 5951 5952 // Add up all the space actually used. 5953 for (unsigned i = 0; i != NumOps; ++i) { 5954 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5955 EVT ArgVT = Outs[i].VT; 5956 EVT OrigVT = Outs[i].ArgVT; 5957 5958 if (Flags.isNest()) 5959 continue; 5960 5961 if (IsFastCall) { 5962 if (Flags.isByVal()) { 5963 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5964 if (NumGPRsUsed > NumGPRs) 5965 HasParameterArea = true; 5966 } else { 5967 switch (ArgVT.getSimpleVT().SimpleTy) { 5968 default: llvm_unreachable("Unexpected ValueType for argument!"); 5969 case MVT::i1: 5970 case MVT::i32: 5971 case MVT::i64: 5972 if (++NumGPRsUsed <= NumGPRs) 5973 continue; 5974 break; 5975 case MVT::v4i32: 5976 case MVT::v8i16: 5977 case MVT::v16i8: 5978 case MVT::v2f64: 5979 case MVT::v2i64: 5980 case MVT::v1i128: 5981 case MVT::f128: 5982 if (++NumVRsUsed <= NumVRs) 5983 continue; 5984 break; 5985 case MVT::v4f32: 5986 // When using QPX, this is handled like a FP register, otherwise, it 5987 // is an Altivec register. 5988 if (Subtarget.hasQPX()) { 5989 if (++NumFPRsUsed <= NumFPRs) 5990 continue; 5991 } else { 5992 if (++NumVRsUsed <= NumVRs) 5993 continue; 5994 } 5995 break; 5996 case MVT::f32: 5997 case MVT::f64: 5998 case MVT::v4f64: // QPX 5999 case MVT::v4i1: // QPX 6000 if (++NumFPRsUsed <= NumFPRs) 6001 continue; 6002 break; 6003 } 6004 HasParameterArea = true; 6005 } 6006 } 6007 6008 /* Respect alignment of argument on the stack. */ 6009 auto Alignement = 6010 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6011 NumBytes = alignTo(NumBytes, Alignement); 6012 6013 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6014 if (Flags.isInConsecutiveRegsLast()) 6015 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6016 } 6017 6018 unsigned NumBytesActuallyUsed = NumBytes; 6019 6020 // In the old ELFv1 ABI, 6021 // the prolog code of the callee may store up to 8 GPR argument registers to 6022 // the stack, allowing va_start to index over them in memory if its varargs. 6023 // Because we cannot tell if this is needed on the caller side, we have to 6024 // conservatively assume that it is needed. As such, make sure we have at 6025 // least enough stack space for the caller to store the 8 GPRs. 6026 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6027 // really requires memory operands, e.g. a vararg function. 6028 if (HasParameterArea) 6029 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6030 else 6031 NumBytes = LinkageSize; 6032 6033 // Tail call needs the stack to be aligned. 6034 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6035 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6036 6037 int SPDiff = 0; 6038 6039 // Calculate by how many bytes the stack has to be adjusted in case of tail 6040 // call optimization. 6041 if (!IsSibCall) 6042 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6043 6044 // To protect arguments on the stack from being clobbered in a tail call, 6045 // force all the loads to happen before doing any other lowering. 6046 if (CFlags.IsTailCall) 6047 Chain = DAG.getStackArgumentTokenFactor(Chain); 6048 6049 // Adjust the stack pointer for the new arguments... 6050 // These operations are automatically eliminated by the prolog/epilog pass 6051 if (!IsSibCall) 6052 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6053 SDValue CallSeqStart = Chain; 6054 6055 // Load the return address and frame pointer so it can be move somewhere else 6056 // later. 6057 SDValue LROp, FPOp; 6058 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6059 6060 // Set up a copy of the stack pointer for use loading and storing any 6061 // arguments that may not fit in the registers available for argument 6062 // passing. 6063 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6064 6065 // Figure out which arguments are going to go in registers, and which in 6066 // memory. Also, if this is a vararg function, floating point operations 6067 // must be stored to our stack, and loaded into integer regs as well, if 6068 // any integer regs are available for argument passing. 6069 unsigned ArgOffset = LinkageSize; 6070 6071 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6072 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6073 6074 SmallVector<SDValue, 8> MemOpChains; 6075 for (unsigned i = 0; i != NumOps; ++i) { 6076 SDValue Arg = OutVals[i]; 6077 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6078 EVT ArgVT = Outs[i].VT; 6079 EVT OrigVT = Outs[i].ArgVT; 6080 6081 // PtrOff will be used to store the current argument to the stack if a 6082 // register cannot be found for it. 6083 SDValue PtrOff; 6084 6085 // We re-align the argument offset for each argument, except when using the 6086 // fast calling convention, when we need to make sure we do that only when 6087 // we'll actually use a stack slot. 6088 auto ComputePtrOff = [&]() { 6089 /* Respect alignment of argument on the stack. */ 6090 auto Alignment = 6091 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6092 ArgOffset = alignTo(ArgOffset, Alignment); 6093 6094 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6095 6096 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6097 }; 6098 6099 if (!IsFastCall) { 6100 ComputePtrOff(); 6101 6102 /* Compute GPR index associated with argument offset. */ 6103 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6104 GPR_idx = std::min(GPR_idx, NumGPRs); 6105 } 6106 6107 // Promote integers to 64-bit values. 6108 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6109 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6110 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6111 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6112 } 6113 6114 // FIXME memcpy is used way more than necessary. Correctness first. 6115 // Note: "by value" is code for passing a structure by value, not 6116 // basic types. 6117 if (Flags.isByVal()) { 6118 // Note: Size includes alignment padding, so 6119 // struct x { short a; char b; } 6120 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6121 // These are the proper values we need for right-justifying the 6122 // aggregate in a parameter register. 6123 unsigned Size = Flags.getByValSize(); 6124 6125 // An empty aggregate parameter takes up no storage and no 6126 // registers. 6127 if (Size == 0) 6128 continue; 6129 6130 if (IsFastCall) 6131 ComputePtrOff(); 6132 6133 // All aggregates smaller than 8 bytes must be passed right-justified. 6134 if (Size==1 || Size==2 || Size==4) { 6135 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6136 if (GPR_idx != NumGPRs) { 6137 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6138 MachinePointerInfo(), VT); 6139 MemOpChains.push_back(Load.getValue(1)); 6140 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6141 6142 ArgOffset += PtrByteSize; 6143 continue; 6144 } 6145 } 6146 6147 if (GPR_idx == NumGPRs && Size < 8) { 6148 SDValue AddPtr = PtrOff; 6149 if (!isLittleEndian) { 6150 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6151 PtrOff.getValueType()); 6152 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6153 } 6154 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6155 CallSeqStart, 6156 Flags, DAG, dl); 6157 ArgOffset += PtrByteSize; 6158 continue; 6159 } 6160 // Copy entire object into memory. There are cases where gcc-generated 6161 // code assumes it is there, even if it could be put entirely into 6162 // registers. (This is not what the doc says.) 6163 6164 // FIXME: The above statement is likely due to a misunderstanding of the 6165 // documents. All arguments must be copied into the parameter area BY 6166 // THE CALLEE in the event that the callee takes the address of any 6167 // formal argument. That has not yet been implemented. However, it is 6168 // reasonable to use the stack area as a staging area for the register 6169 // load. 6170 6171 // Skip this for small aggregates, as we will use the same slot for a 6172 // right-justified copy, below. 6173 if (Size >= 8) 6174 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6175 CallSeqStart, 6176 Flags, DAG, dl); 6177 6178 // When a register is available, pass a small aggregate right-justified. 6179 if (Size < 8 && GPR_idx != NumGPRs) { 6180 // The easiest way to get this right-justified in a register 6181 // is to copy the structure into the rightmost portion of a 6182 // local variable slot, then load the whole slot into the 6183 // register. 6184 // FIXME: The memcpy seems to produce pretty awful code for 6185 // small aggregates, particularly for packed ones. 6186 // FIXME: It would be preferable to use the slot in the 6187 // parameter save area instead of a new local variable. 6188 SDValue AddPtr = PtrOff; 6189 if (!isLittleEndian) { 6190 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6191 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6192 } 6193 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6194 CallSeqStart, 6195 Flags, DAG, dl); 6196 6197 // Load the slot into the register. 6198 SDValue Load = 6199 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6200 MemOpChains.push_back(Load.getValue(1)); 6201 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6202 6203 // Done with this argument. 6204 ArgOffset += PtrByteSize; 6205 continue; 6206 } 6207 6208 // For aggregates larger than PtrByteSize, copy the pieces of the 6209 // object that fit into registers from the parameter save area. 6210 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6211 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6212 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6213 if (GPR_idx != NumGPRs) { 6214 SDValue Load = 6215 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6216 MemOpChains.push_back(Load.getValue(1)); 6217 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6218 ArgOffset += PtrByteSize; 6219 } else { 6220 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6221 break; 6222 } 6223 } 6224 continue; 6225 } 6226 6227 switch (Arg.getSimpleValueType().SimpleTy) { 6228 default: llvm_unreachable("Unexpected ValueType for argument!"); 6229 case MVT::i1: 6230 case MVT::i32: 6231 case MVT::i64: 6232 if (Flags.isNest()) { 6233 // The 'nest' parameter, if any, is passed in R11. 6234 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6235 break; 6236 } 6237 6238 // These can be scalar arguments or elements of an integer array type 6239 // passed directly. Clang may use those instead of "byval" aggregate 6240 // types to avoid forcing arguments to memory unnecessarily. 6241 if (GPR_idx != NumGPRs) { 6242 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6243 } else { 6244 if (IsFastCall) 6245 ComputePtrOff(); 6246 6247 assert(HasParameterArea && 6248 "Parameter area must exist to pass an argument in memory."); 6249 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6250 true, CFlags.IsTailCall, false, MemOpChains, 6251 TailCallArguments, dl); 6252 if (IsFastCall) 6253 ArgOffset += PtrByteSize; 6254 } 6255 if (!IsFastCall) 6256 ArgOffset += PtrByteSize; 6257 break; 6258 case MVT::f32: 6259 case MVT::f64: { 6260 // These can be scalar arguments or elements of a float array type 6261 // passed directly. The latter are used to implement ELFv2 homogenous 6262 // float aggregates. 6263 6264 // Named arguments go into FPRs first, and once they overflow, the 6265 // remaining arguments go into GPRs and then the parameter save area. 6266 // Unnamed arguments for vararg functions always go to GPRs and 6267 // then the parameter save area. For now, put all arguments to vararg 6268 // routines always in both locations (FPR *and* GPR or stack slot). 6269 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6270 bool NeededLoad = false; 6271 6272 // First load the argument into the next available FPR. 6273 if (FPR_idx != NumFPRs) 6274 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6275 6276 // Next, load the argument into GPR or stack slot if needed. 6277 if (!NeedGPROrStack) 6278 ; 6279 else if (GPR_idx != NumGPRs && !IsFastCall) { 6280 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6281 // once we support fp <-> gpr moves. 6282 6283 // In the non-vararg case, this can only ever happen in the 6284 // presence of f32 array types, since otherwise we never run 6285 // out of FPRs before running out of GPRs. 6286 SDValue ArgVal; 6287 6288 // Double values are always passed in a single GPR. 6289 if (Arg.getValueType() != MVT::f32) { 6290 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6291 6292 // Non-array float values are extended and passed in a GPR. 6293 } else if (!Flags.isInConsecutiveRegs()) { 6294 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6295 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6296 6297 // If we have an array of floats, we collect every odd element 6298 // together with its predecessor into one GPR. 6299 } else if (ArgOffset % PtrByteSize != 0) { 6300 SDValue Lo, Hi; 6301 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6302 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6303 if (!isLittleEndian) 6304 std::swap(Lo, Hi); 6305 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6306 6307 // The final element, if even, goes into the first half of a GPR. 6308 } else if (Flags.isInConsecutiveRegsLast()) { 6309 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6310 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6311 if (!isLittleEndian) 6312 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6313 DAG.getConstant(32, dl, MVT::i32)); 6314 6315 // Non-final even elements are skipped; they will be handled 6316 // together the with subsequent argument on the next go-around. 6317 } else 6318 ArgVal = SDValue(); 6319 6320 if (ArgVal.getNode()) 6321 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6322 } else { 6323 if (IsFastCall) 6324 ComputePtrOff(); 6325 6326 // Single-precision floating-point values are mapped to the 6327 // second (rightmost) word of the stack doubleword. 6328 if (Arg.getValueType() == MVT::f32 && 6329 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6330 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6331 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6332 } 6333 6334 assert(HasParameterArea && 6335 "Parameter area must exist to pass an argument in memory."); 6336 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6337 true, CFlags.IsTailCall, false, MemOpChains, 6338 TailCallArguments, dl); 6339 6340 NeededLoad = true; 6341 } 6342 // When passing an array of floats, the array occupies consecutive 6343 // space in the argument area; only round up to the next doubleword 6344 // at the end of the array. Otherwise, each float takes 8 bytes. 6345 if (!IsFastCall || NeededLoad) { 6346 ArgOffset += (Arg.getValueType() == MVT::f32 && 6347 Flags.isInConsecutiveRegs()) ? 4 : 8; 6348 if (Flags.isInConsecutiveRegsLast()) 6349 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6350 } 6351 break; 6352 } 6353 case MVT::v4f32: 6354 case MVT::v4i32: 6355 case MVT::v8i16: 6356 case MVT::v16i8: 6357 case MVT::v2f64: 6358 case MVT::v2i64: 6359 case MVT::v1i128: 6360 case MVT::f128: 6361 if (!Subtarget.hasQPX()) { 6362 // These can be scalar arguments or elements of a vector array type 6363 // passed directly. The latter are used to implement ELFv2 homogenous 6364 // vector aggregates. 6365 6366 // For a varargs call, named arguments go into VRs or on the stack as 6367 // usual; unnamed arguments always go to the stack or the corresponding 6368 // GPRs when within range. For now, we always put the value in both 6369 // locations (or even all three). 6370 if (CFlags.IsVarArg) { 6371 assert(HasParameterArea && 6372 "Parameter area must exist if we have a varargs call."); 6373 // We could elide this store in the case where the object fits 6374 // entirely in R registers. Maybe later. 6375 SDValue Store = 6376 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6377 MemOpChains.push_back(Store); 6378 if (VR_idx != NumVRs) { 6379 SDValue Load = 6380 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6381 MemOpChains.push_back(Load.getValue(1)); 6382 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6383 } 6384 ArgOffset += 16; 6385 for (unsigned i=0; i<16; i+=PtrByteSize) { 6386 if (GPR_idx == NumGPRs) 6387 break; 6388 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6389 DAG.getConstant(i, dl, PtrVT)); 6390 SDValue Load = 6391 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6392 MemOpChains.push_back(Load.getValue(1)); 6393 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6394 } 6395 break; 6396 } 6397 6398 // Non-varargs Altivec params go into VRs or on the stack. 6399 if (VR_idx != NumVRs) { 6400 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6401 } else { 6402 if (IsFastCall) 6403 ComputePtrOff(); 6404 6405 assert(HasParameterArea && 6406 "Parameter area must exist to pass an argument in memory."); 6407 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6408 true, CFlags.IsTailCall, true, MemOpChains, 6409 TailCallArguments, dl); 6410 if (IsFastCall) 6411 ArgOffset += 16; 6412 } 6413 6414 if (!IsFastCall) 6415 ArgOffset += 16; 6416 break; 6417 } // not QPX 6418 6419 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6420 "Invalid QPX parameter type"); 6421 6422 LLVM_FALLTHROUGH; 6423 case MVT::v4f64: 6424 case MVT::v4i1: { 6425 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6426 if (CFlags.IsVarArg) { 6427 assert(HasParameterArea && 6428 "Parameter area must exist if we have a varargs call."); 6429 // We could elide this store in the case where the object fits 6430 // entirely in R registers. Maybe later. 6431 SDValue Store = 6432 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6433 MemOpChains.push_back(Store); 6434 if (QFPR_idx != NumQFPRs) { 6435 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6436 PtrOff, MachinePointerInfo()); 6437 MemOpChains.push_back(Load.getValue(1)); 6438 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6439 } 6440 ArgOffset += (IsF32 ? 16 : 32); 6441 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6442 if (GPR_idx == NumGPRs) 6443 break; 6444 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6445 DAG.getConstant(i, dl, PtrVT)); 6446 SDValue Load = 6447 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6448 MemOpChains.push_back(Load.getValue(1)); 6449 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6450 } 6451 break; 6452 } 6453 6454 // Non-varargs QPX params go into registers or on the stack. 6455 if (QFPR_idx != NumQFPRs) { 6456 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6457 } else { 6458 if (IsFastCall) 6459 ComputePtrOff(); 6460 6461 assert(HasParameterArea && 6462 "Parameter area must exist to pass an argument in memory."); 6463 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6464 true, CFlags.IsTailCall, true, MemOpChains, 6465 TailCallArguments, dl); 6466 if (IsFastCall) 6467 ArgOffset += (IsF32 ? 16 : 32); 6468 } 6469 6470 if (!IsFastCall) 6471 ArgOffset += (IsF32 ? 16 : 32); 6472 break; 6473 } 6474 } 6475 } 6476 6477 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6478 "mismatch in size of parameter area"); 6479 (void)NumBytesActuallyUsed; 6480 6481 if (!MemOpChains.empty()) 6482 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6483 6484 // Check if this is an indirect call (MTCTR/BCTRL). 6485 // See prepareDescriptorIndirectCall and buildCallOperands for more 6486 // information about calls through function pointers in the 64-bit SVR4 ABI. 6487 if (CFlags.IsIndirect) { 6488 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6489 // Load r2 into a virtual register and store it to the TOC save area. 6490 setUsesTOCBasePtr(DAG); 6491 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6492 // TOC save area offset. 6493 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6494 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6495 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6496 Chain = DAG.getStore( 6497 Val.getValue(1), dl, Val, AddPtr, 6498 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6499 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6500 // This does not mean the MTCTR instruction must use R12; it's easier 6501 // to model this as an extra parameter, so do that. 6502 if (isELFv2ABI && !CFlags.IsPatchPoint) 6503 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6504 } 6505 6506 // Build a sequence of copy-to-reg nodes chained together with token chain 6507 // and flag operands which copy the outgoing args into the appropriate regs. 6508 SDValue InFlag; 6509 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6510 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6511 RegsToPass[i].second, InFlag); 6512 InFlag = Chain.getValue(1); 6513 } 6514 6515 if (CFlags.IsTailCall && !IsSibCall) 6516 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6517 TailCallArguments); 6518 6519 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6520 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6521 } 6522 6523 SDValue PPCTargetLowering::LowerCall_Darwin( 6524 SDValue Chain, SDValue Callee, CallFlags CFlags, 6525 const SmallVectorImpl<ISD::OutputArg> &Outs, 6526 const SmallVectorImpl<SDValue> &OutVals, 6527 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6528 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6529 const CallBase *CB) const { 6530 unsigned NumOps = Outs.size(); 6531 6532 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6533 bool isPPC64 = PtrVT == MVT::i64; 6534 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6535 6536 MachineFunction &MF = DAG.getMachineFunction(); 6537 6538 // Mark this function as potentially containing a function that contains a 6539 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6540 // and restoring the callers stack pointer in this functions epilog. This is 6541 // done because by tail calling the called function might overwrite the value 6542 // in this function's (MF) stack pointer stack slot 0(SP). 6543 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6544 CFlags.CallConv == CallingConv::Fast) 6545 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6546 6547 // Count how many bytes are to be pushed on the stack, including the linkage 6548 // area, and parameter passing area. We start with 24/48 bytes, which is 6549 // prereserved space for [SP][CR][LR][3 x unused]. 6550 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6551 unsigned NumBytes = LinkageSize; 6552 6553 // Add up all the space actually used. 6554 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6555 // they all go in registers, but we must reserve stack space for them for 6556 // possible use by the caller. In varargs or 64-bit calls, parameters are 6557 // assigned stack space in order, with padding so Altivec parameters are 6558 // 16-byte aligned. 6559 unsigned nAltivecParamsAtEnd = 0; 6560 for (unsigned i = 0; i != NumOps; ++i) { 6561 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6562 EVT ArgVT = Outs[i].VT; 6563 // Varargs Altivec parameters are padded to a 16 byte boundary. 6564 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6565 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6566 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6567 if (!CFlags.IsVarArg && !isPPC64) { 6568 // Non-varargs Altivec parameters go after all the non-Altivec 6569 // parameters; handle those later so we know how much padding we need. 6570 nAltivecParamsAtEnd++; 6571 continue; 6572 } 6573 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6574 NumBytes = ((NumBytes+15)/16)*16; 6575 } 6576 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6577 } 6578 6579 // Allow for Altivec parameters at the end, if needed. 6580 if (nAltivecParamsAtEnd) { 6581 NumBytes = ((NumBytes+15)/16)*16; 6582 NumBytes += 16*nAltivecParamsAtEnd; 6583 } 6584 6585 // The prolog code of the callee may store up to 8 GPR argument registers to 6586 // the stack, allowing va_start to index over them in memory if its varargs. 6587 // Because we cannot tell if this is needed on the caller side, we have to 6588 // conservatively assume that it is needed. As such, make sure we have at 6589 // least enough stack space for the caller to store the 8 GPRs. 6590 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6591 6592 // Tail call needs the stack to be aligned. 6593 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6594 CFlags.CallConv == CallingConv::Fast) 6595 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6596 6597 // Calculate by how many bytes the stack has to be adjusted in case of tail 6598 // call optimization. 6599 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6600 6601 // To protect arguments on the stack from being clobbered in a tail call, 6602 // force all the loads to happen before doing any other lowering. 6603 if (CFlags.IsTailCall) 6604 Chain = DAG.getStackArgumentTokenFactor(Chain); 6605 6606 // Adjust the stack pointer for the new arguments... 6607 // These operations are automatically eliminated by the prolog/epilog pass 6608 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6609 SDValue CallSeqStart = Chain; 6610 6611 // Load the return address and frame pointer so it can be move somewhere else 6612 // later. 6613 SDValue LROp, FPOp; 6614 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6615 6616 // Set up a copy of the stack pointer for use loading and storing any 6617 // arguments that may not fit in the registers available for argument 6618 // passing. 6619 SDValue StackPtr; 6620 if (isPPC64) 6621 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6622 else 6623 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6624 6625 // Figure out which arguments are going to go in registers, and which in 6626 // memory. Also, if this is a vararg function, floating point operations 6627 // must be stored to our stack, and loaded into integer regs as well, if 6628 // any integer regs are available for argument passing. 6629 unsigned ArgOffset = LinkageSize; 6630 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6631 6632 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6633 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6634 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6635 }; 6636 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6637 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6638 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6639 }; 6640 static const MCPhysReg VR[] = { 6641 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6642 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6643 }; 6644 const unsigned NumGPRs = array_lengthof(GPR_32); 6645 const unsigned NumFPRs = 13; 6646 const unsigned NumVRs = array_lengthof(VR); 6647 6648 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6649 6650 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6651 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6652 6653 SmallVector<SDValue, 8> MemOpChains; 6654 for (unsigned i = 0; i != NumOps; ++i) { 6655 SDValue Arg = OutVals[i]; 6656 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6657 6658 // PtrOff will be used to store the current argument to the stack if a 6659 // register cannot be found for it. 6660 SDValue PtrOff; 6661 6662 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6663 6664 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6665 6666 // On PPC64, promote integers to 64-bit values. 6667 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6668 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6669 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6670 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6671 } 6672 6673 // FIXME memcpy is used way more than necessary. Correctness first. 6674 // Note: "by value" is code for passing a structure by value, not 6675 // basic types. 6676 if (Flags.isByVal()) { 6677 unsigned Size = Flags.getByValSize(); 6678 // Very small objects are passed right-justified. Everything else is 6679 // passed left-justified. 6680 if (Size==1 || Size==2) { 6681 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6682 if (GPR_idx != NumGPRs) { 6683 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6684 MachinePointerInfo(), VT); 6685 MemOpChains.push_back(Load.getValue(1)); 6686 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6687 6688 ArgOffset += PtrByteSize; 6689 } else { 6690 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6691 PtrOff.getValueType()); 6692 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6693 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6694 CallSeqStart, 6695 Flags, DAG, dl); 6696 ArgOffset += PtrByteSize; 6697 } 6698 continue; 6699 } 6700 // Copy entire object into memory. There are cases where gcc-generated 6701 // code assumes it is there, even if it could be put entirely into 6702 // registers. (This is not what the doc says.) 6703 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6704 CallSeqStart, 6705 Flags, DAG, dl); 6706 6707 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6708 // copy the pieces of the object that fit into registers from the 6709 // parameter save area. 6710 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6711 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6712 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6713 if (GPR_idx != NumGPRs) { 6714 SDValue Load = 6715 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6716 MemOpChains.push_back(Load.getValue(1)); 6717 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6718 ArgOffset += PtrByteSize; 6719 } else { 6720 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6721 break; 6722 } 6723 } 6724 continue; 6725 } 6726 6727 switch (Arg.getSimpleValueType().SimpleTy) { 6728 default: llvm_unreachable("Unexpected ValueType for argument!"); 6729 case MVT::i1: 6730 case MVT::i32: 6731 case MVT::i64: 6732 if (GPR_idx != NumGPRs) { 6733 if (Arg.getValueType() == MVT::i1) 6734 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6735 6736 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6737 } else { 6738 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6739 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6740 TailCallArguments, dl); 6741 } 6742 ArgOffset += PtrByteSize; 6743 break; 6744 case MVT::f32: 6745 case MVT::f64: 6746 if (FPR_idx != NumFPRs) { 6747 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6748 6749 if (CFlags.IsVarArg) { 6750 SDValue Store = 6751 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6752 MemOpChains.push_back(Store); 6753 6754 // Float varargs are always shadowed in available integer registers 6755 if (GPR_idx != NumGPRs) { 6756 SDValue Load = 6757 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6758 MemOpChains.push_back(Load.getValue(1)); 6759 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6760 } 6761 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6762 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6763 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6764 SDValue Load = 6765 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6766 MemOpChains.push_back(Load.getValue(1)); 6767 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6768 } 6769 } else { 6770 // If we have any FPRs remaining, we may also have GPRs remaining. 6771 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6772 // GPRs. 6773 if (GPR_idx != NumGPRs) 6774 ++GPR_idx; 6775 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6776 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6777 ++GPR_idx; 6778 } 6779 } else 6780 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6781 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6782 TailCallArguments, dl); 6783 if (isPPC64) 6784 ArgOffset += 8; 6785 else 6786 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6787 break; 6788 case MVT::v4f32: 6789 case MVT::v4i32: 6790 case MVT::v8i16: 6791 case MVT::v16i8: 6792 if (CFlags.IsVarArg) { 6793 // These go aligned on the stack, or in the corresponding R registers 6794 // when within range. The Darwin PPC ABI doc claims they also go in 6795 // V registers; in fact gcc does this only for arguments that are 6796 // prototyped, not for those that match the ... We do it for all 6797 // arguments, seems to work. 6798 while (ArgOffset % 16 !=0) { 6799 ArgOffset += PtrByteSize; 6800 if (GPR_idx != NumGPRs) 6801 GPR_idx++; 6802 } 6803 // We could elide this store in the case where the object fits 6804 // entirely in R registers. Maybe later. 6805 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6806 DAG.getConstant(ArgOffset, dl, PtrVT)); 6807 SDValue Store = 6808 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6809 MemOpChains.push_back(Store); 6810 if (VR_idx != NumVRs) { 6811 SDValue Load = 6812 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6813 MemOpChains.push_back(Load.getValue(1)); 6814 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6815 } 6816 ArgOffset += 16; 6817 for (unsigned i=0; i<16; i+=PtrByteSize) { 6818 if (GPR_idx == NumGPRs) 6819 break; 6820 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6821 DAG.getConstant(i, dl, PtrVT)); 6822 SDValue Load = 6823 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6824 MemOpChains.push_back(Load.getValue(1)); 6825 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6826 } 6827 break; 6828 } 6829 6830 // Non-varargs Altivec params generally go in registers, but have 6831 // stack space allocated at the end. 6832 if (VR_idx != NumVRs) { 6833 // Doesn't have GPR space allocated. 6834 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6835 } else if (nAltivecParamsAtEnd==0) { 6836 // We are emitting Altivec params in order. 6837 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6838 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6839 TailCallArguments, dl); 6840 ArgOffset += 16; 6841 } 6842 break; 6843 } 6844 } 6845 // If all Altivec parameters fit in registers, as they usually do, 6846 // they get stack space following the non-Altivec parameters. We 6847 // don't track this here because nobody below needs it. 6848 // If there are more Altivec parameters than fit in registers emit 6849 // the stores here. 6850 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6851 unsigned j = 0; 6852 // Offset is aligned; skip 1st 12 params which go in V registers. 6853 ArgOffset = ((ArgOffset+15)/16)*16; 6854 ArgOffset += 12*16; 6855 for (unsigned i = 0; i != NumOps; ++i) { 6856 SDValue Arg = OutVals[i]; 6857 EVT ArgType = Outs[i].VT; 6858 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6859 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6860 if (++j > NumVRs) { 6861 SDValue PtrOff; 6862 // We are emitting Altivec params in order. 6863 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6864 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6865 TailCallArguments, dl); 6866 ArgOffset += 16; 6867 } 6868 } 6869 } 6870 } 6871 6872 if (!MemOpChains.empty()) 6873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6874 6875 // On Darwin, R12 must contain the address of an indirect callee. This does 6876 // not mean the MTCTR instruction must use R12; it's easier to model this as 6877 // an extra parameter, so do that. 6878 if (CFlags.IsIndirect) { 6879 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6880 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6881 PPC::R12), Callee)); 6882 } 6883 6884 // Build a sequence of copy-to-reg nodes chained together with token chain 6885 // and flag operands which copy the outgoing args into the appropriate regs. 6886 SDValue InFlag; 6887 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6888 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6889 RegsToPass[i].second, InFlag); 6890 InFlag = Chain.getValue(1); 6891 } 6892 6893 if (CFlags.IsTailCall) 6894 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6895 TailCallArguments); 6896 6897 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6898 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6899 } 6900 6901 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6902 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6903 CCState &State) { 6904 6905 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6906 State.getMachineFunction().getSubtarget()); 6907 const bool IsPPC64 = Subtarget.isPPC64(); 6908 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6909 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6910 6911 assert((!ValVT.isInteger() || 6912 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6913 "Integer argument exceeds register size: should have been legalized"); 6914 6915 if (ValVT == MVT::f128) 6916 report_fatal_error("f128 is unimplemented on AIX."); 6917 6918 if (ArgFlags.isNest()) 6919 report_fatal_error("Nest arguments are unimplemented."); 6920 6921 if (ValVT.isVector() || LocVT.isVector()) 6922 report_fatal_error("Vector arguments are unimplemented on AIX."); 6923 6924 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6925 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6926 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6927 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6928 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6929 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6930 6931 if (ArgFlags.isByVal()) { 6932 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 6933 report_fatal_error("Pass-by-value arguments with alignment greater than " 6934 "register width are not supported."); 6935 6936 const unsigned ByValSize = ArgFlags.getByValSize(); 6937 6938 // An empty aggregate parameter takes up no storage and no registers, 6939 // but needs a MemLoc for a stack slot for the formal arguments side. 6940 if (ByValSize == 0) { 6941 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6942 State.getNextStackOffset(), RegVT, 6943 LocInfo)); 6944 return false; 6945 } 6946 6947 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 6948 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 6949 for (const unsigned E = Offset + StackSize; Offset < E; 6950 Offset += PtrByteSize) { 6951 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6952 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6953 else { 6954 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6955 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6956 LocInfo)); 6957 break; 6958 } 6959 } 6960 return false; 6961 } 6962 6963 // Arguments always reserve parameter save area. 6964 switch (ValVT.SimpleTy) { 6965 default: 6966 report_fatal_error("Unhandled value type for argument."); 6967 case MVT::i64: 6968 // i64 arguments should have been split to i32 for PPC32. 6969 assert(IsPPC64 && "PPC32 should have split i64 values."); 6970 LLVM_FALLTHROUGH; 6971 case MVT::i1: 6972 case MVT::i32: { 6973 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 6974 // AIX integer arguments are always passed in register width. 6975 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6976 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6977 : CCValAssign::LocInfo::ZExt; 6978 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6979 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6980 else 6981 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6982 6983 return false; 6984 } 6985 case MVT::f32: 6986 case MVT::f64: { 6987 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6988 const unsigned StoreSize = LocVT.getStoreSize(); 6989 // Floats are always 4-byte aligned in the PSA on AIX. 6990 // This includes f64 in 64-bit mode for ABI compatibility. 6991 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6992 unsigned FReg = State.AllocateReg(FPR); 6993 if (FReg) 6994 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6995 6996 // Reserve and initialize GPRs or initialize the PSA as required. 6997 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 6998 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6999 assert(FReg && "An FPR should be available when a GPR is reserved."); 7000 if (State.isVarArg()) { 7001 // Successfully reserved GPRs are only initialized for vararg calls. 7002 // Custom handling is required for: 7003 // f64 in PPC32 needs to be split into 2 GPRs. 7004 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7005 State.addLoc( 7006 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7007 } 7008 } else { 7009 // If there are insufficient GPRs, the PSA needs to be initialized. 7010 // Initialization occurs even if an FPR was initialized for 7011 // compatibility with the AIX XL compiler. The full memory for the 7012 // argument will be initialized even if a prior word is saved in GPR. 7013 // A custom memLoc is used when the argument also passes in FPR so 7014 // that the callee handling can skip over it easily. 7015 State.addLoc( 7016 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7017 LocInfo) 7018 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7019 break; 7020 } 7021 } 7022 7023 return false; 7024 } 7025 } 7026 return true; 7027 } 7028 7029 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7030 bool IsPPC64) { 7031 assert((IsPPC64 || SVT != MVT::i64) && 7032 "i64 should have been split for 32-bit codegen."); 7033 7034 switch (SVT) { 7035 default: 7036 report_fatal_error("Unexpected value type for formal argument"); 7037 case MVT::i1: 7038 case MVT::i32: 7039 case MVT::i64: 7040 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7041 case MVT::f32: 7042 return &PPC::F4RCRegClass; 7043 case MVT::f64: 7044 return &PPC::F8RCRegClass; 7045 } 7046 } 7047 7048 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7049 SelectionDAG &DAG, SDValue ArgValue, 7050 MVT LocVT, const SDLoc &dl) { 7051 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7052 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7053 7054 if (Flags.isSExt()) 7055 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7056 DAG.getValueType(ValVT)); 7057 else if (Flags.isZExt()) 7058 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7059 DAG.getValueType(ValVT)); 7060 7061 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7062 } 7063 7064 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7065 const unsigned LASize = FL->getLinkageSize(); 7066 7067 if (PPC::GPRCRegClass.contains(Reg)) { 7068 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7069 "Reg must be a valid argument register!"); 7070 return LASize + 4 * (Reg - PPC::R3); 7071 } 7072 7073 if (PPC::G8RCRegClass.contains(Reg)) { 7074 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7075 "Reg must be a valid argument register!"); 7076 return LASize + 8 * (Reg - PPC::X3); 7077 } 7078 7079 llvm_unreachable("Only general purpose registers expected."); 7080 } 7081 7082 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7083 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7084 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7085 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7086 7087 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7088 CallConv == CallingConv::Fast) && 7089 "Unexpected calling convention!"); 7090 7091 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7092 report_fatal_error("Tail call support is unimplemented on AIX."); 7093 7094 if (useSoftFloat()) 7095 report_fatal_error("Soft float support is unimplemented on AIX."); 7096 7097 const PPCSubtarget &Subtarget = 7098 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7099 if (Subtarget.hasQPX()) 7100 report_fatal_error("QPX support is not supported on AIX."); 7101 7102 const bool IsPPC64 = Subtarget.isPPC64(); 7103 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7104 7105 // Assign locations to all of the incoming arguments. 7106 SmallVector<CCValAssign, 16> ArgLocs; 7107 MachineFunction &MF = DAG.getMachineFunction(); 7108 MachineFrameInfo &MFI = MF.getFrameInfo(); 7109 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7110 7111 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7112 // Reserve space for the linkage area on the stack. 7113 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7114 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7115 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7116 7117 SmallVector<SDValue, 8> MemOps; 7118 7119 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7120 CCValAssign &VA = ArgLocs[I++]; 7121 MVT LocVT = VA.getLocVT(); 7122 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7123 7124 // For compatibility with the AIX XL compiler, the float args in the 7125 // parameter save area are initialized even if the argument is available 7126 // in register. The caller is required to initialize both the register 7127 // and memory, however, the callee can choose to expect it in either. 7128 // The memloc is dismissed here because the argument is retrieved from 7129 // the register. 7130 if (VA.isMemLoc() && VA.needsCustom()) 7131 continue; 7132 7133 if (Flags.isByVal() && VA.isMemLoc()) { 7134 if (Flags.getByValSize() != 0) 7135 report_fatal_error( 7136 "ByVal arguments passed on stack not implemented yet"); 7137 7138 const int FI = MF.getFrameInfo().CreateFixedObject( 7139 PtrByteSize, VA.getLocMemOffset(), /* IsImmutable */ false, 7140 /* IsAliased */ true); 7141 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7142 InVals.push_back(FIN); 7143 7144 continue; 7145 } 7146 7147 if (Flags.isByVal()) { 7148 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7149 7150 const MCPhysReg ArgReg = VA.getLocReg(); 7151 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7152 7153 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7154 report_fatal_error("Over aligned byvals not supported yet."); 7155 7156 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7157 const int FI = MF.getFrameInfo().CreateFixedObject( 7158 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7159 /* IsAliased */ true); 7160 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7161 InVals.push_back(FIN); 7162 7163 // Add live ins for all the RegLocs for the same ByVal. 7164 const TargetRegisterClass *RegClass = 7165 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7166 7167 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7168 unsigned Offset) { 7169 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7170 // Since the callers side has left justified the aggregate in the 7171 // register, we can simply store the entire register into the stack 7172 // slot. 7173 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7174 // The store to the fixedstack object is needed becuase accessing a 7175 // field of the ByVal will use a gep and load. Ideally we will optimize 7176 // to extracting the value from the register directly, and elide the 7177 // stores when the arguments address is not taken, but that will need to 7178 // be future work. 7179 SDValue Store = 7180 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7181 DAG.getObjectPtrOffset(dl, FIN, Offset), 7182 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7183 7184 MemOps.push_back(Store); 7185 }; 7186 7187 unsigned Offset = 0; 7188 HandleRegLoc(VA.getLocReg(), Offset); 7189 Offset += PtrByteSize; 7190 for (; Offset != StackSize; Offset += PtrByteSize) { 7191 assert(I != End && 7192 "Expecting enough RegLocs to copy entire ByVal arg."); 7193 7194 if (!ArgLocs[I].isRegLoc()) 7195 report_fatal_error("Passing ByVals split between registers and stack " 7196 "not yet implemented."); 7197 7198 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7199 "Expecting more RegLocs for ByVal argument."); 7200 7201 const CCValAssign RL = ArgLocs[I++]; 7202 HandleRegLoc(RL.getLocReg(), Offset); 7203 } 7204 continue; 7205 } 7206 7207 EVT ValVT = VA.getValVT(); 7208 if (VA.isRegLoc() && !VA.needsCustom()) { 7209 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7210 unsigned VReg = 7211 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7212 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7213 if (ValVT.isScalarInteger() && 7214 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7215 ArgValue = 7216 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7217 } 7218 InVals.push_back(ArgValue); 7219 continue; 7220 } 7221 if (VA.isMemLoc()) { 7222 const unsigned LocSize = LocVT.getStoreSize(); 7223 const unsigned ValSize = ValVT.getStoreSize(); 7224 assert((ValSize <= LocSize) && 7225 "Object size is larger than size of MemLoc"); 7226 int CurArgOffset = VA.getLocMemOffset(); 7227 // Objects are right-justified because AIX is big-endian. 7228 if (LocSize > ValSize) 7229 CurArgOffset += LocSize - ValSize; 7230 // Potential tail calls could cause overwriting of argument stack slots. 7231 const bool IsImmutable = 7232 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7233 (CallConv == CallingConv::Fast)); 7234 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7235 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7236 SDValue ArgValue = 7237 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7238 InVals.push_back(ArgValue); 7239 continue; 7240 } 7241 } 7242 7243 // On AIX a minimum of 8 words is saved to the parameter save area. 7244 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7245 // Area that is at least reserved in the caller of this function. 7246 unsigned CallerReservedArea = 7247 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7248 7249 // Set the size that is at least reserved in caller of this function. Tail 7250 // call optimized function's reserved stack space needs to be aligned so 7251 // that taking the difference between two stack areas will result in an 7252 // aligned stack. 7253 CallerReservedArea = 7254 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7255 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7256 FuncInfo->setMinReservedArea(CallerReservedArea); 7257 7258 if (isVarArg) { 7259 FuncInfo->setVarArgsFrameIndex( 7260 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7261 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7262 7263 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7264 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7265 7266 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7267 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7268 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7269 7270 // The fixed integer arguments of a variadic function are stored to the 7271 // VarArgsFrameIndex on the stack so that they may be loaded by 7272 // dereferencing the result of va_next. 7273 for (unsigned GPRIndex = 7274 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7275 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7276 7277 const unsigned VReg = 7278 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7279 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7280 7281 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7282 SDValue Store = 7283 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7284 MemOps.push_back(Store); 7285 // Increment the address for the next argument to store. 7286 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7287 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7288 } 7289 } 7290 7291 if (!MemOps.empty()) 7292 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7293 7294 return Chain; 7295 } 7296 7297 SDValue PPCTargetLowering::LowerCall_AIX( 7298 SDValue Chain, SDValue Callee, CallFlags CFlags, 7299 const SmallVectorImpl<ISD::OutputArg> &Outs, 7300 const SmallVectorImpl<SDValue> &OutVals, 7301 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7302 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7303 const CallBase *CB) const { 7304 7305 assert((CFlags.CallConv == CallingConv::C || 7306 CFlags.CallConv == CallingConv::Cold || 7307 CFlags.CallConv == CallingConv::Fast) && 7308 "Unexpected calling convention!"); 7309 7310 if (CFlags.IsPatchPoint) 7311 report_fatal_error("This call type is unimplemented on AIX."); 7312 7313 const PPCSubtarget& Subtarget = 7314 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7315 if (Subtarget.hasQPX()) 7316 report_fatal_error("QPX is not supported on AIX."); 7317 if (Subtarget.hasAltivec()) 7318 report_fatal_error("Altivec support is unimplemented on AIX."); 7319 7320 MachineFunction &MF = DAG.getMachineFunction(); 7321 SmallVector<CCValAssign, 16> ArgLocs; 7322 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7323 *DAG.getContext()); 7324 7325 // Reserve space for the linkage save area (LSA) on the stack. 7326 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7327 // [SP][CR][LR][2 x reserved][TOC]. 7328 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7329 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7330 const bool IsPPC64 = Subtarget.isPPC64(); 7331 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7332 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7333 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7334 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7335 7336 // The prolog code of the callee may store up to 8 GPR argument registers to 7337 // the stack, allowing va_start to index over them in memory if the callee 7338 // is variadic. 7339 // Because we cannot tell if this is needed on the caller side, we have to 7340 // conservatively assume that it is needed. As such, make sure we have at 7341 // least enough stack space for the caller to store the 8 GPRs. 7342 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7343 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7344 CCInfo.getNextStackOffset()); 7345 7346 // Adjust the stack pointer for the new arguments... 7347 // These operations are automatically eliminated by the prolog/epilog pass. 7348 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7349 SDValue CallSeqStart = Chain; 7350 7351 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7352 SmallVector<SDValue, 8> MemOpChains; 7353 7354 // Set up a copy of the stack pointer for loading and storing any 7355 // arguments that may not fit in the registers available for argument 7356 // passing. 7357 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7358 : DAG.getRegister(PPC::R1, MVT::i32); 7359 7360 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7361 const unsigned ValNo = ArgLocs[I].getValNo(); 7362 SDValue Arg = OutVals[ValNo]; 7363 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7364 7365 if (Flags.isByVal()) { 7366 const unsigned ByValSize = Flags.getByValSize(); 7367 7368 // Nothing to do for zero-sized ByVals on the caller side. 7369 if (!ByValSize) { 7370 ++I; 7371 continue; 7372 } 7373 7374 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7375 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7376 (LoadOffset != 0) 7377 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7378 : Arg, 7379 MachinePointerInfo(), VT); 7380 }; 7381 7382 unsigned LoadOffset = 0; 7383 7384 // Initialize registers, which are fully occupied by the by-val argument. 7385 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7386 SDValue Load = GetLoad(PtrVT, LoadOffset); 7387 MemOpChains.push_back(Load.getValue(1)); 7388 LoadOffset += PtrByteSize; 7389 const CCValAssign &ByValVA = ArgLocs[I++]; 7390 assert(ByValVA.getValNo() == ValNo && 7391 "Unexpected location for pass-by-value argument."); 7392 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7393 } 7394 7395 if (LoadOffset == ByValSize) 7396 continue; 7397 7398 // There must be one more loc to handle the remainder. 7399 assert(ArgLocs[I].getValNo() == ValNo && 7400 "Expected additional location for by-value argument."); 7401 7402 if (ArgLocs[I].isMemLoc()) { 7403 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7404 const CCValAssign &ByValVA = ArgLocs[I++]; 7405 ISD::ArgFlagsTy MemcpyFlags = Flags; 7406 // Only memcpy the bytes that don't pass in register. 7407 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7408 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7409 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7410 : Arg, 7411 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7412 CallSeqStart, MemcpyFlags, DAG, dl); 7413 continue; 7414 } 7415 7416 // Initialize the final register residue. 7417 // Any residue that occupies the final by-val arg register must be 7418 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7419 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7420 // 2 and 1 byte loads. 7421 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7422 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7423 "Unexpected register residue for by-value argument."); 7424 SDValue ResidueVal; 7425 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7426 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7427 const MVT VT = 7428 N == 1 ? MVT::i8 7429 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7430 SDValue Load = GetLoad(VT, LoadOffset); 7431 MemOpChains.push_back(Load.getValue(1)); 7432 LoadOffset += N; 7433 Bytes += N; 7434 7435 // By-val arguments are passed left-justfied in register. 7436 // Every load here needs to be shifted, otherwise a full register load 7437 // should have been used. 7438 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7439 "Unexpected load emitted during handling of pass-by-value " 7440 "argument."); 7441 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7442 EVT ShiftAmountTy = 7443 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7444 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7445 SDValue ShiftedLoad = 7446 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7447 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7448 ShiftedLoad) 7449 : ShiftedLoad; 7450 } 7451 7452 const CCValAssign &ByValVA = ArgLocs[I++]; 7453 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7454 continue; 7455 } 7456 7457 CCValAssign &VA = ArgLocs[I++]; 7458 const MVT LocVT = VA.getLocVT(); 7459 const MVT ValVT = VA.getValVT(); 7460 7461 switch (VA.getLocInfo()) { 7462 default: 7463 report_fatal_error("Unexpected argument extension type."); 7464 case CCValAssign::Full: 7465 break; 7466 case CCValAssign::ZExt: 7467 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7468 break; 7469 case CCValAssign::SExt: 7470 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7471 break; 7472 } 7473 7474 if (VA.isRegLoc() && !VA.needsCustom()) { 7475 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7476 continue; 7477 } 7478 7479 if (VA.isMemLoc()) { 7480 SDValue PtrOff = 7481 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7482 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7483 MemOpChains.push_back( 7484 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7485 7486 continue; 7487 } 7488 7489 // Custom handling is used for GPR initializations for vararg float 7490 // arguments. 7491 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7492 ValVT.isFloatingPoint() && LocVT.isInteger() && 7493 "Unexpected register handling for calling convention."); 7494 7495 SDValue ArgAsInt = 7496 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7497 7498 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7499 // f32 in 32-bit GPR 7500 // f64 in 64-bit GPR 7501 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7502 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7503 // f32 in 64-bit GPR. 7504 RegsToPass.push_back(std::make_pair( 7505 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7506 else { 7507 // f64 in two 32-bit GPRs 7508 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7509 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7510 "Unexpected custom register for argument!"); 7511 CCValAssign &GPR1 = VA; 7512 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7513 DAG.getConstant(32, dl, MVT::i8)); 7514 RegsToPass.push_back(std::make_pair( 7515 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7516 7517 if (I != E) { 7518 // If only 1 GPR was available, there will only be one custom GPR and 7519 // the argument will also pass in memory. 7520 CCValAssign &PeekArg = ArgLocs[I]; 7521 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7522 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7523 CCValAssign &GPR2 = ArgLocs[I++]; 7524 RegsToPass.push_back(std::make_pair( 7525 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7526 } 7527 } 7528 } 7529 } 7530 7531 if (!MemOpChains.empty()) 7532 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7533 7534 // For indirect calls, we need to save the TOC base to the stack for 7535 // restoration after the call. 7536 if (CFlags.IsIndirect) { 7537 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7538 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7539 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7540 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7541 const unsigned TOCSaveOffset = 7542 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7543 7544 setUsesTOCBasePtr(DAG); 7545 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7546 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7547 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7548 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7549 Chain = DAG.getStore( 7550 Val.getValue(1), dl, Val, AddPtr, 7551 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7552 } 7553 7554 // Build a sequence of copy-to-reg nodes chained together with token chain 7555 // and flag operands which copy the outgoing args into the appropriate regs. 7556 SDValue InFlag; 7557 for (auto Reg : RegsToPass) { 7558 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7559 InFlag = Chain.getValue(1); 7560 } 7561 7562 const int SPDiff = 0; 7563 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7564 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7565 } 7566 7567 bool 7568 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7569 MachineFunction &MF, bool isVarArg, 7570 const SmallVectorImpl<ISD::OutputArg> &Outs, 7571 LLVMContext &Context) const { 7572 SmallVector<CCValAssign, 16> RVLocs; 7573 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7574 return CCInfo.CheckReturn( 7575 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7576 ? RetCC_PPC_Cold 7577 : RetCC_PPC); 7578 } 7579 7580 SDValue 7581 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7582 bool isVarArg, 7583 const SmallVectorImpl<ISD::OutputArg> &Outs, 7584 const SmallVectorImpl<SDValue> &OutVals, 7585 const SDLoc &dl, SelectionDAG &DAG) const { 7586 SmallVector<CCValAssign, 16> RVLocs; 7587 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7588 *DAG.getContext()); 7589 CCInfo.AnalyzeReturn(Outs, 7590 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7591 ? RetCC_PPC_Cold 7592 : RetCC_PPC); 7593 7594 SDValue Flag; 7595 SmallVector<SDValue, 4> RetOps(1, Chain); 7596 7597 // Copy the result values into the output registers. 7598 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7599 CCValAssign &VA = RVLocs[i]; 7600 assert(VA.isRegLoc() && "Can only return in registers!"); 7601 7602 SDValue Arg = OutVals[RealResIdx]; 7603 7604 switch (VA.getLocInfo()) { 7605 default: llvm_unreachable("Unknown loc info!"); 7606 case CCValAssign::Full: break; 7607 case CCValAssign::AExt: 7608 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7609 break; 7610 case CCValAssign::ZExt: 7611 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7612 break; 7613 case CCValAssign::SExt: 7614 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7615 break; 7616 } 7617 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7618 bool isLittleEndian = Subtarget.isLittleEndian(); 7619 // Legalize ret f64 -> ret 2 x i32. 7620 SDValue SVal = 7621 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7622 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7623 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7624 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7625 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7626 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7627 Flag = Chain.getValue(1); 7628 VA = RVLocs[++i]; // skip ahead to next loc 7629 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7630 } else 7631 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7632 Flag = Chain.getValue(1); 7633 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7634 } 7635 7636 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7637 const MCPhysReg *I = 7638 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7639 if (I) { 7640 for (; *I; ++I) { 7641 7642 if (PPC::G8RCRegClass.contains(*I)) 7643 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7644 else if (PPC::F8RCRegClass.contains(*I)) 7645 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7646 else if (PPC::CRRCRegClass.contains(*I)) 7647 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7648 else if (PPC::VRRCRegClass.contains(*I)) 7649 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7650 else 7651 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7652 } 7653 } 7654 7655 RetOps[0] = Chain; // Update chain. 7656 7657 // Add the flag if we have it. 7658 if (Flag.getNode()) 7659 RetOps.push_back(Flag); 7660 7661 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7662 } 7663 7664 SDValue 7665 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7666 SelectionDAG &DAG) const { 7667 SDLoc dl(Op); 7668 7669 // Get the correct type for integers. 7670 EVT IntVT = Op.getValueType(); 7671 7672 // Get the inputs. 7673 SDValue Chain = Op.getOperand(0); 7674 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7675 // Build a DYNAREAOFFSET node. 7676 SDValue Ops[2] = {Chain, FPSIdx}; 7677 SDVTList VTs = DAG.getVTList(IntVT); 7678 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7679 } 7680 7681 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7682 SelectionDAG &DAG) const { 7683 // When we pop the dynamic allocation we need to restore the SP link. 7684 SDLoc dl(Op); 7685 7686 // Get the correct type for pointers. 7687 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7688 7689 // Construct the stack pointer operand. 7690 bool isPPC64 = Subtarget.isPPC64(); 7691 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7692 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7693 7694 // Get the operands for the STACKRESTORE. 7695 SDValue Chain = Op.getOperand(0); 7696 SDValue SaveSP = Op.getOperand(1); 7697 7698 // Load the old link SP. 7699 SDValue LoadLinkSP = 7700 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7701 7702 // Restore the stack pointer. 7703 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7704 7705 // Store the old link SP. 7706 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7707 } 7708 7709 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7710 MachineFunction &MF = DAG.getMachineFunction(); 7711 bool isPPC64 = Subtarget.isPPC64(); 7712 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7713 7714 // Get current frame pointer save index. The users of this index will be 7715 // primarily DYNALLOC instructions. 7716 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7717 int RASI = FI->getReturnAddrSaveIndex(); 7718 7719 // If the frame pointer save index hasn't been defined yet. 7720 if (!RASI) { 7721 // Find out what the fix offset of the frame pointer save area. 7722 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7723 // Allocate the frame index for frame pointer save area. 7724 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7725 // Save the result. 7726 FI->setReturnAddrSaveIndex(RASI); 7727 } 7728 return DAG.getFrameIndex(RASI, PtrVT); 7729 } 7730 7731 SDValue 7732 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7733 MachineFunction &MF = DAG.getMachineFunction(); 7734 bool isPPC64 = Subtarget.isPPC64(); 7735 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7736 7737 // Get current frame pointer save index. The users of this index will be 7738 // primarily DYNALLOC instructions. 7739 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7740 int FPSI = FI->getFramePointerSaveIndex(); 7741 7742 // If the frame pointer save index hasn't been defined yet. 7743 if (!FPSI) { 7744 // Find out what the fix offset of the frame pointer save area. 7745 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7746 // Allocate the frame index for frame pointer save area. 7747 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7748 // Save the result. 7749 FI->setFramePointerSaveIndex(FPSI); 7750 } 7751 return DAG.getFrameIndex(FPSI, PtrVT); 7752 } 7753 7754 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7755 SelectionDAG &DAG) const { 7756 // Get the inputs. 7757 SDValue Chain = Op.getOperand(0); 7758 SDValue Size = Op.getOperand(1); 7759 SDLoc dl(Op); 7760 7761 // Get the correct type for pointers. 7762 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7763 // Negate the size. 7764 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7765 DAG.getConstant(0, dl, PtrVT), Size); 7766 // Construct a node for the frame pointer save index. 7767 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7768 // Build a DYNALLOC node. 7769 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7770 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7771 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7772 } 7773 7774 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7775 SelectionDAG &DAG) const { 7776 MachineFunction &MF = DAG.getMachineFunction(); 7777 7778 bool isPPC64 = Subtarget.isPPC64(); 7779 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7780 7781 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7782 return DAG.getFrameIndex(FI, PtrVT); 7783 } 7784 7785 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7786 SelectionDAG &DAG) const { 7787 SDLoc DL(Op); 7788 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7789 DAG.getVTList(MVT::i32, MVT::Other), 7790 Op.getOperand(0), Op.getOperand(1)); 7791 } 7792 7793 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7794 SelectionDAG &DAG) const { 7795 SDLoc DL(Op); 7796 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7797 Op.getOperand(0), Op.getOperand(1)); 7798 } 7799 7800 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7801 if (Op.getValueType().isVector()) 7802 return LowerVectorLoad(Op, DAG); 7803 7804 assert(Op.getValueType() == MVT::i1 && 7805 "Custom lowering only for i1 loads"); 7806 7807 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7808 7809 SDLoc dl(Op); 7810 LoadSDNode *LD = cast<LoadSDNode>(Op); 7811 7812 SDValue Chain = LD->getChain(); 7813 SDValue BasePtr = LD->getBasePtr(); 7814 MachineMemOperand *MMO = LD->getMemOperand(); 7815 7816 SDValue NewLD = 7817 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7818 BasePtr, MVT::i8, MMO); 7819 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7820 7821 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7822 return DAG.getMergeValues(Ops, dl); 7823 } 7824 7825 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7826 if (Op.getOperand(1).getValueType().isVector()) 7827 return LowerVectorStore(Op, DAG); 7828 7829 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7830 "Custom lowering only for i1 stores"); 7831 7832 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7833 7834 SDLoc dl(Op); 7835 StoreSDNode *ST = cast<StoreSDNode>(Op); 7836 7837 SDValue Chain = ST->getChain(); 7838 SDValue BasePtr = ST->getBasePtr(); 7839 SDValue Value = ST->getValue(); 7840 MachineMemOperand *MMO = ST->getMemOperand(); 7841 7842 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7843 Value); 7844 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7845 } 7846 7847 // FIXME: Remove this once the ANDI glue bug is fixed: 7848 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7849 assert(Op.getValueType() == MVT::i1 && 7850 "Custom lowering only for i1 results"); 7851 7852 SDLoc DL(Op); 7853 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7854 } 7855 7856 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7857 SelectionDAG &DAG) const { 7858 7859 // Implements a vector truncate that fits in a vector register as a shuffle. 7860 // We want to legalize vector truncates down to where the source fits in 7861 // a vector register (and target is therefore smaller than vector register 7862 // size). At that point legalization will try to custom lower the sub-legal 7863 // result and get here - where we can contain the truncate as a single target 7864 // operation. 7865 7866 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7867 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7868 // 7869 // We will implement it for big-endian ordering as this (where x denotes 7870 // undefined): 7871 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7872 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7873 // 7874 // The same operation in little-endian ordering will be: 7875 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7876 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7877 7878 assert(Op.getValueType().isVector() && "Vector type expected."); 7879 7880 SDLoc DL(Op); 7881 SDValue N1 = Op.getOperand(0); 7882 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7883 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7884 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7885 7886 EVT TrgVT = Op.getValueType(); 7887 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7888 EVT EltVT = TrgVT.getVectorElementType(); 7889 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7890 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7891 7892 // First list the elements we want to keep. 7893 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7894 SmallVector<int, 16> ShuffV; 7895 if (Subtarget.isLittleEndian()) 7896 for (unsigned i = 0; i < TrgNumElts; ++i) 7897 ShuffV.push_back(i * SizeMult); 7898 else 7899 for (unsigned i = 1; i <= TrgNumElts; ++i) 7900 ShuffV.push_back(i * SizeMult - 1); 7901 7902 // Populate the remaining elements with undefs. 7903 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7904 // ShuffV.push_back(i + WideNumElts); 7905 ShuffV.push_back(WideNumElts + 1); 7906 7907 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7908 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7909 } 7910 7911 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7912 /// possible. 7913 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7914 // Not FP? Not a fsel. 7915 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7916 !Op.getOperand(2).getValueType().isFloatingPoint()) 7917 return Op; 7918 7919 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7920 7921 EVT ResVT = Op.getValueType(); 7922 EVT CmpVT = Op.getOperand(0).getValueType(); 7923 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7924 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7925 SDLoc dl(Op); 7926 7927 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7928 // presence of infinities. 7929 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7930 switch (CC) { 7931 default: 7932 break; 7933 case ISD::SETOGT: 7934 case ISD::SETGT: 7935 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7936 case ISD::SETOLT: 7937 case ISD::SETLT: 7938 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7939 } 7940 } 7941 7942 // We might be able to do better than this under some circumstances, but in 7943 // general, fsel-based lowering of select is a finite-math-only optimization. 7944 // For more information, see section F.3 of the 2.06 ISA specification. 7945 // With ISA 3.0 7946 if (!DAG.getTarget().Options.NoInfsFPMath || 7947 !DAG.getTarget().Options.NoNaNsFPMath) 7948 return Op; 7949 7950 // TODO: Propagate flags from the select rather than global settings. 7951 SDNodeFlags Flags; 7952 Flags.setNoInfs(true); 7953 Flags.setNoNaNs(true); 7954 7955 // If the RHS of the comparison is a 0.0, we don't need to do the 7956 // subtraction at all. 7957 SDValue Sel1; 7958 if (isFloatingPointZero(RHS)) 7959 switch (CC) { 7960 default: break; // SETUO etc aren't handled by fsel. 7961 case ISD::SETNE: 7962 std::swap(TV, FV); 7963 LLVM_FALLTHROUGH; 7964 case ISD::SETEQ: 7965 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7966 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7967 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7968 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7969 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7970 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7971 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7972 case ISD::SETULT: 7973 case ISD::SETLT: 7974 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7975 LLVM_FALLTHROUGH; 7976 case ISD::SETOGE: 7977 case ISD::SETGE: 7978 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7979 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7980 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7981 case ISD::SETUGT: 7982 case ISD::SETGT: 7983 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7984 LLVM_FALLTHROUGH; 7985 case ISD::SETOLE: 7986 case ISD::SETLE: 7987 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7988 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7989 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7990 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7991 } 7992 7993 SDValue Cmp; 7994 switch (CC) { 7995 default: break; // SETUO etc aren't handled by fsel. 7996 case ISD::SETNE: 7997 std::swap(TV, FV); 7998 LLVM_FALLTHROUGH; 7999 case ISD::SETEQ: 8000 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8001 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8002 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8003 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8004 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8005 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8006 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8007 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8008 case ISD::SETULT: 8009 case ISD::SETLT: 8010 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8011 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8012 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8013 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8014 case ISD::SETOGE: 8015 case ISD::SETGE: 8016 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8017 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8018 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8019 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8020 case ISD::SETUGT: 8021 case ISD::SETGT: 8022 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8023 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8024 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8025 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8026 case ISD::SETOLE: 8027 case ISD::SETLE: 8028 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8029 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8030 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8031 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8032 } 8033 return Op; 8034 } 8035 8036 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8037 SelectionDAG &DAG, 8038 const SDLoc &dl) const { 8039 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8040 SDValue Src = Op.getOperand(0); 8041 if (Src.getValueType() == MVT::f32) 8042 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8043 8044 SDValue Tmp; 8045 switch (Op.getSimpleValueType().SimpleTy) { 8046 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8047 case MVT::i32: 8048 Tmp = DAG.getNode( 8049 Op.getOpcode() == ISD::FP_TO_SINT 8050 ? PPCISD::FCTIWZ 8051 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8052 dl, MVT::f64, Src); 8053 break; 8054 case MVT::i64: 8055 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8056 "i64 FP_TO_UINT is supported only with FPCVT"); 8057 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8058 PPCISD::FCTIDUZ, 8059 dl, MVT::f64, Src); 8060 break; 8061 } 8062 8063 // Convert the FP value to an int value through memory. 8064 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8065 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8066 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8067 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8068 MachinePointerInfo MPI = 8069 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8070 8071 // Emit a store to the stack slot. 8072 SDValue Chain; 8073 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8074 if (i32Stack) { 8075 MachineFunction &MF = DAG.getMachineFunction(); 8076 Alignment = Align(4); 8077 MachineMemOperand *MMO = 8078 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8079 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8080 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8081 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8082 } else 8083 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8084 8085 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8086 // add in a bias on big endian. 8087 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8088 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8089 DAG.getConstant(4, dl, FIPtr.getValueType())); 8090 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8091 } 8092 8093 RLI.Chain = Chain; 8094 RLI.Ptr = FIPtr; 8095 RLI.MPI = MPI; 8096 RLI.Alignment = Alignment; 8097 } 8098 8099 /// Custom lowers floating point to integer conversions to use 8100 /// the direct move instructions available in ISA 2.07 to avoid the 8101 /// need for load/store combinations. 8102 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8103 SelectionDAG &DAG, 8104 const SDLoc &dl) const { 8105 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8106 SDValue Src = Op.getOperand(0); 8107 8108 if (Src.getValueType() == MVT::f32) 8109 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8110 8111 SDValue Tmp; 8112 switch (Op.getSimpleValueType().SimpleTy) { 8113 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8114 case MVT::i32: 8115 Tmp = DAG.getNode( 8116 Op.getOpcode() == ISD::FP_TO_SINT 8117 ? PPCISD::FCTIWZ 8118 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8119 dl, MVT::f64, Src); 8120 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8121 break; 8122 case MVT::i64: 8123 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8124 "i64 FP_TO_UINT is supported only with FPCVT"); 8125 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8126 PPCISD::FCTIDUZ, 8127 dl, MVT::f64, Src); 8128 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8129 break; 8130 } 8131 return Tmp; 8132 } 8133 8134 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8135 const SDLoc &dl) const { 8136 8137 // FP to INT conversions are legal for f128. 8138 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8139 return Op; 8140 8141 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8142 // PPC (the libcall is not available). 8143 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8144 if (Op.getValueType() == MVT::i32) { 8145 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8146 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8147 MVT::f64, Op.getOperand(0), 8148 DAG.getIntPtrConstant(0, dl)); 8149 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8150 MVT::f64, Op.getOperand(0), 8151 DAG.getIntPtrConstant(1, dl)); 8152 8153 // Add the two halves of the long double in round-to-zero mode. 8154 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8155 8156 // Now use a smaller FP_TO_SINT. 8157 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8158 } 8159 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8160 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8161 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8162 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8163 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8164 // FIXME: generated code sucks. 8165 // TODO: Are there fast-math-flags to propagate to this FSUB? 8166 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8167 Op.getOperand(0), Tmp); 8168 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8169 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8170 DAG.getConstant(0x80000000, dl, MVT::i32)); 8171 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8172 Op.getOperand(0)); 8173 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8174 ISD::SETGE); 8175 } 8176 } 8177 8178 return SDValue(); 8179 } 8180 8181 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8182 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8183 8184 ReuseLoadInfo RLI; 8185 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8186 8187 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8188 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8189 } 8190 8191 // We're trying to insert a regular store, S, and then a load, L. If the 8192 // incoming value, O, is a load, we might just be able to have our load use the 8193 // address used by O. However, we don't know if anything else will store to 8194 // that address before we can load from it. To prevent this situation, we need 8195 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8196 // the same chain operand as O, we create a token factor from the chain results 8197 // of O and L, and we replace all uses of O's chain result with that token 8198 // factor (see spliceIntoChain below for this last part). 8199 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8200 ReuseLoadInfo &RLI, 8201 SelectionDAG &DAG, 8202 ISD::LoadExtType ET) const { 8203 SDLoc dl(Op); 8204 if (ET == ISD::NON_EXTLOAD && 8205 (Op.getOpcode() == ISD::FP_TO_UINT || 8206 Op.getOpcode() == ISD::FP_TO_SINT) && 8207 isOperationLegalOrCustom(Op.getOpcode(), 8208 Op.getOperand(0).getValueType())) { 8209 8210 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8211 return true; 8212 } 8213 8214 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8215 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8216 LD->isNonTemporal()) 8217 return false; 8218 if (LD->getMemoryVT() != MemVT) 8219 return false; 8220 8221 RLI.Ptr = LD->getBasePtr(); 8222 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8223 assert(LD->getAddressingMode() == ISD::PRE_INC && 8224 "Non-pre-inc AM on PPC?"); 8225 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8226 LD->getOffset()); 8227 } 8228 8229 RLI.Chain = LD->getChain(); 8230 RLI.MPI = LD->getPointerInfo(); 8231 RLI.IsDereferenceable = LD->isDereferenceable(); 8232 RLI.IsInvariant = LD->isInvariant(); 8233 RLI.Alignment = LD->getAlign(); 8234 RLI.AAInfo = LD->getAAInfo(); 8235 RLI.Ranges = LD->getRanges(); 8236 8237 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8238 return true; 8239 } 8240 8241 // Given the head of the old chain, ResChain, insert a token factor containing 8242 // it and NewResChain, and make users of ResChain now be users of that token 8243 // factor. 8244 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8245 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8246 SDValue NewResChain, 8247 SelectionDAG &DAG) const { 8248 if (!ResChain) 8249 return; 8250 8251 SDLoc dl(NewResChain); 8252 8253 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8254 NewResChain, DAG.getUNDEF(MVT::Other)); 8255 assert(TF.getNode() != NewResChain.getNode() && 8256 "A new TF really is required here"); 8257 8258 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8259 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8260 } 8261 8262 /// Analyze profitability of direct move 8263 /// prefer float load to int load plus direct move 8264 /// when there is no integer use of int load 8265 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8266 SDNode *Origin = Op.getOperand(0).getNode(); 8267 if (Origin->getOpcode() != ISD::LOAD) 8268 return true; 8269 8270 // If there is no LXSIBZX/LXSIHZX, like Power8, 8271 // prefer direct move if the memory size is 1 or 2 bytes. 8272 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8273 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8274 return true; 8275 8276 for (SDNode::use_iterator UI = Origin->use_begin(), 8277 UE = Origin->use_end(); 8278 UI != UE; ++UI) { 8279 8280 // Only look at the users of the loaded value. 8281 if (UI.getUse().get().getResNo() != 0) 8282 continue; 8283 8284 if (UI->getOpcode() != ISD::SINT_TO_FP && 8285 UI->getOpcode() != ISD::UINT_TO_FP) 8286 return true; 8287 } 8288 8289 return false; 8290 } 8291 8292 /// Custom lowers integer to floating point conversions to use 8293 /// the direct move instructions available in ISA 2.07 to avoid the 8294 /// need for load/store combinations. 8295 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8296 SelectionDAG &DAG, 8297 const SDLoc &dl) const { 8298 assert((Op.getValueType() == MVT::f32 || 8299 Op.getValueType() == MVT::f64) && 8300 "Invalid floating point type as target of conversion"); 8301 assert(Subtarget.hasFPCVT() && 8302 "Int to FP conversions with direct moves require FPCVT"); 8303 SDValue FP; 8304 SDValue Src = Op.getOperand(0); 8305 bool SinglePrec = Op.getValueType() == MVT::f32; 8306 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8307 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8308 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8309 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8310 8311 if (WordInt) { 8312 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8313 dl, MVT::f64, Src); 8314 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8315 } 8316 else { 8317 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8318 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8319 } 8320 8321 return FP; 8322 } 8323 8324 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8325 8326 EVT VecVT = Vec.getValueType(); 8327 assert(VecVT.isVector() && "Expected a vector type."); 8328 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8329 8330 EVT EltVT = VecVT.getVectorElementType(); 8331 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8332 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8333 8334 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8335 SmallVector<SDValue, 16> Ops(NumConcat); 8336 Ops[0] = Vec; 8337 SDValue UndefVec = DAG.getUNDEF(VecVT); 8338 for (unsigned i = 1; i < NumConcat; ++i) 8339 Ops[i] = UndefVec; 8340 8341 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8342 } 8343 8344 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8345 const SDLoc &dl) const { 8346 8347 unsigned Opc = Op.getOpcode(); 8348 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8349 "Unexpected conversion type"); 8350 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8351 "Supports conversions to v2f64/v4f32 only."); 8352 8353 bool SignedConv = Opc == ISD::SINT_TO_FP; 8354 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8355 8356 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8357 EVT WideVT = Wide.getValueType(); 8358 unsigned WideNumElts = WideVT.getVectorNumElements(); 8359 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8360 8361 SmallVector<int, 16> ShuffV; 8362 for (unsigned i = 0; i < WideNumElts; ++i) 8363 ShuffV.push_back(i + WideNumElts); 8364 8365 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8366 int SaveElts = FourEltRes ? 4 : 2; 8367 if (Subtarget.isLittleEndian()) 8368 for (int i = 0; i < SaveElts; i++) 8369 ShuffV[i * Stride] = i; 8370 else 8371 for (int i = 1; i <= SaveElts; i++) 8372 ShuffV[i * Stride - 1] = i - 1; 8373 8374 SDValue ShuffleSrc2 = 8375 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8376 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8377 8378 SDValue Extend; 8379 if (SignedConv) { 8380 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8381 EVT ExtVT = Op.getOperand(0).getValueType(); 8382 if (Subtarget.hasP9Altivec()) 8383 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8384 IntermediateVT.getVectorNumElements()); 8385 8386 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8387 DAG.getValueType(ExtVT)); 8388 } else 8389 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8390 8391 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8392 } 8393 8394 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8395 SelectionDAG &DAG) const { 8396 SDLoc dl(Op); 8397 8398 EVT InVT = Op.getOperand(0).getValueType(); 8399 EVT OutVT = Op.getValueType(); 8400 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8401 isOperationCustom(Op.getOpcode(), InVT)) 8402 return LowerINT_TO_FPVector(Op, DAG, dl); 8403 8404 // Conversions to f128 are legal. 8405 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8406 return Op; 8407 8408 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8409 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8410 return SDValue(); 8411 8412 SDValue Value = Op.getOperand(0); 8413 // The values are now known to be -1 (false) or 1 (true). To convert this 8414 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8415 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8416 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8417 8418 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8419 8420 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8421 8422 if (Op.getValueType() != MVT::v4f64) 8423 Value = DAG.getNode(ISD::FP_ROUND, dl, 8424 Op.getValueType(), Value, 8425 DAG.getIntPtrConstant(1, dl)); 8426 return Value; 8427 } 8428 8429 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8430 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8431 return SDValue(); 8432 8433 if (Op.getOperand(0).getValueType() == MVT::i1) 8434 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8435 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8436 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8437 8438 // If we have direct moves, we can do all the conversion, skip the store/load 8439 // however, without FPCVT we can't do most conversions. 8440 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8441 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8442 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8443 8444 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8445 "UINT_TO_FP is supported only with FPCVT"); 8446 8447 // If we have FCFIDS, then use it when converting to single-precision. 8448 // Otherwise, convert to double-precision and then round. 8449 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8450 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8451 : PPCISD::FCFIDS) 8452 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8453 : PPCISD::FCFID); 8454 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8455 ? MVT::f32 8456 : MVT::f64; 8457 8458 if (Op.getOperand(0).getValueType() == MVT::i64) { 8459 SDValue SINT = Op.getOperand(0); 8460 // When converting to single-precision, we actually need to convert 8461 // to double-precision first and then round to single-precision. 8462 // To avoid double-rounding effects during that operation, we have 8463 // to prepare the input operand. Bits that might be truncated when 8464 // converting to double-precision are replaced by a bit that won't 8465 // be lost at this stage, but is below the single-precision rounding 8466 // position. 8467 // 8468 // However, if -enable-unsafe-fp-math is in effect, accept double 8469 // rounding to avoid the extra overhead. 8470 if (Op.getValueType() == MVT::f32 && 8471 !Subtarget.hasFPCVT() && 8472 !DAG.getTarget().Options.UnsafeFPMath) { 8473 8474 // Twiddle input to make sure the low 11 bits are zero. (If this 8475 // is the case, we are guaranteed the value will fit into the 53 bit 8476 // mantissa of an IEEE double-precision value without rounding.) 8477 // If any of those low 11 bits were not zero originally, make sure 8478 // bit 12 (value 2048) is set instead, so that the final rounding 8479 // to single-precision gets the correct result. 8480 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8481 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8482 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8483 Round, DAG.getConstant(2047, dl, MVT::i64)); 8484 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8485 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8486 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8487 8488 // However, we cannot use that value unconditionally: if the magnitude 8489 // of the input value is small, the bit-twiddling we did above might 8490 // end up visibly changing the output. Fortunately, in that case, we 8491 // don't need to twiddle bits since the original input will convert 8492 // exactly to double-precision floating-point already. Therefore, 8493 // construct a conditional to use the original value if the top 11 8494 // bits are all sign-bit copies, and use the rounded value computed 8495 // above otherwise. 8496 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8497 SINT, DAG.getConstant(53, dl, MVT::i32)); 8498 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8499 Cond, DAG.getConstant(1, dl, MVT::i64)); 8500 Cond = DAG.getSetCC( 8501 dl, 8502 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8503 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8504 8505 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8506 } 8507 8508 ReuseLoadInfo RLI; 8509 SDValue Bits; 8510 8511 MachineFunction &MF = DAG.getMachineFunction(); 8512 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8513 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8514 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8515 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8516 } else if (Subtarget.hasLFIWAX() && 8517 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8518 MachineMemOperand *MMO = 8519 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8520 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8521 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8522 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8523 DAG.getVTList(MVT::f64, MVT::Other), 8524 Ops, MVT::i32, MMO); 8525 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8526 } else if (Subtarget.hasFPCVT() && 8527 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8528 MachineMemOperand *MMO = 8529 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8530 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8531 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8532 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8533 DAG.getVTList(MVT::f64, MVT::Other), 8534 Ops, MVT::i32, MMO); 8535 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8536 } else if (((Subtarget.hasLFIWAX() && 8537 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8538 (Subtarget.hasFPCVT() && 8539 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8540 SINT.getOperand(0).getValueType() == MVT::i32) { 8541 MachineFrameInfo &MFI = MF.getFrameInfo(); 8542 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8543 8544 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8545 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8546 8547 SDValue Store = 8548 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8549 MachinePointerInfo::getFixedStack( 8550 DAG.getMachineFunction(), FrameIdx)); 8551 8552 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8553 "Expected an i32 store"); 8554 8555 RLI.Ptr = FIdx; 8556 RLI.Chain = Store; 8557 RLI.MPI = 8558 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8559 RLI.Alignment = Align(4); 8560 8561 MachineMemOperand *MMO = 8562 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8563 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8564 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8565 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8566 PPCISD::LFIWZX : PPCISD::LFIWAX, 8567 dl, DAG.getVTList(MVT::f64, MVT::Other), 8568 Ops, MVT::i32, MMO); 8569 } else 8570 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8571 8572 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8573 8574 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8575 FP = DAG.getNode(ISD::FP_ROUND, dl, 8576 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8577 return FP; 8578 } 8579 8580 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8581 "Unhandled INT_TO_FP type in custom expander!"); 8582 // Since we only generate this in 64-bit mode, we can take advantage of 8583 // 64-bit registers. In particular, sign extend the input value into the 8584 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8585 // then lfd it and fcfid it. 8586 MachineFunction &MF = DAG.getMachineFunction(); 8587 MachineFrameInfo &MFI = MF.getFrameInfo(); 8588 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8589 8590 SDValue Ld; 8591 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8592 ReuseLoadInfo RLI; 8593 bool ReusingLoad; 8594 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8595 DAG))) { 8596 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8597 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8598 8599 SDValue Store = 8600 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8601 MachinePointerInfo::getFixedStack( 8602 DAG.getMachineFunction(), FrameIdx)); 8603 8604 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8605 "Expected an i32 store"); 8606 8607 RLI.Ptr = FIdx; 8608 RLI.Chain = Store; 8609 RLI.MPI = 8610 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8611 RLI.Alignment = Align(4); 8612 } 8613 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 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8619 PPCISD::LFIWZX : PPCISD::LFIWAX, 8620 dl, DAG.getVTList(MVT::f64, MVT::Other), 8621 Ops, MVT::i32, MMO); 8622 if (ReusingLoad) 8623 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8624 } else { 8625 assert(Subtarget.isPPC64() && 8626 "i32->FP without LFIWAX supported only on PPC64"); 8627 8628 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8629 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8630 8631 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8632 Op.getOperand(0)); 8633 8634 // STD the extended value into the stack slot. 8635 SDValue Store = DAG.getStore( 8636 DAG.getEntryNode(), dl, Ext64, FIdx, 8637 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8638 8639 // Load the value as a double. 8640 Ld = DAG.getLoad( 8641 MVT::f64, dl, Store, FIdx, 8642 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8643 } 8644 8645 // FCFID it and return it. 8646 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8647 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8648 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8649 DAG.getIntPtrConstant(0, dl)); 8650 return FP; 8651 } 8652 8653 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8654 SelectionDAG &DAG) const { 8655 SDLoc dl(Op); 8656 /* 8657 The rounding mode is in bits 30:31 of FPSR, and has the following 8658 settings: 8659 00 Round to nearest 8660 01 Round to 0 8661 10 Round to +inf 8662 11 Round to -inf 8663 8664 FLT_ROUNDS, on the other hand, expects the following: 8665 -1 Undefined 8666 0 Round to 0 8667 1 Round to nearest 8668 2 Round to +inf 8669 3 Round to -inf 8670 8671 To perform the conversion, we do: 8672 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8673 */ 8674 8675 MachineFunction &MF = DAG.getMachineFunction(); 8676 EVT VT = Op.getValueType(); 8677 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8678 8679 // Save FP Control Word to register 8680 SDValue Chain = Op.getOperand(0); 8681 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8682 Chain = MFFS.getValue(1); 8683 8684 // Save FP register to stack slot 8685 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8686 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8687 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8688 8689 // Load FP Control Word from low 32 bits of stack slot. 8690 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8691 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8692 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8693 Chain = CWD.getValue(1); 8694 8695 // Transform as necessary 8696 SDValue CWD1 = 8697 DAG.getNode(ISD::AND, dl, MVT::i32, 8698 CWD, DAG.getConstant(3, dl, MVT::i32)); 8699 SDValue CWD2 = 8700 DAG.getNode(ISD::SRL, dl, MVT::i32, 8701 DAG.getNode(ISD::AND, dl, MVT::i32, 8702 DAG.getNode(ISD::XOR, dl, MVT::i32, 8703 CWD, DAG.getConstant(3, dl, MVT::i32)), 8704 DAG.getConstant(3, dl, MVT::i32)), 8705 DAG.getConstant(1, dl, MVT::i32)); 8706 8707 SDValue RetVal = 8708 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8709 8710 RetVal = 8711 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8712 dl, VT, RetVal); 8713 8714 return DAG.getMergeValues({RetVal, Chain}, dl); 8715 } 8716 8717 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8718 EVT VT = Op.getValueType(); 8719 unsigned BitWidth = VT.getSizeInBits(); 8720 SDLoc dl(Op); 8721 assert(Op.getNumOperands() == 3 && 8722 VT == Op.getOperand(1).getValueType() && 8723 "Unexpected SHL!"); 8724 8725 // Expand into a bunch of logical ops. Note that these ops 8726 // depend on the PPC behavior for oversized shift amounts. 8727 SDValue Lo = Op.getOperand(0); 8728 SDValue Hi = Op.getOperand(1); 8729 SDValue Amt = Op.getOperand(2); 8730 EVT AmtVT = Amt.getValueType(); 8731 8732 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8733 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8734 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8735 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8736 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8737 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8738 DAG.getConstant(-BitWidth, dl, AmtVT)); 8739 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8740 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8741 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8742 SDValue OutOps[] = { OutLo, OutHi }; 8743 return DAG.getMergeValues(OutOps, dl); 8744 } 8745 8746 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8747 EVT VT = Op.getValueType(); 8748 SDLoc dl(Op); 8749 unsigned BitWidth = VT.getSizeInBits(); 8750 assert(Op.getNumOperands() == 3 && 8751 VT == Op.getOperand(1).getValueType() && 8752 "Unexpected SRL!"); 8753 8754 // Expand into a bunch of logical ops. Note that these ops 8755 // depend on the PPC behavior for oversized shift amounts. 8756 SDValue Lo = Op.getOperand(0); 8757 SDValue Hi = Op.getOperand(1); 8758 SDValue Amt = Op.getOperand(2); 8759 EVT AmtVT = Amt.getValueType(); 8760 8761 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8762 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8763 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8764 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8765 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8766 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8767 DAG.getConstant(-BitWidth, dl, AmtVT)); 8768 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8769 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8770 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8771 SDValue OutOps[] = { OutLo, OutHi }; 8772 return DAG.getMergeValues(OutOps, dl); 8773 } 8774 8775 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8776 SDLoc dl(Op); 8777 EVT VT = Op.getValueType(); 8778 unsigned BitWidth = VT.getSizeInBits(); 8779 assert(Op.getNumOperands() == 3 && 8780 VT == Op.getOperand(1).getValueType() && 8781 "Unexpected SRA!"); 8782 8783 // Expand into a bunch of logical ops, followed by a select_cc. 8784 SDValue Lo = Op.getOperand(0); 8785 SDValue Hi = Op.getOperand(1); 8786 SDValue Amt = Op.getOperand(2); 8787 EVT AmtVT = Amt.getValueType(); 8788 8789 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8790 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8791 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8792 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8793 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8794 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8795 DAG.getConstant(-BitWidth, dl, AmtVT)); 8796 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8797 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8798 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8799 Tmp4, Tmp6, ISD::SETLE); 8800 SDValue OutOps[] = { OutLo, OutHi }; 8801 return DAG.getMergeValues(OutOps, dl); 8802 } 8803 8804 //===----------------------------------------------------------------------===// 8805 // Vector related lowering. 8806 // 8807 8808 /// BuildSplatI - Build a canonical splati of Val with an element size of 8809 /// SplatSize. Cast the result to VT. 8810 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8811 SelectionDAG &DAG, const SDLoc &dl) { 8812 static const MVT VTys[] = { // canonical VT to use for each size. 8813 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8814 }; 8815 8816 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8817 8818 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8819 if (Val == -1) 8820 SplatSize = 1; 8821 8822 EVT CanonicalVT = VTys[SplatSize-1]; 8823 8824 // Build a canonical splat for this value. 8825 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8826 } 8827 8828 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8829 /// specified intrinsic ID. 8830 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8831 const SDLoc &dl, EVT DestVT = MVT::Other) { 8832 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8833 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8834 DAG.getConstant(IID, dl, MVT::i32), Op); 8835 } 8836 8837 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8838 /// specified intrinsic ID. 8839 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8840 SelectionDAG &DAG, const SDLoc &dl, 8841 EVT DestVT = MVT::Other) { 8842 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8843 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8844 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8845 } 8846 8847 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8848 /// specified intrinsic ID. 8849 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8850 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8851 EVT DestVT = MVT::Other) { 8852 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8853 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8854 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8855 } 8856 8857 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8858 /// amount. The result has the specified value type. 8859 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8860 SelectionDAG &DAG, const SDLoc &dl) { 8861 // Force LHS/RHS to be the right type. 8862 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8863 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8864 8865 int Ops[16]; 8866 for (unsigned i = 0; i != 16; ++i) 8867 Ops[i] = i + Amt; 8868 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8869 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8870 } 8871 8872 /// Do we have an efficient pattern in a .td file for this node? 8873 /// 8874 /// \param V - pointer to the BuildVectorSDNode being matched 8875 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8876 /// 8877 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8878 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8879 /// the opposite is true (expansion is beneficial) are: 8880 /// - The node builds a vector out of integers that are not 32 or 64-bits 8881 /// - The node builds a vector out of constants 8882 /// - The node is a "load-and-splat" 8883 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8884 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8885 bool HasDirectMove, 8886 bool HasP8Vector) { 8887 EVT VecVT = V->getValueType(0); 8888 bool RightType = VecVT == MVT::v2f64 || 8889 (HasP8Vector && VecVT == MVT::v4f32) || 8890 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8891 if (!RightType) 8892 return false; 8893 8894 bool IsSplat = true; 8895 bool IsLoad = false; 8896 SDValue Op0 = V->getOperand(0); 8897 8898 // This function is called in a block that confirms the node is not a constant 8899 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8900 // different constants. 8901 if (V->isConstant()) 8902 return false; 8903 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8904 if (V->getOperand(i).isUndef()) 8905 return false; 8906 // We want to expand nodes that represent load-and-splat even if the 8907 // loaded value is a floating point truncation or conversion to int. 8908 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8909 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8910 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8911 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8912 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8913 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8914 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8915 IsLoad = true; 8916 // If the operands are different or the input is not a load and has more 8917 // uses than just this BV node, then it isn't a splat. 8918 if (V->getOperand(i) != Op0 || 8919 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8920 IsSplat = false; 8921 } 8922 return !(IsSplat && IsLoad); 8923 } 8924 8925 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8926 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8927 8928 SDLoc dl(Op); 8929 SDValue Op0 = Op->getOperand(0); 8930 8931 if (!EnableQuadPrecision || 8932 (Op.getValueType() != MVT::f128 ) || 8933 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8934 (Op0.getOperand(0).getValueType() != MVT::i64) || 8935 (Op0.getOperand(1).getValueType() != MVT::i64)) 8936 return SDValue(); 8937 8938 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8939 Op0.getOperand(1)); 8940 } 8941 8942 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8943 const SDValue *InputLoad = &Op; 8944 if (InputLoad->getOpcode() == ISD::BITCAST) 8945 InputLoad = &InputLoad->getOperand(0); 8946 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8947 InputLoad = &InputLoad->getOperand(0); 8948 if (InputLoad->getOpcode() != ISD::LOAD) 8949 return nullptr; 8950 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8951 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8952 } 8953 8954 // If this is a case we can't handle, return null and let the default 8955 // expansion code take care of it. If we CAN select this case, and if it 8956 // selects to a single instruction, return Op. Otherwise, if we can codegen 8957 // this case more efficiently than a constant pool load, lower it to the 8958 // sequence of ops that should be used. 8959 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8960 SelectionDAG &DAG) const { 8961 SDLoc dl(Op); 8962 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8963 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8964 8965 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8966 // We first build an i32 vector, load it into a QPX register, 8967 // then convert it to a floating-point vector and compare it 8968 // to a zero vector to get the boolean result. 8969 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8970 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8971 MachinePointerInfo PtrInfo = 8972 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8973 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8974 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8975 8976 assert(BVN->getNumOperands() == 4 && 8977 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8978 8979 bool IsConst = true; 8980 for (unsigned i = 0; i < 4; ++i) { 8981 if (BVN->getOperand(i).isUndef()) continue; 8982 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8983 IsConst = false; 8984 break; 8985 } 8986 } 8987 8988 if (IsConst) { 8989 Constant *One = 8990 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8991 Constant *NegOne = 8992 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8993 8994 Constant *CV[4]; 8995 for (unsigned i = 0; i < 4; ++i) { 8996 if (BVN->getOperand(i).isUndef()) 8997 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8998 else if (isNullConstant(BVN->getOperand(i))) 8999 CV[i] = NegOne; 9000 else 9001 CV[i] = One; 9002 } 9003 9004 Constant *CP = ConstantVector::get(CV); 9005 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 9006 16 /* alignment */); 9007 9008 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9009 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9010 return DAG.getMemIntrinsicNode( 9011 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9012 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9013 } 9014 9015 SmallVector<SDValue, 4> Stores; 9016 for (unsigned i = 0; i < 4; ++i) { 9017 if (BVN->getOperand(i).isUndef()) continue; 9018 9019 unsigned Offset = 4*i; 9020 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9021 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9022 9023 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9024 if (StoreSize > 4) { 9025 Stores.push_back( 9026 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9027 PtrInfo.getWithOffset(Offset), MVT::i32)); 9028 } else { 9029 SDValue StoreValue = BVN->getOperand(i); 9030 if (StoreSize < 4) 9031 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9032 9033 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9034 PtrInfo.getWithOffset(Offset))); 9035 } 9036 } 9037 9038 SDValue StoreChain; 9039 if (!Stores.empty()) 9040 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9041 else 9042 StoreChain = DAG.getEntryNode(); 9043 9044 // Now load from v4i32 into the QPX register; this will extend it to 9045 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9046 // is typed as v4f64 because the QPX register integer states are not 9047 // explicitly represented. 9048 9049 SDValue Ops[] = {StoreChain, 9050 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9051 FIdx}; 9052 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9053 9054 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9055 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9056 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9057 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9058 LoadedVect); 9059 9060 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9061 9062 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9063 } 9064 9065 // All other QPX vectors are handled by generic code. 9066 if (Subtarget.hasQPX()) 9067 return SDValue(); 9068 9069 // Check if this is a splat of a constant value. 9070 APInt APSplatBits, APSplatUndef; 9071 unsigned SplatBitSize; 9072 bool HasAnyUndefs; 9073 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9074 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9075 SplatBitSize > 32) { 9076 9077 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9078 // Handle load-and-splat patterns as we have instructions that will do this 9079 // in one go. 9080 if (InputLoad && DAG.isSplatValue(Op, true)) { 9081 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9082 9083 // We have handling for 4 and 8 byte elements. 9084 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9085 9086 // Checking for a single use of this load, we have to check for vector 9087 // width (128 bits) / ElementSize uses (since each operand of the 9088 // BUILD_VECTOR is a separate use of the value. 9089 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9090 ((Subtarget.hasVSX() && ElementSize == 64) || 9091 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9092 SDValue Ops[] = { 9093 LD->getChain(), // Chain 9094 LD->getBasePtr(), // Ptr 9095 DAG.getValueType(Op.getValueType()) // VT 9096 }; 9097 return 9098 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9099 DAG.getVTList(Op.getValueType(), MVT::Other), 9100 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9101 } 9102 } 9103 9104 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9105 // lowered to VSX instructions under certain conditions. 9106 // Without VSX, there is no pattern more efficient than expanding the node. 9107 if (Subtarget.hasVSX() && 9108 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9109 Subtarget.hasP8Vector())) 9110 return Op; 9111 return SDValue(); 9112 } 9113 9114 unsigned SplatBits = APSplatBits.getZExtValue(); 9115 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9116 unsigned SplatSize = SplatBitSize / 8; 9117 9118 // First, handle single instruction cases. 9119 9120 // All zeros? 9121 if (SplatBits == 0) { 9122 // Canonicalize all zero vectors to be v4i32. 9123 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9124 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9125 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9126 } 9127 return Op; 9128 } 9129 9130 // We have XXSPLTIB for constant splats one byte wide 9131 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9132 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9133 if (Subtarget.hasP9Vector() && SplatSize == 1) 9134 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9135 9136 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9137 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9138 (32-SplatBitSize)); 9139 if (SextVal >= -16 && SextVal <= 15) 9140 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9141 9142 // Two instruction sequences. 9143 9144 // If this value is in the range [-32,30] and is even, use: 9145 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9146 // If this value is in the range [17,31] and is odd, use: 9147 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9148 // If this value is in the range [-31,-17] and is odd, use: 9149 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9150 // Note the last two are three-instruction sequences. 9151 if (SextVal >= -32 && SextVal <= 31) { 9152 // To avoid having these optimizations undone by constant folding, 9153 // we convert to a pseudo that will be expanded later into one of 9154 // the above forms. 9155 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9156 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9157 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9158 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9159 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9160 if (VT == Op.getValueType()) 9161 return RetVal; 9162 else 9163 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9164 } 9165 9166 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9167 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9168 // for fneg/fabs. 9169 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9170 // Make -1 and vspltisw -1: 9171 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9172 9173 // Make the VSLW intrinsic, computing 0x8000_0000. 9174 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9175 OnesV, DAG, dl); 9176 9177 // xor by OnesV to invert it. 9178 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9179 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9180 } 9181 9182 // Check to see if this is a wide variety of vsplti*, binop self cases. 9183 static const signed char SplatCsts[] = { 9184 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9185 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9186 }; 9187 9188 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9189 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9190 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9191 int i = SplatCsts[idx]; 9192 9193 // Figure out what shift amount will be used by altivec if shifted by i in 9194 // this splat size. 9195 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9196 9197 // vsplti + shl self. 9198 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9199 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9200 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9201 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9202 Intrinsic::ppc_altivec_vslw 9203 }; 9204 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9205 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9206 } 9207 9208 // vsplti + srl self. 9209 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9210 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9211 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9212 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9213 Intrinsic::ppc_altivec_vsrw 9214 }; 9215 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9216 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9217 } 9218 9219 // vsplti + sra self. 9220 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9221 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9222 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9223 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9224 Intrinsic::ppc_altivec_vsraw 9225 }; 9226 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9227 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9228 } 9229 9230 // vsplti + rol self. 9231 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9232 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9233 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9234 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9235 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9236 Intrinsic::ppc_altivec_vrlw 9237 }; 9238 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9239 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9240 } 9241 9242 // t = vsplti c, result = vsldoi t, t, 1 9243 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9244 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9245 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9246 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9247 } 9248 // t = vsplti c, result = vsldoi t, t, 2 9249 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9250 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9251 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9252 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9253 } 9254 // t = vsplti c, result = vsldoi t, t, 3 9255 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9256 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9257 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9258 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9259 } 9260 } 9261 9262 return SDValue(); 9263 } 9264 9265 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9266 /// the specified operations to build the shuffle. 9267 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9268 SDValue RHS, SelectionDAG &DAG, 9269 const SDLoc &dl) { 9270 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9271 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9272 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9273 9274 enum { 9275 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9276 OP_VMRGHW, 9277 OP_VMRGLW, 9278 OP_VSPLTISW0, 9279 OP_VSPLTISW1, 9280 OP_VSPLTISW2, 9281 OP_VSPLTISW3, 9282 OP_VSLDOI4, 9283 OP_VSLDOI8, 9284 OP_VSLDOI12 9285 }; 9286 9287 if (OpNum == OP_COPY) { 9288 if (LHSID == (1*9+2)*9+3) return LHS; 9289 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9290 return RHS; 9291 } 9292 9293 SDValue OpLHS, OpRHS; 9294 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9295 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9296 9297 int ShufIdxs[16]; 9298 switch (OpNum) { 9299 default: llvm_unreachable("Unknown i32 permute!"); 9300 case OP_VMRGHW: 9301 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9302 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9303 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9304 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9305 break; 9306 case OP_VMRGLW: 9307 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9308 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9309 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9310 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9311 break; 9312 case OP_VSPLTISW0: 9313 for (unsigned i = 0; i != 16; ++i) 9314 ShufIdxs[i] = (i&3)+0; 9315 break; 9316 case OP_VSPLTISW1: 9317 for (unsigned i = 0; i != 16; ++i) 9318 ShufIdxs[i] = (i&3)+4; 9319 break; 9320 case OP_VSPLTISW2: 9321 for (unsigned i = 0; i != 16; ++i) 9322 ShufIdxs[i] = (i&3)+8; 9323 break; 9324 case OP_VSPLTISW3: 9325 for (unsigned i = 0; i != 16; ++i) 9326 ShufIdxs[i] = (i&3)+12; 9327 break; 9328 case OP_VSLDOI4: 9329 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9330 case OP_VSLDOI8: 9331 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9332 case OP_VSLDOI12: 9333 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9334 } 9335 EVT VT = OpLHS.getValueType(); 9336 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9337 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9338 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9339 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9340 } 9341 9342 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9343 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9344 /// SDValue. 9345 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9346 SelectionDAG &DAG) const { 9347 const unsigned BytesInVector = 16; 9348 bool IsLE = Subtarget.isLittleEndian(); 9349 SDLoc dl(N); 9350 SDValue V1 = N->getOperand(0); 9351 SDValue V2 = N->getOperand(1); 9352 unsigned ShiftElts = 0, InsertAtByte = 0; 9353 bool Swap = false; 9354 9355 // Shifts required to get the byte we want at element 7. 9356 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9357 0, 15, 14, 13, 12, 11, 10, 9}; 9358 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9359 1, 2, 3, 4, 5, 6, 7, 8}; 9360 9361 ArrayRef<int> Mask = N->getMask(); 9362 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9363 9364 // For each mask element, find out if we're just inserting something 9365 // from V2 into V1 or vice versa. 9366 // Possible permutations inserting an element from V2 into V1: 9367 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9368 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9369 // ... 9370 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9371 // Inserting from V1 into V2 will be similar, except mask range will be 9372 // [16,31]. 9373 9374 bool FoundCandidate = false; 9375 // If both vector operands for the shuffle are the same vector, the mask 9376 // will contain only elements from the first one and the second one will be 9377 // undef. 9378 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9379 // Go through the mask of half-words to find an element that's being moved 9380 // from one vector to the other. 9381 for (unsigned i = 0; i < BytesInVector; ++i) { 9382 unsigned CurrentElement = Mask[i]; 9383 // If 2nd operand is undefined, we should only look for element 7 in the 9384 // Mask. 9385 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9386 continue; 9387 9388 bool OtherElementsInOrder = true; 9389 // Examine the other elements in the Mask to see if they're in original 9390 // order. 9391 for (unsigned j = 0; j < BytesInVector; ++j) { 9392 if (j == i) 9393 continue; 9394 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9395 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9396 // in which we always assume we're always picking from the 1st operand. 9397 int MaskOffset = 9398 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9399 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9400 OtherElementsInOrder = false; 9401 break; 9402 } 9403 } 9404 // If other elements are in original order, we record the number of shifts 9405 // we need to get the element we want into element 7. Also record which byte 9406 // in the vector we should insert into. 9407 if (OtherElementsInOrder) { 9408 // If 2nd operand is undefined, we assume no shifts and no swapping. 9409 if (V2.isUndef()) { 9410 ShiftElts = 0; 9411 Swap = false; 9412 } else { 9413 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9414 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9415 : BigEndianShifts[CurrentElement & 0xF]; 9416 Swap = CurrentElement < BytesInVector; 9417 } 9418 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9419 FoundCandidate = true; 9420 break; 9421 } 9422 } 9423 9424 if (!FoundCandidate) 9425 return SDValue(); 9426 9427 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9428 // optionally with VECSHL if shift is required. 9429 if (Swap) 9430 std::swap(V1, V2); 9431 if (V2.isUndef()) 9432 V2 = V1; 9433 if (ShiftElts) { 9434 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9435 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9436 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9437 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9438 } 9439 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9440 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9441 } 9442 9443 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9444 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9445 /// SDValue. 9446 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9447 SelectionDAG &DAG) const { 9448 const unsigned NumHalfWords = 8; 9449 const unsigned BytesInVector = NumHalfWords * 2; 9450 // Check that the shuffle is on half-words. 9451 if (!isNByteElemShuffleMask(N, 2, 1)) 9452 return SDValue(); 9453 9454 bool IsLE = Subtarget.isLittleEndian(); 9455 SDLoc dl(N); 9456 SDValue V1 = N->getOperand(0); 9457 SDValue V2 = N->getOperand(1); 9458 unsigned ShiftElts = 0, InsertAtByte = 0; 9459 bool Swap = false; 9460 9461 // Shifts required to get the half-word we want at element 3. 9462 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9463 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9464 9465 uint32_t Mask = 0; 9466 uint32_t OriginalOrderLow = 0x1234567; 9467 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9468 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9469 // 32-bit space, only need 4-bit nibbles per element. 9470 for (unsigned i = 0; i < NumHalfWords; ++i) { 9471 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9472 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9473 } 9474 9475 // For each mask element, find out if we're just inserting something 9476 // from V2 into V1 or vice versa. Possible permutations inserting an element 9477 // from V2 into V1: 9478 // X, 1, 2, 3, 4, 5, 6, 7 9479 // 0, X, 2, 3, 4, 5, 6, 7 9480 // 0, 1, X, 3, 4, 5, 6, 7 9481 // 0, 1, 2, X, 4, 5, 6, 7 9482 // 0, 1, 2, 3, X, 5, 6, 7 9483 // 0, 1, 2, 3, 4, X, 6, 7 9484 // 0, 1, 2, 3, 4, 5, X, 7 9485 // 0, 1, 2, 3, 4, 5, 6, X 9486 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9487 9488 bool FoundCandidate = false; 9489 // Go through the mask of half-words to find an element that's being moved 9490 // from one vector to the other. 9491 for (unsigned i = 0; i < NumHalfWords; ++i) { 9492 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9493 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9494 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9495 uint32_t TargetOrder = 0x0; 9496 9497 // If both vector operands for the shuffle are the same vector, the mask 9498 // will contain only elements from the first one and the second one will be 9499 // undef. 9500 if (V2.isUndef()) { 9501 ShiftElts = 0; 9502 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9503 TargetOrder = OriginalOrderLow; 9504 Swap = false; 9505 // Skip if not the correct element or mask of other elements don't equal 9506 // to our expected order. 9507 if (MaskOneElt == VINSERTHSrcElem && 9508 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9509 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9510 FoundCandidate = true; 9511 break; 9512 } 9513 } else { // If both operands are defined. 9514 // Target order is [8,15] if the current mask is between [0,7]. 9515 TargetOrder = 9516 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9517 // Skip if mask of other elements don't equal our expected order. 9518 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9519 // We only need the last 3 bits for the number of shifts. 9520 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9521 : BigEndianShifts[MaskOneElt & 0x7]; 9522 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9523 Swap = MaskOneElt < NumHalfWords; 9524 FoundCandidate = true; 9525 break; 9526 } 9527 } 9528 } 9529 9530 if (!FoundCandidate) 9531 return SDValue(); 9532 9533 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9534 // optionally with VECSHL if shift is required. 9535 if (Swap) 9536 std::swap(V1, V2); 9537 if (V2.isUndef()) 9538 V2 = V1; 9539 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9540 if (ShiftElts) { 9541 // Double ShiftElts because we're left shifting on v16i8 type. 9542 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9543 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9544 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9545 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9546 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9547 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9548 } 9549 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9550 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9551 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9552 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9553 } 9554 9555 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9556 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9557 /// return the code it can be lowered into. Worst case, it can always be 9558 /// lowered into a vperm. 9559 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9560 SelectionDAG &DAG) const { 9561 SDLoc dl(Op); 9562 SDValue V1 = Op.getOperand(0); 9563 SDValue V2 = Op.getOperand(1); 9564 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9565 EVT VT = Op.getValueType(); 9566 bool isLittleEndian = Subtarget.isLittleEndian(); 9567 9568 unsigned ShiftElts, InsertAtByte; 9569 bool Swap = false; 9570 9571 // If this is a load-and-splat, we can do that with a single instruction 9572 // in some cases. However if the load has multiple uses, we don't want to 9573 // combine it because that will just produce multiple loads. 9574 const SDValue *InputLoad = getNormalLoadInput(V1); 9575 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9576 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9577 InputLoad->hasOneUse()) { 9578 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9579 int SplatIdx = 9580 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9581 9582 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9583 // For 4-byte load-and-splat, we need Power9. 9584 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9585 uint64_t Offset = 0; 9586 if (IsFourByte) 9587 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9588 else 9589 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9590 SDValue BasePtr = LD->getBasePtr(); 9591 if (Offset != 0) 9592 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9593 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9594 SDValue Ops[] = { 9595 LD->getChain(), // Chain 9596 BasePtr, // BasePtr 9597 DAG.getValueType(Op.getValueType()) // VT 9598 }; 9599 SDVTList VTL = 9600 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9601 SDValue LdSplt = 9602 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9603 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9604 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9605 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9606 return LdSplt; 9607 } 9608 } 9609 if (Subtarget.hasP9Vector() && 9610 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9611 isLittleEndian)) { 9612 if (Swap) 9613 std::swap(V1, V2); 9614 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9615 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9616 if (ShiftElts) { 9617 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9618 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9619 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9620 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9621 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9622 } 9623 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9624 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9625 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9626 } 9627 9628 if (Subtarget.hasP9Altivec()) { 9629 SDValue NewISDNode; 9630 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9631 return NewISDNode; 9632 9633 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9634 return NewISDNode; 9635 } 9636 9637 if (Subtarget.hasVSX() && 9638 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9639 if (Swap) 9640 std::swap(V1, V2); 9641 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9642 SDValue Conv2 = 9643 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9644 9645 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9646 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9647 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9648 } 9649 9650 if (Subtarget.hasVSX() && 9651 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9652 if (Swap) 9653 std::swap(V1, V2); 9654 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9655 SDValue Conv2 = 9656 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9657 9658 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9659 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9660 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9661 } 9662 9663 if (Subtarget.hasP9Vector()) { 9664 if (PPC::isXXBRHShuffleMask(SVOp)) { 9665 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9666 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9667 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9668 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9669 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9670 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9671 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9672 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9673 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9674 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9675 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9676 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9677 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9678 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9679 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9680 } 9681 } 9682 9683 if (Subtarget.hasVSX()) { 9684 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9685 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9686 9687 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9688 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9689 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9690 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9691 } 9692 9693 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9694 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9695 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9696 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9697 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9698 } 9699 } 9700 9701 if (Subtarget.hasQPX()) { 9702 if (VT.getVectorNumElements() != 4) 9703 return SDValue(); 9704 9705 if (V2.isUndef()) V2 = V1; 9706 9707 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9708 if (AlignIdx != -1) { 9709 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9710 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9711 } else if (SVOp->isSplat()) { 9712 int SplatIdx = SVOp->getSplatIndex(); 9713 if (SplatIdx >= 4) { 9714 std::swap(V1, V2); 9715 SplatIdx -= 4; 9716 } 9717 9718 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9719 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9720 } 9721 9722 // Lower this into a qvgpci/qvfperm pair. 9723 9724 // Compute the qvgpci literal 9725 unsigned idx = 0; 9726 for (unsigned i = 0; i < 4; ++i) { 9727 int m = SVOp->getMaskElt(i); 9728 unsigned mm = m >= 0 ? (unsigned) m : i; 9729 idx |= mm << (3-i)*3; 9730 } 9731 9732 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9733 DAG.getConstant(idx, dl, MVT::i32)); 9734 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9735 } 9736 9737 // Cases that are handled by instructions that take permute immediates 9738 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9739 // selected by the instruction selector. 9740 if (V2.isUndef()) { 9741 if (PPC::isSplatShuffleMask(SVOp, 1) || 9742 PPC::isSplatShuffleMask(SVOp, 2) || 9743 PPC::isSplatShuffleMask(SVOp, 4) || 9744 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9745 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9746 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9747 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9748 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9749 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9750 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9751 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9752 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9753 (Subtarget.hasP8Altivec() && ( 9754 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9755 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9756 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9757 return Op; 9758 } 9759 } 9760 9761 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9762 // and produce a fixed permutation. If any of these match, do not lower to 9763 // VPERM. 9764 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9765 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9766 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9767 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9768 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9769 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9770 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9771 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9772 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9773 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9774 (Subtarget.hasP8Altivec() && ( 9775 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9776 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9777 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9778 return Op; 9779 9780 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9781 // perfect shuffle table to emit an optimal matching sequence. 9782 ArrayRef<int> PermMask = SVOp->getMask(); 9783 9784 unsigned PFIndexes[4]; 9785 bool isFourElementShuffle = true; 9786 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9787 unsigned EltNo = 8; // Start out undef. 9788 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9789 if (PermMask[i*4+j] < 0) 9790 continue; // Undef, ignore it. 9791 9792 unsigned ByteSource = PermMask[i*4+j]; 9793 if ((ByteSource & 3) != j) { 9794 isFourElementShuffle = false; 9795 break; 9796 } 9797 9798 if (EltNo == 8) { 9799 EltNo = ByteSource/4; 9800 } else if (EltNo != ByteSource/4) { 9801 isFourElementShuffle = false; 9802 break; 9803 } 9804 } 9805 PFIndexes[i] = EltNo; 9806 } 9807 9808 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9809 // perfect shuffle vector to determine if it is cost effective to do this as 9810 // discrete instructions, or whether we should use a vperm. 9811 // For now, we skip this for little endian until such time as we have a 9812 // little-endian perfect shuffle table. 9813 if (isFourElementShuffle && !isLittleEndian) { 9814 // Compute the index in the perfect shuffle table. 9815 unsigned PFTableIndex = 9816 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9817 9818 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9819 unsigned Cost = (PFEntry >> 30); 9820 9821 // Determining when to avoid vperm is tricky. Many things affect the cost 9822 // of vperm, particularly how many times the perm mask needs to be computed. 9823 // For example, if the perm mask can be hoisted out of a loop or is already 9824 // used (perhaps because there are multiple permutes with the same shuffle 9825 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9826 // the loop requires an extra register. 9827 // 9828 // As a compromise, we only emit discrete instructions if the shuffle can be 9829 // generated in 3 or fewer operations. When we have loop information 9830 // available, if this block is within a loop, we should avoid using vperm 9831 // for 3-operation perms and use a constant pool load instead. 9832 if (Cost < 3) 9833 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9834 } 9835 9836 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9837 // vector that will get spilled to the constant pool. 9838 if (V2.isUndef()) V2 = V1; 9839 9840 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9841 // that it is in input element units, not in bytes. Convert now. 9842 9843 // For little endian, the order of the input vectors is reversed, and 9844 // the permutation mask is complemented with respect to 31. This is 9845 // necessary to produce proper semantics with the big-endian-biased vperm 9846 // instruction. 9847 EVT EltVT = V1.getValueType().getVectorElementType(); 9848 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9849 9850 SmallVector<SDValue, 16> ResultMask; 9851 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9852 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9853 9854 for (unsigned j = 0; j != BytesPerElement; ++j) 9855 if (isLittleEndian) 9856 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9857 dl, MVT::i32)); 9858 else 9859 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9860 MVT::i32)); 9861 } 9862 9863 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9864 if (isLittleEndian) 9865 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9866 V2, V1, VPermMask); 9867 else 9868 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9869 V1, V2, VPermMask); 9870 } 9871 9872 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9873 /// vector comparison. If it is, return true and fill in Opc/isDot with 9874 /// information about the intrinsic. 9875 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9876 bool &isDot, const PPCSubtarget &Subtarget) { 9877 unsigned IntrinsicID = 9878 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9879 CompareOpc = -1; 9880 isDot = false; 9881 switch (IntrinsicID) { 9882 default: 9883 return false; 9884 // Comparison predicates. 9885 case Intrinsic::ppc_altivec_vcmpbfp_p: 9886 CompareOpc = 966; 9887 isDot = true; 9888 break; 9889 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9890 CompareOpc = 198; 9891 isDot = true; 9892 break; 9893 case Intrinsic::ppc_altivec_vcmpequb_p: 9894 CompareOpc = 6; 9895 isDot = true; 9896 break; 9897 case Intrinsic::ppc_altivec_vcmpequh_p: 9898 CompareOpc = 70; 9899 isDot = true; 9900 break; 9901 case Intrinsic::ppc_altivec_vcmpequw_p: 9902 CompareOpc = 134; 9903 isDot = true; 9904 break; 9905 case Intrinsic::ppc_altivec_vcmpequd_p: 9906 if (Subtarget.hasP8Altivec()) { 9907 CompareOpc = 199; 9908 isDot = true; 9909 } else 9910 return false; 9911 break; 9912 case Intrinsic::ppc_altivec_vcmpneb_p: 9913 case Intrinsic::ppc_altivec_vcmpneh_p: 9914 case Intrinsic::ppc_altivec_vcmpnew_p: 9915 case Intrinsic::ppc_altivec_vcmpnezb_p: 9916 case Intrinsic::ppc_altivec_vcmpnezh_p: 9917 case Intrinsic::ppc_altivec_vcmpnezw_p: 9918 if (Subtarget.hasP9Altivec()) { 9919 switch (IntrinsicID) { 9920 default: 9921 llvm_unreachable("Unknown comparison intrinsic."); 9922 case Intrinsic::ppc_altivec_vcmpneb_p: 9923 CompareOpc = 7; 9924 break; 9925 case Intrinsic::ppc_altivec_vcmpneh_p: 9926 CompareOpc = 71; 9927 break; 9928 case Intrinsic::ppc_altivec_vcmpnew_p: 9929 CompareOpc = 135; 9930 break; 9931 case Intrinsic::ppc_altivec_vcmpnezb_p: 9932 CompareOpc = 263; 9933 break; 9934 case Intrinsic::ppc_altivec_vcmpnezh_p: 9935 CompareOpc = 327; 9936 break; 9937 case Intrinsic::ppc_altivec_vcmpnezw_p: 9938 CompareOpc = 391; 9939 break; 9940 } 9941 isDot = true; 9942 } else 9943 return false; 9944 break; 9945 case Intrinsic::ppc_altivec_vcmpgefp_p: 9946 CompareOpc = 454; 9947 isDot = true; 9948 break; 9949 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9950 CompareOpc = 710; 9951 isDot = true; 9952 break; 9953 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9954 CompareOpc = 774; 9955 isDot = true; 9956 break; 9957 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9958 CompareOpc = 838; 9959 isDot = true; 9960 break; 9961 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9962 CompareOpc = 902; 9963 isDot = true; 9964 break; 9965 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9966 if (Subtarget.hasP8Altivec()) { 9967 CompareOpc = 967; 9968 isDot = true; 9969 } else 9970 return false; 9971 break; 9972 case Intrinsic::ppc_altivec_vcmpgtub_p: 9973 CompareOpc = 518; 9974 isDot = true; 9975 break; 9976 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9977 CompareOpc = 582; 9978 isDot = true; 9979 break; 9980 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9981 CompareOpc = 646; 9982 isDot = true; 9983 break; 9984 case Intrinsic::ppc_altivec_vcmpgtud_p: 9985 if (Subtarget.hasP8Altivec()) { 9986 CompareOpc = 711; 9987 isDot = true; 9988 } else 9989 return false; 9990 break; 9991 9992 // VSX predicate comparisons use the same infrastructure 9993 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9994 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9995 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9996 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9997 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9998 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9999 if (Subtarget.hasVSX()) { 10000 switch (IntrinsicID) { 10001 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10002 CompareOpc = 99; 10003 break; 10004 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10005 CompareOpc = 115; 10006 break; 10007 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10008 CompareOpc = 107; 10009 break; 10010 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10011 CompareOpc = 67; 10012 break; 10013 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10014 CompareOpc = 83; 10015 break; 10016 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10017 CompareOpc = 75; 10018 break; 10019 } 10020 isDot = true; 10021 } else 10022 return false; 10023 break; 10024 10025 // Normal Comparisons. 10026 case Intrinsic::ppc_altivec_vcmpbfp: 10027 CompareOpc = 966; 10028 break; 10029 case Intrinsic::ppc_altivec_vcmpeqfp: 10030 CompareOpc = 198; 10031 break; 10032 case Intrinsic::ppc_altivec_vcmpequb: 10033 CompareOpc = 6; 10034 break; 10035 case Intrinsic::ppc_altivec_vcmpequh: 10036 CompareOpc = 70; 10037 break; 10038 case Intrinsic::ppc_altivec_vcmpequw: 10039 CompareOpc = 134; 10040 break; 10041 case Intrinsic::ppc_altivec_vcmpequd: 10042 if (Subtarget.hasP8Altivec()) 10043 CompareOpc = 199; 10044 else 10045 return false; 10046 break; 10047 case Intrinsic::ppc_altivec_vcmpneb: 10048 case Intrinsic::ppc_altivec_vcmpneh: 10049 case Intrinsic::ppc_altivec_vcmpnew: 10050 case Intrinsic::ppc_altivec_vcmpnezb: 10051 case Intrinsic::ppc_altivec_vcmpnezh: 10052 case Intrinsic::ppc_altivec_vcmpnezw: 10053 if (Subtarget.hasP9Altivec()) 10054 switch (IntrinsicID) { 10055 default: 10056 llvm_unreachable("Unknown comparison intrinsic."); 10057 case Intrinsic::ppc_altivec_vcmpneb: 10058 CompareOpc = 7; 10059 break; 10060 case Intrinsic::ppc_altivec_vcmpneh: 10061 CompareOpc = 71; 10062 break; 10063 case Intrinsic::ppc_altivec_vcmpnew: 10064 CompareOpc = 135; 10065 break; 10066 case Intrinsic::ppc_altivec_vcmpnezb: 10067 CompareOpc = 263; 10068 break; 10069 case Intrinsic::ppc_altivec_vcmpnezh: 10070 CompareOpc = 327; 10071 break; 10072 case Intrinsic::ppc_altivec_vcmpnezw: 10073 CompareOpc = 391; 10074 break; 10075 } 10076 else 10077 return false; 10078 break; 10079 case Intrinsic::ppc_altivec_vcmpgefp: 10080 CompareOpc = 454; 10081 break; 10082 case Intrinsic::ppc_altivec_vcmpgtfp: 10083 CompareOpc = 710; 10084 break; 10085 case Intrinsic::ppc_altivec_vcmpgtsb: 10086 CompareOpc = 774; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpgtsh: 10089 CompareOpc = 838; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpgtsw: 10092 CompareOpc = 902; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpgtsd: 10095 if (Subtarget.hasP8Altivec()) 10096 CompareOpc = 967; 10097 else 10098 return false; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpgtub: 10101 CompareOpc = 518; 10102 break; 10103 case Intrinsic::ppc_altivec_vcmpgtuh: 10104 CompareOpc = 582; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpgtuw: 10107 CompareOpc = 646; 10108 break; 10109 case Intrinsic::ppc_altivec_vcmpgtud: 10110 if (Subtarget.hasP8Altivec()) 10111 CompareOpc = 711; 10112 else 10113 return false; 10114 break; 10115 } 10116 return true; 10117 } 10118 10119 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10120 /// lower, do it, otherwise return null. 10121 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10122 SelectionDAG &DAG) const { 10123 unsigned IntrinsicID = 10124 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10125 10126 SDLoc dl(Op); 10127 10128 if (IntrinsicID == Intrinsic::thread_pointer) { 10129 // Reads the thread pointer register, used for __builtin_thread_pointer. 10130 if (Subtarget.isPPC64()) 10131 return DAG.getRegister(PPC::X13, MVT::i64); 10132 return DAG.getRegister(PPC::R2, MVT::i32); 10133 } 10134 10135 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10136 // opcode number of the comparison. 10137 int CompareOpc; 10138 bool isDot; 10139 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10140 return SDValue(); // Don't custom lower most intrinsics. 10141 10142 // If this is a non-dot comparison, make the VCMP node and we are done. 10143 if (!isDot) { 10144 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10145 Op.getOperand(1), Op.getOperand(2), 10146 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10147 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10148 } 10149 10150 // Create the PPCISD altivec 'dot' comparison node. 10151 SDValue Ops[] = { 10152 Op.getOperand(2), // LHS 10153 Op.getOperand(3), // RHS 10154 DAG.getConstant(CompareOpc, dl, MVT::i32) 10155 }; 10156 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10157 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10158 10159 // Now that we have the comparison, emit a copy from the CR to a GPR. 10160 // This is flagged to the above dot comparison. 10161 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10162 DAG.getRegister(PPC::CR6, MVT::i32), 10163 CompNode.getValue(1)); 10164 10165 // Unpack the result based on how the target uses it. 10166 unsigned BitNo; // Bit # of CR6. 10167 bool InvertBit; // Invert result? 10168 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10169 default: // Can't happen, don't crash on invalid number though. 10170 case 0: // Return the value of the EQ bit of CR6. 10171 BitNo = 0; InvertBit = false; 10172 break; 10173 case 1: // Return the inverted value of the EQ bit of CR6. 10174 BitNo = 0; InvertBit = true; 10175 break; 10176 case 2: // Return the value of the LT bit of CR6. 10177 BitNo = 2; InvertBit = false; 10178 break; 10179 case 3: // Return the inverted value of the LT bit of CR6. 10180 BitNo = 2; InvertBit = true; 10181 break; 10182 } 10183 10184 // Shift the bit into the low position. 10185 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10186 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10187 // Isolate the bit. 10188 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10189 DAG.getConstant(1, dl, MVT::i32)); 10190 10191 // If we are supposed to, toggle the bit. 10192 if (InvertBit) 10193 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10194 DAG.getConstant(1, dl, MVT::i32)); 10195 return Flags; 10196 } 10197 10198 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10199 SelectionDAG &DAG) const { 10200 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10201 // the beginning of the argument list. 10202 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10203 SDLoc DL(Op); 10204 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10205 case Intrinsic::ppc_cfence: { 10206 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10207 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10208 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10209 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10210 Op.getOperand(ArgStart + 1)), 10211 Op.getOperand(0)), 10212 0); 10213 } 10214 default: 10215 break; 10216 } 10217 return SDValue(); 10218 } 10219 10220 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10221 // Check for a DIV with the same operands as this REM. 10222 for (auto UI : Op.getOperand(1)->uses()) { 10223 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10224 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10225 if (UI->getOperand(0) == Op.getOperand(0) && 10226 UI->getOperand(1) == Op.getOperand(1)) 10227 return SDValue(); 10228 } 10229 return Op; 10230 } 10231 10232 // Lower scalar BSWAP64 to xxbrd. 10233 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10234 SDLoc dl(Op); 10235 // MTVSRDD 10236 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10237 Op.getOperand(0)); 10238 // XXBRD 10239 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10240 // MFVSRD 10241 int VectorIndex = 0; 10242 if (Subtarget.isLittleEndian()) 10243 VectorIndex = 1; 10244 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10245 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10246 return Op; 10247 } 10248 10249 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10250 // compared to a value that is atomically loaded (atomic loads zero-extend). 10251 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10252 SelectionDAG &DAG) const { 10253 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10254 "Expecting an atomic compare-and-swap here."); 10255 SDLoc dl(Op); 10256 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10257 EVT MemVT = AtomicNode->getMemoryVT(); 10258 if (MemVT.getSizeInBits() >= 32) 10259 return Op; 10260 10261 SDValue CmpOp = Op.getOperand(2); 10262 // If this is already correctly zero-extended, leave it alone. 10263 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10264 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10265 return Op; 10266 10267 // Clear the high bits of the compare operand. 10268 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10269 SDValue NewCmpOp = 10270 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10271 DAG.getConstant(MaskVal, dl, MVT::i32)); 10272 10273 // Replace the existing compare operand with the properly zero-extended one. 10274 SmallVector<SDValue, 4> Ops; 10275 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10276 Ops.push_back(AtomicNode->getOperand(i)); 10277 Ops[2] = NewCmpOp; 10278 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10279 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10280 auto NodeTy = 10281 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10282 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10283 } 10284 10285 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10286 SelectionDAG &DAG) const { 10287 SDLoc dl(Op); 10288 // Create a stack slot that is 16-byte aligned. 10289 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10290 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10291 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10292 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10293 10294 // Store the input value into Value#0 of the stack slot. 10295 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10296 MachinePointerInfo()); 10297 // Load it out. 10298 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10299 } 10300 10301 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10302 SelectionDAG &DAG) const { 10303 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10304 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10305 10306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10307 // We have legal lowering for constant indices but not for variable ones. 10308 if (!C) 10309 return SDValue(); 10310 10311 EVT VT = Op.getValueType(); 10312 SDLoc dl(Op); 10313 SDValue V1 = Op.getOperand(0); 10314 SDValue V2 = Op.getOperand(1); 10315 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10316 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10317 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10318 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10319 unsigned InsertAtElement = C->getZExtValue(); 10320 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10321 if (Subtarget.isLittleEndian()) { 10322 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10323 } 10324 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10325 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10326 } 10327 return Op; 10328 } 10329 10330 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10331 SelectionDAG &DAG) const { 10332 SDLoc dl(Op); 10333 SDNode *N = Op.getNode(); 10334 10335 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10336 "Unknown extract_vector_elt type"); 10337 10338 SDValue Value = N->getOperand(0); 10339 10340 // The first part of this is like the store lowering except that we don't 10341 // need to track the chain. 10342 10343 // The values are now known to be -1 (false) or 1 (true). To convert this 10344 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10345 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10346 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10347 10348 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10349 // understand how to form the extending load. 10350 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10351 10352 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10353 10354 // Now convert to an integer and store. 10355 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10356 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10357 Value); 10358 10359 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10360 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10361 MachinePointerInfo PtrInfo = 10362 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10363 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10364 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10365 10366 SDValue StoreChain = DAG.getEntryNode(); 10367 SDValue Ops[] = {StoreChain, 10368 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10369 Value, FIdx}; 10370 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10371 10372 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10373 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10374 10375 // Extract the value requested. 10376 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10377 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10378 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10379 10380 SDValue IntVal = 10381 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10382 10383 if (!Subtarget.useCRBits()) 10384 return IntVal; 10385 10386 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10387 } 10388 10389 /// Lowering for QPX v4i1 loads 10390 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10391 SelectionDAG &DAG) const { 10392 SDLoc dl(Op); 10393 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10394 SDValue LoadChain = LN->getChain(); 10395 SDValue BasePtr = LN->getBasePtr(); 10396 10397 if (Op.getValueType() == MVT::v4f64 || 10398 Op.getValueType() == MVT::v4f32) { 10399 EVT MemVT = LN->getMemoryVT(); 10400 unsigned Alignment = LN->getAlignment(); 10401 10402 // If this load is properly aligned, then it is legal. 10403 if (Alignment >= MemVT.getStoreSize()) 10404 return Op; 10405 10406 EVT ScalarVT = Op.getValueType().getScalarType(), 10407 ScalarMemVT = MemVT.getScalarType(); 10408 unsigned Stride = ScalarMemVT.getStoreSize(); 10409 10410 SDValue Vals[4], LoadChains[4]; 10411 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10412 SDValue Load; 10413 if (ScalarVT != ScalarMemVT) 10414 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10415 BasePtr, 10416 LN->getPointerInfo().getWithOffset(Idx * Stride), 10417 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10418 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10419 else 10420 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10421 LN->getPointerInfo().getWithOffset(Idx * Stride), 10422 MinAlign(Alignment, Idx * Stride), 10423 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10424 10425 if (Idx == 0 && LN->isIndexed()) { 10426 assert(LN->getAddressingMode() == ISD::PRE_INC && 10427 "Unknown addressing mode on vector load"); 10428 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10429 LN->getAddressingMode()); 10430 } 10431 10432 Vals[Idx] = Load; 10433 LoadChains[Idx] = Load.getValue(1); 10434 10435 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10436 DAG.getConstant(Stride, dl, 10437 BasePtr.getValueType())); 10438 } 10439 10440 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10441 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10442 10443 if (LN->isIndexed()) { 10444 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10445 return DAG.getMergeValues(RetOps, dl); 10446 } 10447 10448 SDValue RetOps[] = { Value, TF }; 10449 return DAG.getMergeValues(RetOps, dl); 10450 } 10451 10452 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10453 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10454 10455 // To lower v4i1 from a byte array, we load the byte elements of the 10456 // vector and then reuse the BUILD_VECTOR logic. 10457 10458 SDValue VectElmts[4], VectElmtChains[4]; 10459 for (unsigned i = 0; i < 4; ++i) { 10460 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10461 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10462 10463 VectElmts[i] = DAG.getExtLoad( 10464 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10465 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10466 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10467 VectElmtChains[i] = VectElmts[i].getValue(1); 10468 } 10469 10470 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10471 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10472 10473 SDValue RVals[] = { Value, LoadChain }; 10474 return DAG.getMergeValues(RVals, dl); 10475 } 10476 10477 /// Lowering for QPX v4i1 stores 10478 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10479 SelectionDAG &DAG) const { 10480 SDLoc dl(Op); 10481 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10482 SDValue StoreChain = SN->getChain(); 10483 SDValue BasePtr = SN->getBasePtr(); 10484 SDValue Value = SN->getValue(); 10485 10486 if (Value.getValueType() == MVT::v4f64 || 10487 Value.getValueType() == MVT::v4f32) { 10488 EVT MemVT = SN->getMemoryVT(); 10489 unsigned Alignment = SN->getAlignment(); 10490 10491 // If this store is properly aligned, then it is legal. 10492 if (Alignment >= MemVT.getStoreSize()) 10493 return Op; 10494 10495 EVT ScalarVT = Value.getValueType().getScalarType(), 10496 ScalarMemVT = MemVT.getScalarType(); 10497 unsigned Stride = ScalarMemVT.getStoreSize(); 10498 10499 SDValue Stores[4]; 10500 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10501 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10502 DAG.getVectorIdxConstant(Idx, dl)); 10503 SDValue Store; 10504 if (ScalarVT != ScalarMemVT) 10505 Store = 10506 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10507 SN->getPointerInfo().getWithOffset(Idx * Stride), 10508 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10509 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10510 else 10511 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10512 SN->getPointerInfo().getWithOffset(Idx * Stride), 10513 MinAlign(Alignment, Idx * Stride), 10514 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10515 10516 if (Idx == 0 && SN->isIndexed()) { 10517 assert(SN->getAddressingMode() == ISD::PRE_INC && 10518 "Unknown addressing mode on vector store"); 10519 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10520 SN->getAddressingMode()); 10521 } 10522 10523 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10524 DAG.getConstant(Stride, dl, 10525 BasePtr.getValueType())); 10526 Stores[Idx] = Store; 10527 } 10528 10529 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10530 10531 if (SN->isIndexed()) { 10532 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10533 return DAG.getMergeValues(RetOps, dl); 10534 } 10535 10536 return TF; 10537 } 10538 10539 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10540 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10541 10542 // The values are now known to be -1 (false) or 1 (true). To convert this 10543 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10544 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10545 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10546 10547 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10548 // understand how to form the extending load. 10549 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10550 10551 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10552 10553 // Now convert to an integer and store. 10554 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10555 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10556 Value); 10557 10558 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10559 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10560 MachinePointerInfo PtrInfo = 10561 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10562 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10563 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10564 10565 SDValue Ops[] = {StoreChain, 10566 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10567 Value, FIdx}; 10568 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10569 10570 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10571 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10572 10573 // Move data into the byte array. 10574 SDValue Loads[4], LoadChains[4]; 10575 for (unsigned i = 0; i < 4; ++i) { 10576 unsigned Offset = 4*i; 10577 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10578 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10579 10580 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10581 PtrInfo.getWithOffset(Offset)); 10582 LoadChains[i] = Loads[i].getValue(1); 10583 } 10584 10585 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10586 10587 SDValue Stores[4]; 10588 for (unsigned i = 0; i < 4; ++i) { 10589 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10590 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10591 10592 Stores[i] = DAG.getTruncStore( 10593 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10594 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10595 SN->getAAInfo()); 10596 } 10597 10598 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10599 10600 return StoreChain; 10601 } 10602 10603 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10604 SDLoc dl(Op); 10605 if (Op.getValueType() == MVT::v4i32) { 10606 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10607 10608 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10609 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10610 10611 SDValue RHSSwap = // = vrlw RHS, 16 10612 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10613 10614 // Shrinkify inputs to v8i16. 10615 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10616 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10617 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10618 10619 // Low parts multiplied together, generating 32-bit results (we ignore the 10620 // top parts). 10621 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10622 LHS, RHS, DAG, dl, MVT::v4i32); 10623 10624 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10625 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10626 // Shift the high parts up 16 bits. 10627 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10628 Neg16, DAG, dl); 10629 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10630 } else if (Op.getValueType() == MVT::v16i8) { 10631 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10632 bool isLittleEndian = Subtarget.isLittleEndian(); 10633 10634 // Multiply the even 8-bit parts, producing 16-bit sums. 10635 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10636 LHS, RHS, DAG, dl, MVT::v8i16); 10637 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10638 10639 // Multiply the odd 8-bit parts, producing 16-bit sums. 10640 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10641 LHS, RHS, DAG, dl, MVT::v8i16); 10642 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10643 10644 // Merge the results together. Because vmuleub and vmuloub are 10645 // instructions with a big-endian bias, we must reverse the 10646 // element numbering and reverse the meaning of "odd" and "even" 10647 // when generating little endian code. 10648 int Ops[16]; 10649 for (unsigned i = 0; i != 8; ++i) { 10650 if (isLittleEndian) { 10651 Ops[i*2 ] = 2*i; 10652 Ops[i*2+1] = 2*i+16; 10653 } else { 10654 Ops[i*2 ] = 2*i+1; 10655 Ops[i*2+1] = 2*i+1+16; 10656 } 10657 } 10658 if (isLittleEndian) 10659 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10660 else 10661 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10662 } else { 10663 llvm_unreachable("Unknown mul to lower!"); 10664 } 10665 } 10666 10667 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10668 10669 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10670 10671 EVT VT = Op.getValueType(); 10672 assert(VT.isVector() && 10673 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10674 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10675 VT == MVT::v16i8) && 10676 "Unexpected vector element type!"); 10677 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10678 "Current subtarget doesn't support smax v2i64!"); 10679 10680 // For vector abs, it can be lowered to: 10681 // abs x 10682 // ==> 10683 // y = -x 10684 // smax(x, y) 10685 10686 SDLoc dl(Op); 10687 SDValue X = Op.getOperand(0); 10688 SDValue Zero = DAG.getConstant(0, dl, VT); 10689 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10690 10691 // SMAX patch https://reviews.llvm.org/D47332 10692 // hasn't landed yet, so use intrinsic first here. 10693 // TODO: Should use SMAX directly once SMAX patch landed 10694 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10695 if (VT == MVT::v2i64) 10696 BifID = Intrinsic::ppc_altivec_vmaxsd; 10697 else if (VT == MVT::v8i16) 10698 BifID = Intrinsic::ppc_altivec_vmaxsh; 10699 else if (VT == MVT::v16i8) 10700 BifID = Intrinsic::ppc_altivec_vmaxsb; 10701 10702 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10703 } 10704 10705 // Custom lowering for fpext vf32 to v2f64 10706 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10707 10708 assert(Op.getOpcode() == ISD::FP_EXTEND && 10709 "Should only be called for ISD::FP_EXTEND"); 10710 10711 // We only want to custom lower an extend from v2f32 to v2f64. 10712 if (Op.getValueType() != MVT::v2f64 || 10713 Op.getOperand(0).getValueType() != MVT::v2f32) 10714 return SDValue(); 10715 10716 SDLoc dl(Op); 10717 SDValue Op0 = Op.getOperand(0); 10718 10719 switch (Op0.getOpcode()) { 10720 default: 10721 return SDValue(); 10722 case ISD::EXTRACT_SUBVECTOR: { 10723 assert(Op0.getNumOperands() == 2 && 10724 isa<ConstantSDNode>(Op0->getOperand(1)) && 10725 "Node should have 2 operands with second one being a constant!"); 10726 10727 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10728 return SDValue(); 10729 10730 // Custom lower is only done for high or low doubleword. 10731 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10732 if (Idx % 2 != 0) 10733 return SDValue(); 10734 10735 // Since input is v4f32, at this point Idx is either 0 or 2. 10736 // Shift to get the doubleword position we want. 10737 int DWord = Idx >> 1; 10738 10739 // High and low word positions are different on little endian. 10740 if (Subtarget.isLittleEndian()) 10741 DWord ^= 0x1; 10742 10743 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10744 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10745 } 10746 case ISD::FADD: 10747 case ISD::FMUL: 10748 case ISD::FSUB: { 10749 SDValue NewLoad[2]; 10750 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10751 // Ensure both input are loads. 10752 SDValue LdOp = Op0.getOperand(i); 10753 if (LdOp.getOpcode() != ISD::LOAD) 10754 return SDValue(); 10755 // Generate new load node. 10756 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10757 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10758 NewLoad[i] = DAG.getMemIntrinsicNode( 10759 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10760 LD->getMemoryVT(), LD->getMemOperand()); 10761 } 10762 SDValue NewOp = 10763 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10764 NewLoad[1], Op0.getNode()->getFlags()); 10765 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10766 DAG.getConstant(0, dl, MVT::i32)); 10767 } 10768 case ISD::LOAD: { 10769 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10770 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10771 SDValue NewLd = DAG.getMemIntrinsicNode( 10772 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10773 LD->getMemoryVT(), LD->getMemOperand()); 10774 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10775 DAG.getConstant(0, dl, MVT::i32)); 10776 } 10777 } 10778 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10779 } 10780 10781 /// LowerOperation - Provide custom lowering hooks for some operations. 10782 /// 10783 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10784 switch (Op.getOpcode()) { 10785 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10786 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10787 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10788 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10789 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10790 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10791 case ISD::SETCC: return LowerSETCC(Op, DAG); 10792 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10793 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10794 10795 // Variable argument lowering. 10796 case ISD::VASTART: return LowerVASTART(Op, DAG); 10797 case ISD::VAARG: return LowerVAARG(Op, DAG); 10798 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10799 10800 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10801 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10802 case ISD::GET_DYNAMIC_AREA_OFFSET: 10803 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10804 10805 // Exception handling lowering. 10806 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10807 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10808 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10809 10810 case ISD::LOAD: return LowerLOAD(Op, DAG); 10811 case ISD::STORE: return LowerSTORE(Op, DAG); 10812 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10813 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10814 case ISD::FP_TO_UINT: 10815 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10816 case ISD::UINT_TO_FP: 10817 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10818 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10819 10820 // Lower 64-bit shifts. 10821 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10822 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10823 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10824 10825 // Vector-related lowering. 10826 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10827 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10828 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10829 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10830 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10831 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10832 case ISD::MUL: return LowerMUL(Op, DAG); 10833 case ISD::ABS: return LowerABS(Op, DAG); 10834 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10835 10836 // For counter-based loop handling. 10837 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10838 10839 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10840 10841 // Frame & Return address. 10842 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10843 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10844 10845 case ISD::INTRINSIC_VOID: 10846 return LowerINTRINSIC_VOID(Op, DAG); 10847 case ISD::SREM: 10848 case ISD::UREM: 10849 return LowerREM(Op, DAG); 10850 case ISD::BSWAP: 10851 return LowerBSWAP(Op, DAG); 10852 case ISD::ATOMIC_CMP_SWAP: 10853 return LowerATOMIC_CMP_SWAP(Op, DAG); 10854 } 10855 } 10856 10857 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10858 SmallVectorImpl<SDValue>&Results, 10859 SelectionDAG &DAG) const { 10860 SDLoc dl(N); 10861 switch (N->getOpcode()) { 10862 default: 10863 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10864 case ISD::READCYCLECOUNTER: { 10865 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10866 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10867 10868 Results.push_back( 10869 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10870 Results.push_back(RTB.getValue(2)); 10871 break; 10872 } 10873 case ISD::INTRINSIC_W_CHAIN: { 10874 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10875 Intrinsic::loop_decrement) 10876 break; 10877 10878 assert(N->getValueType(0) == MVT::i1 && 10879 "Unexpected result type for CTR decrement intrinsic"); 10880 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10881 N->getValueType(0)); 10882 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10883 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10884 N->getOperand(1)); 10885 10886 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10887 Results.push_back(NewInt.getValue(1)); 10888 break; 10889 } 10890 case ISD::VAARG: { 10891 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10892 return; 10893 10894 EVT VT = N->getValueType(0); 10895 10896 if (VT == MVT::i64) { 10897 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10898 10899 Results.push_back(NewNode); 10900 Results.push_back(NewNode.getValue(1)); 10901 } 10902 return; 10903 } 10904 case ISD::FP_TO_SINT: 10905 case ISD::FP_TO_UINT: 10906 // LowerFP_TO_INT() can only handle f32 and f64. 10907 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10908 return; 10909 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10910 return; 10911 case ISD::TRUNCATE: { 10912 EVT TrgVT = N->getValueType(0); 10913 EVT OpVT = N->getOperand(0).getValueType(); 10914 if (TrgVT.isVector() && 10915 isOperationCustom(N->getOpcode(), TrgVT) && 10916 OpVT.getSizeInBits() <= 128 && 10917 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10918 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10919 return; 10920 } 10921 case ISD::BITCAST: 10922 // Don't handle bitcast here. 10923 return; 10924 } 10925 } 10926 10927 //===----------------------------------------------------------------------===// 10928 // Other Lowering Code 10929 //===----------------------------------------------------------------------===// 10930 10931 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10932 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10933 Function *Func = Intrinsic::getDeclaration(M, Id); 10934 return Builder.CreateCall(Func, {}); 10935 } 10936 10937 // The mappings for emitLeading/TrailingFence is taken from 10938 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10939 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10940 Instruction *Inst, 10941 AtomicOrdering Ord) const { 10942 if (Ord == AtomicOrdering::SequentiallyConsistent) 10943 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10944 if (isReleaseOrStronger(Ord)) 10945 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10946 return nullptr; 10947 } 10948 10949 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10950 Instruction *Inst, 10951 AtomicOrdering Ord) const { 10952 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10953 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10954 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10955 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10956 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10957 return Builder.CreateCall( 10958 Intrinsic::getDeclaration( 10959 Builder.GetInsertBlock()->getParent()->getParent(), 10960 Intrinsic::ppc_cfence, {Inst->getType()}), 10961 {Inst}); 10962 // FIXME: Can use isync for rmw operation. 10963 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10964 } 10965 return nullptr; 10966 } 10967 10968 MachineBasicBlock * 10969 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10970 unsigned AtomicSize, 10971 unsigned BinOpcode, 10972 unsigned CmpOpcode, 10973 unsigned CmpPred) const { 10974 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10975 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10976 10977 auto LoadMnemonic = PPC::LDARX; 10978 auto StoreMnemonic = PPC::STDCX; 10979 switch (AtomicSize) { 10980 default: 10981 llvm_unreachable("Unexpected size of atomic entity"); 10982 case 1: 10983 LoadMnemonic = PPC::LBARX; 10984 StoreMnemonic = PPC::STBCX; 10985 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10986 break; 10987 case 2: 10988 LoadMnemonic = PPC::LHARX; 10989 StoreMnemonic = PPC::STHCX; 10990 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10991 break; 10992 case 4: 10993 LoadMnemonic = PPC::LWARX; 10994 StoreMnemonic = PPC::STWCX; 10995 break; 10996 case 8: 10997 LoadMnemonic = PPC::LDARX; 10998 StoreMnemonic = PPC::STDCX; 10999 break; 11000 } 11001 11002 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11003 MachineFunction *F = BB->getParent(); 11004 MachineFunction::iterator It = ++BB->getIterator(); 11005 11006 Register dest = MI.getOperand(0).getReg(); 11007 Register ptrA = MI.getOperand(1).getReg(); 11008 Register ptrB = MI.getOperand(2).getReg(); 11009 Register incr = MI.getOperand(3).getReg(); 11010 DebugLoc dl = MI.getDebugLoc(); 11011 11012 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11013 MachineBasicBlock *loop2MBB = 11014 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11015 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11016 F->insert(It, loopMBB); 11017 if (CmpOpcode) 11018 F->insert(It, loop2MBB); 11019 F->insert(It, exitMBB); 11020 exitMBB->splice(exitMBB->begin(), BB, 11021 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11022 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11023 11024 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11025 Register TmpReg = (!BinOpcode) ? incr : 11026 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11027 : &PPC::GPRCRegClass); 11028 11029 // thisMBB: 11030 // ... 11031 // fallthrough --> loopMBB 11032 BB->addSuccessor(loopMBB); 11033 11034 // loopMBB: 11035 // l[wd]arx dest, ptr 11036 // add r0, dest, incr 11037 // st[wd]cx. r0, ptr 11038 // bne- loopMBB 11039 // fallthrough --> exitMBB 11040 11041 // For max/min... 11042 // loopMBB: 11043 // l[wd]arx dest, ptr 11044 // cmpl?[wd] incr, dest 11045 // bgt exitMBB 11046 // loop2MBB: 11047 // st[wd]cx. dest, ptr 11048 // bne- loopMBB 11049 // fallthrough --> exitMBB 11050 11051 BB = loopMBB; 11052 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11053 .addReg(ptrA).addReg(ptrB); 11054 if (BinOpcode) 11055 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11056 if (CmpOpcode) { 11057 // Signed comparisons of byte or halfword values must be sign-extended. 11058 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11059 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11060 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11061 ExtReg).addReg(dest); 11062 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11063 .addReg(incr).addReg(ExtReg); 11064 } else 11065 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11066 .addReg(incr).addReg(dest); 11067 11068 BuildMI(BB, dl, TII->get(PPC::BCC)) 11069 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11070 BB->addSuccessor(loop2MBB); 11071 BB->addSuccessor(exitMBB); 11072 BB = loop2MBB; 11073 } 11074 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11075 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11076 BuildMI(BB, dl, TII->get(PPC::BCC)) 11077 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11078 BB->addSuccessor(loopMBB); 11079 BB->addSuccessor(exitMBB); 11080 11081 // exitMBB: 11082 // ... 11083 BB = exitMBB; 11084 return BB; 11085 } 11086 11087 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11088 MachineInstr &MI, MachineBasicBlock *BB, 11089 bool is8bit, // operation 11090 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11091 // If we support part-word atomic mnemonics, just use them 11092 if (Subtarget.hasPartwordAtomics()) 11093 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11094 CmpPred); 11095 11096 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11097 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11098 // In 64 bit mode we have to use 64 bits for addresses, even though the 11099 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11100 // registers without caring whether they're 32 or 64, but here we're 11101 // doing actual arithmetic on the addresses. 11102 bool is64bit = Subtarget.isPPC64(); 11103 bool isLittleEndian = Subtarget.isLittleEndian(); 11104 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11105 11106 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11107 MachineFunction *F = BB->getParent(); 11108 MachineFunction::iterator It = ++BB->getIterator(); 11109 11110 Register dest = MI.getOperand(0).getReg(); 11111 Register ptrA = MI.getOperand(1).getReg(); 11112 Register ptrB = MI.getOperand(2).getReg(); 11113 Register incr = MI.getOperand(3).getReg(); 11114 DebugLoc dl = MI.getDebugLoc(); 11115 11116 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11117 MachineBasicBlock *loop2MBB = 11118 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11119 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11120 F->insert(It, loopMBB); 11121 if (CmpOpcode) 11122 F->insert(It, loop2MBB); 11123 F->insert(It, exitMBB); 11124 exitMBB->splice(exitMBB->begin(), BB, 11125 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11126 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11127 11128 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11129 const TargetRegisterClass *RC = 11130 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11131 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11132 11133 Register PtrReg = RegInfo.createVirtualRegister(RC); 11134 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11135 Register ShiftReg = 11136 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11137 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11138 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11139 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11140 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11141 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11142 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11143 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11144 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11145 Register Ptr1Reg; 11146 Register TmpReg = 11147 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11148 11149 // thisMBB: 11150 // ... 11151 // fallthrough --> loopMBB 11152 BB->addSuccessor(loopMBB); 11153 11154 // The 4-byte load must be aligned, while a char or short may be 11155 // anywhere in the word. Hence all this nasty bookkeeping code. 11156 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11157 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11158 // xori shift, shift1, 24 [16] 11159 // rlwinm ptr, ptr1, 0, 0, 29 11160 // slw incr2, incr, shift 11161 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11162 // slw mask, mask2, shift 11163 // loopMBB: 11164 // lwarx tmpDest, ptr 11165 // add tmp, tmpDest, incr2 11166 // andc tmp2, tmpDest, mask 11167 // and tmp3, tmp, mask 11168 // or tmp4, tmp3, tmp2 11169 // stwcx. tmp4, ptr 11170 // bne- loopMBB 11171 // fallthrough --> exitMBB 11172 // srw dest, tmpDest, shift 11173 if (ptrA != ZeroReg) { 11174 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11175 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11176 .addReg(ptrA) 11177 .addReg(ptrB); 11178 } else { 11179 Ptr1Reg = ptrB; 11180 } 11181 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11182 // mode. 11183 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11184 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11185 .addImm(3) 11186 .addImm(27) 11187 .addImm(is8bit ? 28 : 27); 11188 if (!isLittleEndian) 11189 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11190 .addReg(Shift1Reg) 11191 .addImm(is8bit ? 24 : 16); 11192 if (is64bit) 11193 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11194 .addReg(Ptr1Reg) 11195 .addImm(0) 11196 .addImm(61); 11197 else 11198 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11199 .addReg(Ptr1Reg) 11200 .addImm(0) 11201 .addImm(0) 11202 .addImm(29); 11203 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11204 if (is8bit) 11205 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11206 else { 11207 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11208 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11209 .addReg(Mask3Reg) 11210 .addImm(65535); 11211 } 11212 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11213 .addReg(Mask2Reg) 11214 .addReg(ShiftReg); 11215 11216 BB = loopMBB; 11217 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11218 .addReg(ZeroReg) 11219 .addReg(PtrReg); 11220 if (BinOpcode) 11221 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11222 .addReg(Incr2Reg) 11223 .addReg(TmpDestReg); 11224 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11225 .addReg(TmpDestReg) 11226 .addReg(MaskReg); 11227 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11228 if (CmpOpcode) { 11229 // For unsigned comparisons, we can directly compare the shifted values. 11230 // For signed comparisons we shift and sign extend. 11231 Register SReg = RegInfo.createVirtualRegister(GPRC); 11232 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11233 .addReg(TmpDestReg) 11234 .addReg(MaskReg); 11235 unsigned ValueReg = SReg; 11236 unsigned CmpReg = Incr2Reg; 11237 if (CmpOpcode == PPC::CMPW) { 11238 ValueReg = RegInfo.createVirtualRegister(GPRC); 11239 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11240 .addReg(SReg) 11241 .addReg(ShiftReg); 11242 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11243 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11244 .addReg(ValueReg); 11245 ValueReg = ValueSReg; 11246 CmpReg = incr; 11247 } 11248 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11249 .addReg(CmpReg) 11250 .addReg(ValueReg); 11251 BuildMI(BB, dl, TII->get(PPC::BCC)) 11252 .addImm(CmpPred) 11253 .addReg(PPC::CR0) 11254 .addMBB(exitMBB); 11255 BB->addSuccessor(loop2MBB); 11256 BB->addSuccessor(exitMBB); 11257 BB = loop2MBB; 11258 } 11259 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11260 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11261 .addReg(Tmp4Reg) 11262 .addReg(ZeroReg) 11263 .addReg(PtrReg); 11264 BuildMI(BB, dl, TII->get(PPC::BCC)) 11265 .addImm(PPC::PRED_NE) 11266 .addReg(PPC::CR0) 11267 .addMBB(loopMBB); 11268 BB->addSuccessor(loopMBB); 11269 BB->addSuccessor(exitMBB); 11270 11271 // exitMBB: 11272 // ... 11273 BB = exitMBB; 11274 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11275 .addReg(TmpDestReg) 11276 .addReg(ShiftReg); 11277 return BB; 11278 } 11279 11280 llvm::MachineBasicBlock * 11281 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11282 MachineBasicBlock *MBB) const { 11283 DebugLoc DL = MI.getDebugLoc(); 11284 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11285 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11286 11287 MachineFunction *MF = MBB->getParent(); 11288 MachineRegisterInfo &MRI = MF->getRegInfo(); 11289 11290 const BasicBlock *BB = MBB->getBasicBlock(); 11291 MachineFunction::iterator I = ++MBB->getIterator(); 11292 11293 Register DstReg = MI.getOperand(0).getReg(); 11294 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11295 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11296 Register mainDstReg = MRI.createVirtualRegister(RC); 11297 Register restoreDstReg = MRI.createVirtualRegister(RC); 11298 11299 MVT PVT = getPointerTy(MF->getDataLayout()); 11300 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11301 "Invalid Pointer Size!"); 11302 // For v = setjmp(buf), we generate 11303 // 11304 // thisMBB: 11305 // SjLjSetup mainMBB 11306 // bl mainMBB 11307 // v_restore = 1 11308 // b sinkMBB 11309 // 11310 // mainMBB: 11311 // buf[LabelOffset] = LR 11312 // v_main = 0 11313 // 11314 // sinkMBB: 11315 // v = phi(main, restore) 11316 // 11317 11318 MachineBasicBlock *thisMBB = MBB; 11319 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11320 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11321 MF->insert(I, mainMBB); 11322 MF->insert(I, sinkMBB); 11323 11324 MachineInstrBuilder MIB; 11325 11326 // Transfer the remainder of BB and its successor edges to sinkMBB. 11327 sinkMBB->splice(sinkMBB->begin(), MBB, 11328 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11329 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11330 11331 // Note that the structure of the jmp_buf used here is not compatible 11332 // with that used by libc, and is not designed to be. Specifically, it 11333 // stores only those 'reserved' registers that LLVM does not otherwise 11334 // understand how to spill. Also, by convention, by the time this 11335 // intrinsic is called, Clang has already stored the frame address in the 11336 // first slot of the buffer and stack address in the third. Following the 11337 // X86 target code, we'll store the jump address in the second slot. We also 11338 // need to save the TOC pointer (R2) to handle jumps between shared 11339 // libraries, and that will be stored in the fourth slot. The thread 11340 // identifier (R13) is not affected. 11341 11342 // thisMBB: 11343 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11344 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11345 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11346 11347 // Prepare IP either in reg. 11348 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11349 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11350 Register BufReg = MI.getOperand(1).getReg(); 11351 11352 if (Subtarget.is64BitELFABI()) { 11353 setUsesTOCBasePtr(*MBB->getParent()); 11354 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11355 .addReg(PPC::X2) 11356 .addImm(TOCOffset) 11357 .addReg(BufReg) 11358 .cloneMemRefs(MI); 11359 } 11360 11361 // Naked functions never have a base pointer, and so we use r1. For all 11362 // other functions, this decision must be delayed until during PEI. 11363 unsigned BaseReg; 11364 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11365 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11366 else 11367 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11368 11369 MIB = BuildMI(*thisMBB, MI, DL, 11370 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11371 .addReg(BaseReg) 11372 .addImm(BPOffset) 11373 .addReg(BufReg) 11374 .cloneMemRefs(MI); 11375 11376 // Setup 11377 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11378 MIB.addRegMask(TRI->getNoPreservedMask()); 11379 11380 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11381 11382 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11383 .addMBB(mainMBB); 11384 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11385 11386 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11387 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11388 11389 // mainMBB: 11390 // mainDstReg = 0 11391 MIB = 11392 BuildMI(mainMBB, DL, 11393 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11394 11395 // Store IP 11396 if (Subtarget.isPPC64()) { 11397 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11398 .addReg(LabelReg) 11399 .addImm(LabelOffset) 11400 .addReg(BufReg); 11401 } else { 11402 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11403 .addReg(LabelReg) 11404 .addImm(LabelOffset) 11405 .addReg(BufReg); 11406 } 11407 MIB.cloneMemRefs(MI); 11408 11409 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11410 mainMBB->addSuccessor(sinkMBB); 11411 11412 // sinkMBB: 11413 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11414 TII->get(PPC::PHI), DstReg) 11415 .addReg(mainDstReg).addMBB(mainMBB) 11416 .addReg(restoreDstReg).addMBB(thisMBB); 11417 11418 MI.eraseFromParent(); 11419 return sinkMBB; 11420 } 11421 11422 MachineBasicBlock * 11423 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11424 MachineBasicBlock *MBB) const { 11425 DebugLoc DL = MI.getDebugLoc(); 11426 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11427 11428 MachineFunction *MF = MBB->getParent(); 11429 MachineRegisterInfo &MRI = MF->getRegInfo(); 11430 11431 MVT PVT = getPointerTy(MF->getDataLayout()); 11432 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11433 "Invalid Pointer Size!"); 11434 11435 const TargetRegisterClass *RC = 11436 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11437 Register Tmp = MRI.createVirtualRegister(RC); 11438 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11439 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11440 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11441 unsigned BP = 11442 (PVT == MVT::i64) 11443 ? PPC::X30 11444 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11445 : PPC::R30); 11446 11447 MachineInstrBuilder MIB; 11448 11449 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11450 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11451 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11452 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11453 11454 Register BufReg = MI.getOperand(0).getReg(); 11455 11456 // Reload FP (the jumped-to function may not have had a 11457 // frame pointer, and if so, then its r31 will be restored 11458 // as necessary). 11459 if (PVT == MVT::i64) { 11460 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11461 .addImm(0) 11462 .addReg(BufReg); 11463 } else { 11464 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11465 .addImm(0) 11466 .addReg(BufReg); 11467 } 11468 MIB.cloneMemRefs(MI); 11469 11470 // Reload IP 11471 if (PVT == MVT::i64) { 11472 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11473 .addImm(LabelOffset) 11474 .addReg(BufReg); 11475 } else { 11476 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11477 .addImm(LabelOffset) 11478 .addReg(BufReg); 11479 } 11480 MIB.cloneMemRefs(MI); 11481 11482 // Reload SP 11483 if (PVT == MVT::i64) { 11484 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11485 .addImm(SPOffset) 11486 .addReg(BufReg); 11487 } else { 11488 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11489 .addImm(SPOffset) 11490 .addReg(BufReg); 11491 } 11492 MIB.cloneMemRefs(MI); 11493 11494 // Reload BP 11495 if (PVT == MVT::i64) { 11496 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11497 .addImm(BPOffset) 11498 .addReg(BufReg); 11499 } else { 11500 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11501 .addImm(BPOffset) 11502 .addReg(BufReg); 11503 } 11504 MIB.cloneMemRefs(MI); 11505 11506 // Reload TOC 11507 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11508 setUsesTOCBasePtr(*MBB->getParent()); 11509 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11510 .addImm(TOCOffset) 11511 .addReg(BufReg) 11512 .cloneMemRefs(MI); 11513 } 11514 11515 // Jump 11516 BuildMI(*MBB, MI, DL, 11517 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11518 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11519 11520 MI.eraseFromParent(); 11521 return MBB; 11522 } 11523 11524 MachineBasicBlock * 11525 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11526 MachineBasicBlock *BB) const { 11527 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11528 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11529 if (Subtarget.is64BitELFABI() && 11530 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11531 !Subtarget.isUsingPCRelativeCalls()) { 11532 // Call lowering should have added an r2 operand to indicate a dependence 11533 // on the TOC base pointer value. It can't however, because there is no 11534 // way to mark the dependence as implicit there, and so the stackmap code 11535 // will confuse it with a regular operand. Instead, add the dependence 11536 // here. 11537 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11538 } 11539 11540 return emitPatchPoint(MI, BB); 11541 } 11542 11543 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11544 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11545 return emitEHSjLjSetJmp(MI, BB); 11546 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11547 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11548 return emitEHSjLjLongJmp(MI, BB); 11549 } 11550 11551 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11552 11553 // To "insert" these instructions we actually have to insert their 11554 // control-flow patterns. 11555 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11556 MachineFunction::iterator It = ++BB->getIterator(); 11557 11558 MachineFunction *F = BB->getParent(); 11559 11560 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11561 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11562 MI.getOpcode() == PPC::SELECT_I8) { 11563 SmallVector<MachineOperand, 2> Cond; 11564 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11565 MI.getOpcode() == PPC::SELECT_CC_I8) 11566 Cond.push_back(MI.getOperand(4)); 11567 else 11568 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11569 Cond.push_back(MI.getOperand(1)); 11570 11571 DebugLoc dl = MI.getDebugLoc(); 11572 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11573 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11574 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11575 MI.getOpcode() == PPC::SELECT_CC_F8 || 11576 MI.getOpcode() == PPC::SELECT_CC_F16 || 11577 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11578 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11579 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11580 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11581 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11582 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11583 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11584 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11585 MI.getOpcode() == PPC::SELECT_CC_SPE || 11586 MI.getOpcode() == PPC::SELECT_F4 || 11587 MI.getOpcode() == PPC::SELECT_F8 || 11588 MI.getOpcode() == PPC::SELECT_F16 || 11589 MI.getOpcode() == PPC::SELECT_QFRC || 11590 MI.getOpcode() == PPC::SELECT_QSRC || 11591 MI.getOpcode() == PPC::SELECT_QBRC || 11592 MI.getOpcode() == PPC::SELECT_SPE || 11593 MI.getOpcode() == PPC::SELECT_SPE4 || 11594 MI.getOpcode() == PPC::SELECT_VRRC || 11595 MI.getOpcode() == PPC::SELECT_VSFRC || 11596 MI.getOpcode() == PPC::SELECT_VSSRC || 11597 MI.getOpcode() == PPC::SELECT_VSRC) { 11598 // The incoming instruction knows the destination vreg to set, the 11599 // condition code register to branch on, the true/false values to 11600 // select between, and a branch opcode to use. 11601 11602 // thisMBB: 11603 // ... 11604 // TrueVal = ... 11605 // cmpTY ccX, r1, r2 11606 // bCC copy1MBB 11607 // fallthrough --> copy0MBB 11608 MachineBasicBlock *thisMBB = BB; 11609 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11610 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11611 DebugLoc dl = MI.getDebugLoc(); 11612 F->insert(It, copy0MBB); 11613 F->insert(It, sinkMBB); 11614 11615 // Transfer the remainder of BB and its successor edges to sinkMBB. 11616 sinkMBB->splice(sinkMBB->begin(), BB, 11617 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11618 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11619 11620 // Next, add the true and fallthrough blocks as its successors. 11621 BB->addSuccessor(copy0MBB); 11622 BB->addSuccessor(sinkMBB); 11623 11624 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11625 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11626 MI.getOpcode() == PPC::SELECT_F16 || 11627 MI.getOpcode() == PPC::SELECT_SPE4 || 11628 MI.getOpcode() == PPC::SELECT_SPE || 11629 MI.getOpcode() == PPC::SELECT_QFRC || 11630 MI.getOpcode() == PPC::SELECT_QSRC || 11631 MI.getOpcode() == PPC::SELECT_QBRC || 11632 MI.getOpcode() == PPC::SELECT_VRRC || 11633 MI.getOpcode() == PPC::SELECT_VSFRC || 11634 MI.getOpcode() == PPC::SELECT_VSSRC || 11635 MI.getOpcode() == PPC::SELECT_VSRC) { 11636 BuildMI(BB, dl, TII->get(PPC::BC)) 11637 .addReg(MI.getOperand(1).getReg()) 11638 .addMBB(sinkMBB); 11639 } else { 11640 unsigned SelectPred = MI.getOperand(4).getImm(); 11641 BuildMI(BB, dl, TII->get(PPC::BCC)) 11642 .addImm(SelectPred) 11643 .addReg(MI.getOperand(1).getReg()) 11644 .addMBB(sinkMBB); 11645 } 11646 11647 // copy0MBB: 11648 // %FalseValue = ... 11649 // # fallthrough to sinkMBB 11650 BB = copy0MBB; 11651 11652 // Update machine-CFG edges 11653 BB->addSuccessor(sinkMBB); 11654 11655 // sinkMBB: 11656 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11657 // ... 11658 BB = sinkMBB; 11659 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11660 .addReg(MI.getOperand(3).getReg()) 11661 .addMBB(copy0MBB) 11662 .addReg(MI.getOperand(2).getReg()) 11663 .addMBB(thisMBB); 11664 } else if (MI.getOpcode() == PPC::ReadTB) { 11665 // To read the 64-bit time-base register on a 32-bit target, we read the 11666 // two halves. Should the counter have wrapped while it was being read, we 11667 // need to try again. 11668 // ... 11669 // readLoop: 11670 // mfspr Rx,TBU # load from TBU 11671 // mfspr Ry,TB # load from TB 11672 // mfspr Rz,TBU # load from TBU 11673 // cmpw crX,Rx,Rz # check if 'old'='new' 11674 // bne readLoop # branch if they're not equal 11675 // ... 11676 11677 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11678 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11679 DebugLoc dl = MI.getDebugLoc(); 11680 F->insert(It, readMBB); 11681 F->insert(It, sinkMBB); 11682 11683 // Transfer the remainder of BB and its successor edges to sinkMBB. 11684 sinkMBB->splice(sinkMBB->begin(), BB, 11685 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11686 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11687 11688 BB->addSuccessor(readMBB); 11689 BB = readMBB; 11690 11691 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11692 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11693 Register LoReg = MI.getOperand(0).getReg(); 11694 Register HiReg = MI.getOperand(1).getReg(); 11695 11696 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11697 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11698 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11699 11700 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11701 11702 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11703 .addReg(HiReg) 11704 .addReg(ReadAgainReg); 11705 BuildMI(BB, dl, TII->get(PPC::BCC)) 11706 .addImm(PPC::PRED_NE) 11707 .addReg(CmpReg) 11708 .addMBB(readMBB); 11709 11710 BB->addSuccessor(readMBB); 11711 BB->addSuccessor(sinkMBB); 11712 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11713 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11714 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11715 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11716 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11717 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11718 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11719 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11720 11721 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11722 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11723 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11724 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11725 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11726 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11727 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11728 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11729 11730 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11731 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11732 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11733 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11734 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11735 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11736 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11737 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11738 11739 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11740 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11741 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11742 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11743 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11744 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11745 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11746 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11747 11748 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11749 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11750 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11751 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11752 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11753 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11754 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11755 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11756 11757 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11758 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11759 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11760 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11761 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11762 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11763 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11764 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11765 11766 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11767 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11768 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11769 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11770 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11771 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11772 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11773 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11774 11775 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11776 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11777 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11778 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11779 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11780 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11781 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11782 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11783 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11785 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11787 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11789 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11790 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11791 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11792 11793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11794 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11796 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11798 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11799 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11800 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11801 11802 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11803 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11804 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11805 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11806 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11807 BB = EmitAtomicBinary(MI, BB, 4, 0); 11808 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11809 BB = EmitAtomicBinary(MI, BB, 8, 0); 11810 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11811 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11812 (Subtarget.hasPartwordAtomics() && 11813 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11814 (Subtarget.hasPartwordAtomics() && 11815 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11816 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11817 11818 auto LoadMnemonic = PPC::LDARX; 11819 auto StoreMnemonic = PPC::STDCX; 11820 switch (MI.getOpcode()) { 11821 default: 11822 llvm_unreachable("Compare and swap of unknown size"); 11823 case PPC::ATOMIC_CMP_SWAP_I8: 11824 LoadMnemonic = PPC::LBARX; 11825 StoreMnemonic = PPC::STBCX; 11826 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11827 break; 11828 case PPC::ATOMIC_CMP_SWAP_I16: 11829 LoadMnemonic = PPC::LHARX; 11830 StoreMnemonic = PPC::STHCX; 11831 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11832 break; 11833 case PPC::ATOMIC_CMP_SWAP_I32: 11834 LoadMnemonic = PPC::LWARX; 11835 StoreMnemonic = PPC::STWCX; 11836 break; 11837 case PPC::ATOMIC_CMP_SWAP_I64: 11838 LoadMnemonic = PPC::LDARX; 11839 StoreMnemonic = PPC::STDCX; 11840 break; 11841 } 11842 Register dest = MI.getOperand(0).getReg(); 11843 Register ptrA = MI.getOperand(1).getReg(); 11844 Register ptrB = MI.getOperand(2).getReg(); 11845 Register oldval = MI.getOperand(3).getReg(); 11846 Register newval = MI.getOperand(4).getReg(); 11847 DebugLoc dl = MI.getDebugLoc(); 11848 11849 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11850 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11851 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11852 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11853 F->insert(It, loop1MBB); 11854 F->insert(It, loop2MBB); 11855 F->insert(It, midMBB); 11856 F->insert(It, exitMBB); 11857 exitMBB->splice(exitMBB->begin(), BB, 11858 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11859 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11860 11861 // thisMBB: 11862 // ... 11863 // fallthrough --> loopMBB 11864 BB->addSuccessor(loop1MBB); 11865 11866 // loop1MBB: 11867 // l[bhwd]arx dest, ptr 11868 // cmp[wd] dest, oldval 11869 // bne- midMBB 11870 // loop2MBB: 11871 // st[bhwd]cx. newval, ptr 11872 // bne- loopMBB 11873 // b exitBB 11874 // midMBB: 11875 // st[bhwd]cx. dest, ptr 11876 // exitBB: 11877 BB = loop1MBB; 11878 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11879 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11880 .addReg(oldval) 11881 .addReg(dest); 11882 BuildMI(BB, dl, TII->get(PPC::BCC)) 11883 .addImm(PPC::PRED_NE) 11884 .addReg(PPC::CR0) 11885 .addMBB(midMBB); 11886 BB->addSuccessor(loop2MBB); 11887 BB->addSuccessor(midMBB); 11888 11889 BB = loop2MBB; 11890 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11891 .addReg(newval) 11892 .addReg(ptrA) 11893 .addReg(ptrB); 11894 BuildMI(BB, dl, TII->get(PPC::BCC)) 11895 .addImm(PPC::PRED_NE) 11896 .addReg(PPC::CR0) 11897 .addMBB(loop1MBB); 11898 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11899 BB->addSuccessor(loop1MBB); 11900 BB->addSuccessor(exitMBB); 11901 11902 BB = midMBB; 11903 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11904 .addReg(dest) 11905 .addReg(ptrA) 11906 .addReg(ptrB); 11907 BB->addSuccessor(exitMBB); 11908 11909 // exitMBB: 11910 // ... 11911 BB = exitMBB; 11912 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11913 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11914 // We must use 64-bit registers for addresses when targeting 64-bit, 11915 // since we're actually doing arithmetic on them. Other registers 11916 // can be 32-bit. 11917 bool is64bit = Subtarget.isPPC64(); 11918 bool isLittleEndian = Subtarget.isLittleEndian(); 11919 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11920 11921 Register dest = MI.getOperand(0).getReg(); 11922 Register ptrA = MI.getOperand(1).getReg(); 11923 Register ptrB = MI.getOperand(2).getReg(); 11924 Register oldval = MI.getOperand(3).getReg(); 11925 Register newval = MI.getOperand(4).getReg(); 11926 DebugLoc dl = MI.getDebugLoc(); 11927 11928 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11929 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11930 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11931 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11932 F->insert(It, loop1MBB); 11933 F->insert(It, loop2MBB); 11934 F->insert(It, midMBB); 11935 F->insert(It, exitMBB); 11936 exitMBB->splice(exitMBB->begin(), BB, 11937 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11938 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11939 11940 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11941 const TargetRegisterClass *RC = 11942 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11943 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11944 11945 Register PtrReg = RegInfo.createVirtualRegister(RC); 11946 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11947 Register ShiftReg = 11948 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11949 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11950 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11951 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11952 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11953 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11954 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11955 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11956 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11957 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11958 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11959 Register Ptr1Reg; 11960 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11961 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11962 // thisMBB: 11963 // ... 11964 // fallthrough --> loopMBB 11965 BB->addSuccessor(loop1MBB); 11966 11967 // The 4-byte load must be aligned, while a char or short may be 11968 // anywhere in the word. Hence all this nasty bookkeeping code. 11969 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11970 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11971 // xori shift, shift1, 24 [16] 11972 // rlwinm ptr, ptr1, 0, 0, 29 11973 // slw newval2, newval, shift 11974 // slw oldval2, oldval,shift 11975 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11976 // slw mask, mask2, shift 11977 // and newval3, newval2, mask 11978 // and oldval3, oldval2, mask 11979 // loop1MBB: 11980 // lwarx tmpDest, ptr 11981 // and tmp, tmpDest, mask 11982 // cmpw tmp, oldval3 11983 // bne- midMBB 11984 // loop2MBB: 11985 // andc tmp2, tmpDest, mask 11986 // or tmp4, tmp2, newval3 11987 // stwcx. tmp4, ptr 11988 // bne- loop1MBB 11989 // b exitBB 11990 // midMBB: 11991 // stwcx. tmpDest, ptr 11992 // exitBB: 11993 // srw dest, tmpDest, shift 11994 if (ptrA != ZeroReg) { 11995 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11996 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11997 .addReg(ptrA) 11998 .addReg(ptrB); 11999 } else { 12000 Ptr1Reg = ptrB; 12001 } 12002 12003 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12004 // mode. 12005 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12006 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12007 .addImm(3) 12008 .addImm(27) 12009 .addImm(is8bit ? 28 : 27); 12010 if (!isLittleEndian) 12011 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12012 .addReg(Shift1Reg) 12013 .addImm(is8bit ? 24 : 16); 12014 if (is64bit) 12015 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12016 .addReg(Ptr1Reg) 12017 .addImm(0) 12018 .addImm(61); 12019 else 12020 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12021 .addReg(Ptr1Reg) 12022 .addImm(0) 12023 .addImm(0) 12024 .addImm(29); 12025 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12026 .addReg(newval) 12027 .addReg(ShiftReg); 12028 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12029 .addReg(oldval) 12030 .addReg(ShiftReg); 12031 if (is8bit) 12032 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12033 else { 12034 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12035 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12036 .addReg(Mask3Reg) 12037 .addImm(65535); 12038 } 12039 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12040 .addReg(Mask2Reg) 12041 .addReg(ShiftReg); 12042 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12043 .addReg(NewVal2Reg) 12044 .addReg(MaskReg); 12045 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12046 .addReg(OldVal2Reg) 12047 .addReg(MaskReg); 12048 12049 BB = loop1MBB; 12050 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12051 .addReg(ZeroReg) 12052 .addReg(PtrReg); 12053 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12054 .addReg(TmpDestReg) 12055 .addReg(MaskReg); 12056 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12057 .addReg(TmpReg) 12058 .addReg(OldVal3Reg); 12059 BuildMI(BB, dl, TII->get(PPC::BCC)) 12060 .addImm(PPC::PRED_NE) 12061 .addReg(PPC::CR0) 12062 .addMBB(midMBB); 12063 BB->addSuccessor(loop2MBB); 12064 BB->addSuccessor(midMBB); 12065 12066 BB = loop2MBB; 12067 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12068 .addReg(TmpDestReg) 12069 .addReg(MaskReg); 12070 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12071 .addReg(Tmp2Reg) 12072 .addReg(NewVal3Reg); 12073 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12074 .addReg(Tmp4Reg) 12075 .addReg(ZeroReg) 12076 .addReg(PtrReg); 12077 BuildMI(BB, dl, TII->get(PPC::BCC)) 12078 .addImm(PPC::PRED_NE) 12079 .addReg(PPC::CR0) 12080 .addMBB(loop1MBB); 12081 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12082 BB->addSuccessor(loop1MBB); 12083 BB->addSuccessor(exitMBB); 12084 12085 BB = midMBB; 12086 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12087 .addReg(TmpDestReg) 12088 .addReg(ZeroReg) 12089 .addReg(PtrReg); 12090 BB->addSuccessor(exitMBB); 12091 12092 // exitMBB: 12093 // ... 12094 BB = exitMBB; 12095 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12096 .addReg(TmpReg) 12097 .addReg(ShiftReg); 12098 } else if (MI.getOpcode() == PPC::FADDrtz) { 12099 // This pseudo performs an FADD with rounding mode temporarily forced 12100 // to round-to-zero. We emit this via custom inserter since the FPSCR 12101 // is not modeled at the SelectionDAG level. 12102 Register Dest = MI.getOperand(0).getReg(); 12103 Register Src1 = MI.getOperand(1).getReg(); 12104 Register Src2 = MI.getOperand(2).getReg(); 12105 DebugLoc dl = MI.getDebugLoc(); 12106 12107 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12108 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12109 12110 // Save FPSCR value. 12111 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12112 12113 // Set rounding mode to round-to-zero. 12114 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12115 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12116 12117 // Perform addition. 12118 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12119 12120 // Restore FPSCR value. 12121 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12122 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12123 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12124 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12125 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12126 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12127 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12128 ? PPC::ANDI8_rec 12129 : PPC::ANDI_rec; 12130 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12131 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12132 12133 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12134 Register Dest = RegInfo.createVirtualRegister( 12135 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12136 12137 DebugLoc Dl = MI.getDebugLoc(); 12138 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12139 .addReg(MI.getOperand(1).getReg()) 12140 .addImm(1); 12141 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12142 MI.getOperand(0).getReg()) 12143 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12144 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12145 DebugLoc Dl = MI.getDebugLoc(); 12146 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12147 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12148 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12149 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12150 MI.getOperand(0).getReg()) 12151 .addReg(CRReg); 12152 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12153 DebugLoc Dl = MI.getDebugLoc(); 12154 unsigned Imm = MI.getOperand(1).getImm(); 12155 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12156 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12157 MI.getOperand(0).getReg()) 12158 .addReg(PPC::CR0EQ); 12159 } else if (MI.getOpcode() == PPC::SETRNDi) { 12160 DebugLoc dl = MI.getDebugLoc(); 12161 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12162 12163 // Save FPSCR value. 12164 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12165 12166 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12167 // the following settings: 12168 // 00 Round to nearest 12169 // 01 Round to 0 12170 // 10 Round to +inf 12171 // 11 Round to -inf 12172 12173 // When the operand is immediate, using the two least significant bits of 12174 // the immediate to set the bits 62:63 of FPSCR. 12175 unsigned Mode = MI.getOperand(1).getImm(); 12176 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12177 .addImm(31); 12178 12179 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12180 .addImm(30); 12181 } else if (MI.getOpcode() == PPC::SETRND) { 12182 DebugLoc dl = MI.getDebugLoc(); 12183 12184 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12185 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12186 // If the target doesn't have DirectMove, we should use stack to do the 12187 // conversion, because the target doesn't have the instructions like mtvsrd 12188 // or mfvsrd to do this conversion directly. 12189 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12190 if (Subtarget.hasDirectMove()) { 12191 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12192 .addReg(SrcReg); 12193 } else { 12194 // Use stack to do the register copy. 12195 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12196 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12197 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12198 if (RC == &PPC::F8RCRegClass) { 12199 // Copy register from F8RCRegClass to G8RCRegclass. 12200 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12201 "Unsupported RegClass."); 12202 12203 StoreOp = PPC::STFD; 12204 LoadOp = PPC::LD; 12205 } else { 12206 // Copy register from G8RCRegClass to F8RCRegclass. 12207 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12208 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12209 "Unsupported RegClass."); 12210 } 12211 12212 MachineFrameInfo &MFI = F->getFrameInfo(); 12213 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12214 12215 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12216 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12217 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12218 MFI.getObjectAlign(FrameIdx)); 12219 12220 // Store the SrcReg into the stack. 12221 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12222 .addReg(SrcReg) 12223 .addImm(0) 12224 .addFrameIndex(FrameIdx) 12225 .addMemOperand(MMOStore); 12226 12227 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12228 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12229 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12230 MFI.getObjectAlign(FrameIdx)); 12231 12232 // Load from the stack where SrcReg is stored, and save to DestReg, 12233 // so we have done the RegClass conversion from RegClass::SrcReg to 12234 // RegClass::DestReg. 12235 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12236 .addImm(0) 12237 .addFrameIndex(FrameIdx) 12238 .addMemOperand(MMOLoad); 12239 } 12240 }; 12241 12242 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12243 12244 // Save FPSCR value. 12245 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12246 12247 // When the operand is gprc register, use two least significant bits of the 12248 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12249 // 12250 // copy OldFPSCRTmpReg, OldFPSCRReg 12251 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12252 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12253 // copy NewFPSCRReg, NewFPSCRTmpReg 12254 // mtfsf 255, NewFPSCRReg 12255 MachineOperand SrcOp = MI.getOperand(1); 12256 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12257 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12258 12259 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12260 12261 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12262 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12263 12264 // The first operand of INSERT_SUBREG should be a register which has 12265 // subregisters, we only care about its RegClass, so we should use an 12266 // IMPLICIT_DEF register. 12267 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12268 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12269 .addReg(ImDefReg) 12270 .add(SrcOp) 12271 .addImm(1); 12272 12273 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12274 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12275 .addReg(OldFPSCRTmpReg) 12276 .addReg(ExtSrcReg) 12277 .addImm(0) 12278 .addImm(62); 12279 12280 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12281 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12282 12283 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12284 // bits of FPSCR. 12285 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12286 .addImm(255) 12287 .addReg(NewFPSCRReg) 12288 .addImm(0) 12289 .addImm(0); 12290 } else { 12291 llvm_unreachable("Unexpected instr type to insert"); 12292 } 12293 12294 MI.eraseFromParent(); // The pseudo instruction is gone now. 12295 return BB; 12296 } 12297 12298 //===----------------------------------------------------------------------===// 12299 // Target Optimization Hooks 12300 //===----------------------------------------------------------------------===// 12301 12302 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12303 // For the estimates, convergence is quadratic, so we essentially double the 12304 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12305 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12306 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12307 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12308 if (VT.getScalarType() == MVT::f64) 12309 RefinementSteps++; 12310 return RefinementSteps; 12311 } 12312 12313 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12314 int Enabled, int &RefinementSteps, 12315 bool &UseOneConstNR, 12316 bool Reciprocal) const { 12317 EVT VT = Operand.getValueType(); 12318 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12319 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12320 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12321 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12322 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12323 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12324 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12325 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12326 12327 // The Newton-Raphson computation with a single constant does not provide 12328 // enough accuracy on some CPUs. 12329 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12330 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12331 } 12332 return SDValue(); 12333 } 12334 12335 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12336 int Enabled, 12337 int &RefinementSteps) const { 12338 EVT VT = Operand.getValueType(); 12339 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12340 (VT == MVT::f64 && Subtarget.hasFRE()) || 12341 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12342 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12343 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12344 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12345 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12346 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12347 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12348 } 12349 return SDValue(); 12350 } 12351 12352 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12353 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12354 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12355 // enabled for division), this functionality is redundant with the default 12356 // combiner logic (once the division -> reciprocal/multiply transformation 12357 // has taken place). As a result, this matters more for older cores than for 12358 // newer ones. 12359 12360 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12361 // reciprocal if there are two or more FDIVs (for embedded cores with only 12362 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12363 switch (Subtarget.getCPUDirective()) { 12364 default: 12365 return 3; 12366 case PPC::DIR_440: 12367 case PPC::DIR_A2: 12368 case PPC::DIR_E500: 12369 case PPC::DIR_E500mc: 12370 case PPC::DIR_E5500: 12371 return 2; 12372 } 12373 } 12374 12375 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12376 // collapsed, and so we need to look through chains of them. 12377 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12378 int64_t& Offset, SelectionDAG &DAG) { 12379 if (DAG.isBaseWithConstantOffset(Loc)) { 12380 Base = Loc.getOperand(0); 12381 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12382 12383 // The base might itself be a base plus an offset, and if so, accumulate 12384 // that as well. 12385 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12386 } 12387 } 12388 12389 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12390 unsigned Bytes, int Dist, 12391 SelectionDAG &DAG) { 12392 if (VT.getSizeInBits() / 8 != Bytes) 12393 return false; 12394 12395 SDValue BaseLoc = Base->getBasePtr(); 12396 if (Loc.getOpcode() == ISD::FrameIndex) { 12397 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12398 return false; 12399 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12400 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12401 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12402 int FS = MFI.getObjectSize(FI); 12403 int BFS = MFI.getObjectSize(BFI); 12404 if (FS != BFS || FS != (int)Bytes) return false; 12405 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12406 } 12407 12408 SDValue Base1 = Loc, Base2 = BaseLoc; 12409 int64_t Offset1 = 0, Offset2 = 0; 12410 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12411 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12412 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12413 return true; 12414 12415 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12416 const GlobalValue *GV1 = nullptr; 12417 const GlobalValue *GV2 = nullptr; 12418 Offset1 = 0; 12419 Offset2 = 0; 12420 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12421 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12422 if (isGA1 && isGA2 && GV1 == GV2) 12423 return Offset1 == (Offset2 + Dist*Bytes); 12424 return false; 12425 } 12426 12427 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12428 // not enforce equality of the chain operands. 12429 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12430 unsigned Bytes, int Dist, 12431 SelectionDAG &DAG) { 12432 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12433 EVT VT = LS->getMemoryVT(); 12434 SDValue Loc = LS->getBasePtr(); 12435 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12436 } 12437 12438 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12439 EVT VT; 12440 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12441 default: return false; 12442 case Intrinsic::ppc_qpx_qvlfd: 12443 case Intrinsic::ppc_qpx_qvlfda: 12444 VT = MVT::v4f64; 12445 break; 12446 case Intrinsic::ppc_qpx_qvlfs: 12447 case Intrinsic::ppc_qpx_qvlfsa: 12448 VT = MVT::v4f32; 12449 break; 12450 case Intrinsic::ppc_qpx_qvlfcd: 12451 case Intrinsic::ppc_qpx_qvlfcda: 12452 VT = MVT::v2f64; 12453 break; 12454 case Intrinsic::ppc_qpx_qvlfcs: 12455 case Intrinsic::ppc_qpx_qvlfcsa: 12456 VT = MVT::v2f32; 12457 break; 12458 case Intrinsic::ppc_qpx_qvlfiwa: 12459 case Intrinsic::ppc_qpx_qvlfiwz: 12460 case Intrinsic::ppc_altivec_lvx: 12461 case Intrinsic::ppc_altivec_lvxl: 12462 case Intrinsic::ppc_vsx_lxvw4x: 12463 case Intrinsic::ppc_vsx_lxvw4x_be: 12464 VT = MVT::v4i32; 12465 break; 12466 case Intrinsic::ppc_vsx_lxvd2x: 12467 case Intrinsic::ppc_vsx_lxvd2x_be: 12468 VT = MVT::v2f64; 12469 break; 12470 case Intrinsic::ppc_altivec_lvebx: 12471 VT = MVT::i8; 12472 break; 12473 case Intrinsic::ppc_altivec_lvehx: 12474 VT = MVT::i16; 12475 break; 12476 case Intrinsic::ppc_altivec_lvewx: 12477 VT = MVT::i32; 12478 break; 12479 } 12480 12481 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12482 } 12483 12484 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12485 EVT VT; 12486 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12487 default: return false; 12488 case Intrinsic::ppc_qpx_qvstfd: 12489 case Intrinsic::ppc_qpx_qvstfda: 12490 VT = MVT::v4f64; 12491 break; 12492 case Intrinsic::ppc_qpx_qvstfs: 12493 case Intrinsic::ppc_qpx_qvstfsa: 12494 VT = MVT::v4f32; 12495 break; 12496 case Intrinsic::ppc_qpx_qvstfcd: 12497 case Intrinsic::ppc_qpx_qvstfcda: 12498 VT = MVT::v2f64; 12499 break; 12500 case Intrinsic::ppc_qpx_qvstfcs: 12501 case Intrinsic::ppc_qpx_qvstfcsa: 12502 VT = MVT::v2f32; 12503 break; 12504 case Intrinsic::ppc_qpx_qvstfiw: 12505 case Intrinsic::ppc_qpx_qvstfiwa: 12506 case Intrinsic::ppc_altivec_stvx: 12507 case Intrinsic::ppc_altivec_stvxl: 12508 case Intrinsic::ppc_vsx_stxvw4x: 12509 VT = MVT::v4i32; 12510 break; 12511 case Intrinsic::ppc_vsx_stxvd2x: 12512 VT = MVT::v2f64; 12513 break; 12514 case Intrinsic::ppc_vsx_stxvw4x_be: 12515 VT = MVT::v4i32; 12516 break; 12517 case Intrinsic::ppc_vsx_stxvd2x_be: 12518 VT = MVT::v2f64; 12519 break; 12520 case Intrinsic::ppc_altivec_stvebx: 12521 VT = MVT::i8; 12522 break; 12523 case Intrinsic::ppc_altivec_stvehx: 12524 VT = MVT::i16; 12525 break; 12526 case Intrinsic::ppc_altivec_stvewx: 12527 VT = MVT::i32; 12528 break; 12529 } 12530 12531 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12532 } 12533 12534 return false; 12535 } 12536 12537 // Return true is there is a nearyby consecutive load to the one provided 12538 // (regardless of alignment). We search up and down the chain, looking though 12539 // token factors and other loads (but nothing else). As a result, a true result 12540 // indicates that it is safe to create a new consecutive load adjacent to the 12541 // load provided. 12542 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12543 SDValue Chain = LD->getChain(); 12544 EVT VT = LD->getMemoryVT(); 12545 12546 SmallSet<SDNode *, 16> LoadRoots; 12547 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12548 SmallSet<SDNode *, 16> Visited; 12549 12550 // First, search up the chain, branching to follow all token-factor operands. 12551 // If we find a consecutive load, then we're done, otherwise, record all 12552 // nodes just above the top-level loads and token factors. 12553 while (!Queue.empty()) { 12554 SDNode *ChainNext = Queue.pop_back_val(); 12555 if (!Visited.insert(ChainNext).second) 12556 continue; 12557 12558 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12559 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12560 return true; 12561 12562 if (!Visited.count(ChainLD->getChain().getNode())) 12563 Queue.push_back(ChainLD->getChain().getNode()); 12564 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12565 for (const SDUse &O : ChainNext->ops()) 12566 if (!Visited.count(O.getNode())) 12567 Queue.push_back(O.getNode()); 12568 } else 12569 LoadRoots.insert(ChainNext); 12570 } 12571 12572 // Second, search down the chain, starting from the top-level nodes recorded 12573 // in the first phase. These top-level nodes are the nodes just above all 12574 // loads and token factors. Starting with their uses, recursively look though 12575 // all loads (just the chain uses) and token factors to find a consecutive 12576 // load. 12577 Visited.clear(); 12578 Queue.clear(); 12579 12580 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12581 IE = LoadRoots.end(); I != IE; ++I) { 12582 Queue.push_back(*I); 12583 12584 while (!Queue.empty()) { 12585 SDNode *LoadRoot = Queue.pop_back_val(); 12586 if (!Visited.insert(LoadRoot).second) 12587 continue; 12588 12589 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12590 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12591 return true; 12592 12593 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12594 UE = LoadRoot->use_end(); UI != UE; ++UI) 12595 if (((isa<MemSDNode>(*UI) && 12596 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12597 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12598 Queue.push_back(*UI); 12599 } 12600 } 12601 12602 return false; 12603 } 12604 12605 /// This function is called when we have proved that a SETCC node can be replaced 12606 /// by subtraction (and other supporting instructions) so that the result of 12607 /// comparison is kept in a GPR instead of CR. This function is purely for 12608 /// codegen purposes and has some flags to guide the codegen process. 12609 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12610 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12611 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12612 12613 // Zero extend the operands to the largest legal integer. Originally, they 12614 // must be of a strictly smaller size. 12615 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12616 DAG.getConstant(Size, DL, MVT::i32)); 12617 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12618 DAG.getConstant(Size, DL, MVT::i32)); 12619 12620 // Swap if needed. Depends on the condition code. 12621 if (Swap) 12622 std::swap(Op0, Op1); 12623 12624 // Subtract extended integers. 12625 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12626 12627 // Move the sign bit to the least significant position and zero out the rest. 12628 // Now the least significant bit carries the result of original comparison. 12629 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12630 DAG.getConstant(Size - 1, DL, MVT::i32)); 12631 auto Final = Shifted; 12632 12633 // Complement the result if needed. Based on the condition code. 12634 if (Complement) 12635 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12636 DAG.getConstant(1, DL, MVT::i64)); 12637 12638 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12639 } 12640 12641 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12642 DAGCombinerInfo &DCI) const { 12643 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12644 12645 SelectionDAG &DAG = DCI.DAG; 12646 SDLoc DL(N); 12647 12648 // Size of integers being compared has a critical role in the following 12649 // analysis, so we prefer to do this when all types are legal. 12650 if (!DCI.isAfterLegalizeDAG()) 12651 return SDValue(); 12652 12653 // If all users of SETCC extend its value to a legal integer type 12654 // then we replace SETCC with a subtraction 12655 for (SDNode::use_iterator UI = N->use_begin(), 12656 UE = N->use_end(); UI != UE; ++UI) { 12657 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12658 return SDValue(); 12659 } 12660 12661 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12662 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12663 12664 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12665 12666 if (OpSize < Size) { 12667 switch (CC) { 12668 default: break; 12669 case ISD::SETULT: 12670 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12671 case ISD::SETULE: 12672 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12673 case ISD::SETUGT: 12674 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12675 case ISD::SETUGE: 12676 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12677 } 12678 } 12679 12680 return SDValue(); 12681 } 12682 12683 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12684 DAGCombinerInfo &DCI) const { 12685 SelectionDAG &DAG = DCI.DAG; 12686 SDLoc dl(N); 12687 12688 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12689 // If we're tracking CR bits, we need to be careful that we don't have: 12690 // trunc(binary-ops(zext(x), zext(y))) 12691 // or 12692 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12693 // such that we're unnecessarily moving things into GPRs when it would be 12694 // better to keep them in CR bits. 12695 12696 // Note that trunc here can be an actual i1 trunc, or can be the effective 12697 // truncation that comes from a setcc or select_cc. 12698 if (N->getOpcode() == ISD::TRUNCATE && 12699 N->getValueType(0) != MVT::i1) 12700 return SDValue(); 12701 12702 if (N->getOperand(0).getValueType() != MVT::i32 && 12703 N->getOperand(0).getValueType() != MVT::i64) 12704 return SDValue(); 12705 12706 if (N->getOpcode() == ISD::SETCC || 12707 N->getOpcode() == ISD::SELECT_CC) { 12708 // If we're looking at a comparison, then we need to make sure that the 12709 // high bits (all except for the first) don't matter the result. 12710 ISD::CondCode CC = 12711 cast<CondCodeSDNode>(N->getOperand( 12712 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12713 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12714 12715 if (ISD::isSignedIntSetCC(CC)) { 12716 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12717 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12718 return SDValue(); 12719 } else if (ISD::isUnsignedIntSetCC(CC)) { 12720 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12721 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12722 !DAG.MaskedValueIsZero(N->getOperand(1), 12723 APInt::getHighBitsSet(OpBits, OpBits-1))) 12724 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12725 : SDValue()); 12726 } else { 12727 // This is neither a signed nor an unsigned comparison, just make sure 12728 // that the high bits are equal. 12729 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12730 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12731 12732 // We don't really care about what is known about the first bit (if 12733 // anything), so clear it in all masks prior to comparing them. 12734 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12735 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12736 12737 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12738 return SDValue(); 12739 } 12740 } 12741 12742 // We now know that the higher-order bits are irrelevant, we just need to 12743 // make sure that all of the intermediate operations are bit operations, and 12744 // all inputs are extensions. 12745 if (N->getOperand(0).getOpcode() != ISD::AND && 12746 N->getOperand(0).getOpcode() != ISD::OR && 12747 N->getOperand(0).getOpcode() != ISD::XOR && 12748 N->getOperand(0).getOpcode() != ISD::SELECT && 12749 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12750 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12751 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12752 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12753 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12754 return SDValue(); 12755 12756 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12757 N->getOperand(1).getOpcode() != ISD::AND && 12758 N->getOperand(1).getOpcode() != ISD::OR && 12759 N->getOperand(1).getOpcode() != ISD::XOR && 12760 N->getOperand(1).getOpcode() != ISD::SELECT && 12761 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12762 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12763 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12764 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12765 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12766 return SDValue(); 12767 12768 SmallVector<SDValue, 4> Inputs; 12769 SmallVector<SDValue, 8> BinOps, PromOps; 12770 SmallPtrSet<SDNode *, 16> Visited; 12771 12772 for (unsigned i = 0; i < 2; ++i) { 12773 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12774 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12775 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12776 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12777 isa<ConstantSDNode>(N->getOperand(i))) 12778 Inputs.push_back(N->getOperand(i)); 12779 else 12780 BinOps.push_back(N->getOperand(i)); 12781 12782 if (N->getOpcode() == ISD::TRUNCATE) 12783 break; 12784 } 12785 12786 // Visit all inputs, collect all binary operations (and, or, xor and 12787 // select) that are all fed by extensions. 12788 while (!BinOps.empty()) { 12789 SDValue BinOp = BinOps.back(); 12790 BinOps.pop_back(); 12791 12792 if (!Visited.insert(BinOp.getNode()).second) 12793 continue; 12794 12795 PromOps.push_back(BinOp); 12796 12797 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12798 // The condition of the select is not promoted. 12799 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12800 continue; 12801 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12802 continue; 12803 12804 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12805 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12806 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12807 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12808 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12809 Inputs.push_back(BinOp.getOperand(i)); 12810 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12811 BinOp.getOperand(i).getOpcode() == ISD::OR || 12812 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12813 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12814 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12815 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12816 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12817 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12818 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12819 BinOps.push_back(BinOp.getOperand(i)); 12820 } else { 12821 // We have an input that is not an extension or another binary 12822 // operation; we'll abort this transformation. 12823 return SDValue(); 12824 } 12825 } 12826 } 12827 12828 // Make sure that this is a self-contained cluster of operations (which 12829 // is not quite the same thing as saying that everything has only one 12830 // use). 12831 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12832 if (isa<ConstantSDNode>(Inputs[i])) 12833 continue; 12834 12835 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12836 UE = Inputs[i].getNode()->use_end(); 12837 UI != UE; ++UI) { 12838 SDNode *User = *UI; 12839 if (User != N && !Visited.count(User)) 12840 return SDValue(); 12841 12842 // Make sure that we're not going to promote the non-output-value 12843 // operand(s) or SELECT or SELECT_CC. 12844 // FIXME: Although we could sometimes handle this, and it does occur in 12845 // practice that one of the condition inputs to the select is also one of 12846 // the outputs, we currently can't deal with this. 12847 if (User->getOpcode() == ISD::SELECT) { 12848 if (User->getOperand(0) == Inputs[i]) 12849 return SDValue(); 12850 } else if (User->getOpcode() == ISD::SELECT_CC) { 12851 if (User->getOperand(0) == Inputs[i] || 12852 User->getOperand(1) == Inputs[i]) 12853 return SDValue(); 12854 } 12855 } 12856 } 12857 12858 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12859 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12860 UE = PromOps[i].getNode()->use_end(); 12861 UI != UE; ++UI) { 12862 SDNode *User = *UI; 12863 if (User != N && !Visited.count(User)) 12864 return SDValue(); 12865 12866 // Make sure that we're not going to promote the non-output-value 12867 // operand(s) or SELECT or SELECT_CC. 12868 // FIXME: Although we could sometimes handle this, and it does occur in 12869 // practice that one of the condition inputs to the select is also one of 12870 // the outputs, we currently can't deal with this. 12871 if (User->getOpcode() == ISD::SELECT) { 12872 if (User->getOperand(0) == PromOps[i]) 12873 return SDValue(); 12874 } else if (User->getOpcode() == ISD::SELECT_CC) { 12875 if (User->getOperand(0) == PromOps[i] || 12876 User->getOperand(1) == PromOps[i]) 12877 return SDValue(); 12878 } 12879 } 12880 } 12881 12882 // Replace all inputs with the extension operand. 12883 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12884 // Constants may have users outside the cluster of to-be-promoted nodes, 12885 // and so we need to replace those as we do the promotions. 12886 if (isa<ConstantSDNode>(Inputs[i])) 12887 continue; 12888 else 12889 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12890 } 12891 12892 std::list<HandleSDNode> PromOpHandles; 12893 for (auto &PromOp : PromOps) 12894 PromOpHandles.emplace_back(PromOp); 12895 12896 // Replace all operations (these are all the same, but have a different 12897 // (i1) return type). DAG.getNode will validate that the types of 12898 // a binary operator match, so go through the list in reverse so that 12899 // we've likely promoted both operands first. Any intermediate truncations or 12900 // extensions disappear. 12901 while (!PromOpHandles.empty()) { 12902 SDValue PromOp = PromOpHandles.back().getValue(); 12903 PromOpHandles.pop_back(); 12904 12905 if (PromOp.getOpcode() == ISD::TRUNCATE || 12906 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12907 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12908 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12909 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12910 PromOp.getOperand(0).getValueType() != MVT::i1) { 12911 // The operand is not yet ready (see comment below). 12912 PromOpHandles.emplace_front(PromOp); 12913 continue; 12914 } 12915 12916 SDValue RepValue = PromOp.getOperand(0); 12917 if (isa<ConstantSDNode>(RepValue)) 12918 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12919 12920 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12921 continue; 12922 } 12923 12924 unsigned C; 12925 switch (PromOp.getOpcode()) { 12926 default: C = 0; break; 12927 case ISD::SELECT: C = 1; break; 12928 case ISD::SELECT_CC: C = 2; break; 12929 } 12930 12931 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12932 PromOp.getOperand(C).getValueType() != MVT::i1) || 12933 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12934 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12935 // The to-be-promoted operands of this node have not yet been 12936 // promoted (this should be rare because we're going through the 12937 // list backward, but if one of the operands has several users in 12938 // this cluster of to-be-promoted nodes, it is possible). 12939 PromOpHandles.emplace_front(PromOp); 12940 continue; 12941 } 12942 12943 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12944 PromOp.getNode()->op_end()); 12945 12946 // If there are any constant inputs, make sure they're replaced now. 12947 for (unsigned i = 0; i < 2; ++i) 12948 if (isa<ConstantSDNode>(Ops[C+i])) 12949 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12950 12951 DAG.ReplaceAllUsesOfValueWith(PromOp, 12952 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12953 } 12954 12955 // Now we're left with the initial truncation itself. 12956 if (N->getOpcode() == ISD::TRUNCATE) 12957 return N->getOperand(0); 12958 12959 // Otherwise, this is a comparison. The operands to be compared have just 12960 // changed type (to i1), but everything else is the same. 12961 return SDValue(N, 0); 12962 } 12963 12964 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12965 DAGCombinerInfo &DCI) const { 12966 SelectionDAG &DAG = DCI.DAG; 12967 SDLoc dl(N); 12968 12969 // If we're tracking CR bits, we need to be careful that we don't have: 12970 // zext(binary-ops(trunc(x), trunc(y))) 12971 // or 12972 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12973 // such that we're unnecessarily moving things into CR bits that can more 12974 // efficiently stay in GPRs. Note that if we're not certain that the high 12975 // bits are set as required by the final extension, we still may need to do 12976 // some masking to get the proper behavior. 12977 12978 // This same functionality is important on PPC64 when dealing with 12979 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12980 // the return values of functions. Because it is so similar, it is handled 12981 // here as well. 12982 12983 if (N->getValueType(0) != MVT::i32 && 12984 N->getValueType(0) != MVT::i64) 12985 return SDValue(); 12986 12987 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12988 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12989 return SDValue(); 12990 12991 if (N->getOperand(0).getOpcode() != ISD::AND && 12992 N->getOperand(0).getOpcode() != ISD::OR && 12993 N->getOperand(0).getOpcode() != ISD::XOR && 12994 N->getOperand(0).getOpcode() != ISD::SELECT && 12995 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12996 return SDValue(); 12997 12998 SmallVector<SDValue, 4> Inputs; 12999 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13000 SmallPtrSet<SDNode *, 16> Visited; 13001 13002 // Visit all inputs, collect all binary operations (and, or, xor and 13003 // select) that are all fed by truncations. 13004 while (!BinOps.empty()) { 13005 SDValue BinOp = BinOps.back(); 13006 BinOps.pop_back(); 13007 13008 if (!Visited.insert(BinOp.getNode()).second) 13009 continue; 13010 13011 PromOps.push_back(BinOp); 13012 13013 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13014 // The condition of the select is not promoted. 13015 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13016 continue; 13017 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13018 continue; 13019 13020 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13021 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13022 Inputs.push_back(BinOp.getOperand(i)); 13023 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13024 BinOp.getOperand(i).getOpcode() == ISD::OR || 13025 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13026 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13027 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13028 BinOps.push_back(BinOp.getOperand(i)); 13029 } else { 13030 // We have an input that is not a truncation or another binary 13031 // operation; we'll abort this transformation. 13032 return SDValue(); 13033 } 13034 } 13035 } 13036 13037 // The operands of a select that must be truncated when the select is 13038 // promoted because the operand is actually part of the to-be-promoted set. 13039 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13040 13041 // Make sure that this is a self-contained cluster of operations (which 13042 // is not quite the same thing as saying that everything has only one 13043 // use). 13044 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13045 if (isa<ConstantSDNode>(Inputs[i])) 13046 continue; 13047 13048 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13049 UE = Inputs[i].getNode()->use_end(); 13050 UI != UE; ++UI) { 13051 SDNode *User = *UI; 13052 if (User != N && !Visited.count(User)) 13053 return SDValue(); 13054 13055 // If we're going to promote the non-output-value operand(s) or SELECT or 13056 // SELECT_CC, record them for truncation. 13057 if (User->getOpcode() == ISD::SELECT) { 13058 if (User->getOperand(0) == Inputs[i]) 13059 SelectTruncOp[0].insert(std::make_pair(User, 13060 User->getOperand(0).getValueType())); 13061 } else if (User->getOpcode() == ISD::SELECT_CC) { 13062 if (User->getOperand(0) == Inputs[i]) 13063 SelectTruncOp[0].insert(std::make_pair(User, 13064 User->getOperand(0).getValueType())); 13065 if (User->getOperand(1) == Inputs[i]) 13066 SelectTruncOp[1].insert(std::make_pair(User, 13067 User->getOperand(1).getValueType())); 13068 } 13069 } 13070 } 13071 13072 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13073 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13074 UE = PromOps[i].getNode()->use_end(); 13075 UI != UE; ++UI) { 13076 SDNode *User = *UI; 13077 if (User != N && !Visited.count(User)) 13078 return SDValue(); 13079 13080 // If we're going to promote the non-output-value operand(s) or SELECT or 13081 // SELECT_CC, record them for truncation. 13082 if (User->getOpcode() == ISD::SELECT) { 13083 if (User->getOperand(0) == PromOps[i]) 13084 SelectTruncOp[0].insert(std::make_pair(User, 13085 User->getOperand(0).getValueType())); 13086 } else if (User->getOpcode() == ISD::SELECT_CC) { 13087 if (User->getOperand(0) == PromOps[i]) 13088 SelectTruncOp[0].insert(std::make_pair(User, 13089 User->getOperand(0).getValueType())); 13090 if (User->getOperand(1) == PromOps[i]) 13091 SelectTruncOp[1].insert(std::make_pair(User, 13092 User->getOperand(1).getValueType())); 13093 } 13094 } 13095 } 13096 13097 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13098 bool ReallyNeedsExt = false; 13099 if (N->getOpcode() != ISD::ANY_EXTEND) { 13100 // If all of the inputs are not already sign/zero extended, then 13101 // we'll still need to do that at the end. 13102 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13103 if (isa<ConstantSDNode>(Inputs[i])) 13104 continue; 13105 13106 unsigned OpBits = 13107 Inputs[i].getOperand(0).getValueSizeInBits(); 13108 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13109 13110 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13111 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13112 APInt::getHighBitsSet(OpBits, 13113 OpBits-PromBits))) || 13114 (N->getOpcode() == ISD::SIGN_EXTEND && 13115 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13116 (OpBits-(PromBits-1)))) { 13117 ReallyNeedsExt = true; 13118 break; 13119 } 13120 } 13121 } 13122 13123 // Replace all inputs, either with the truncation operand, or a 13124 // truncation or extension to the final output type. 13125 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13126 // Constant inputs need to be replaced with the to-be-promoted nodes that 13127 // use them because they might have users outside of the cluster of 13128 // promoted nodes. 13129 if (isa<ConstantSDNode>(Inputs[i])) 13130 continue; 13131 13132 SDValue InSrc = Inputs[i].getOperand(0); 13133 if (Inputs[i].getValueType() == N->getValueType(0)) 13134 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13135 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13136 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13137 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13138 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13139 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13140 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13141 else 13142 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13143 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13144 } 13145 13146 std::list<HandleSDNode> PromOpHandles; 13147 for (auto &PromOp : PromOps) 13148 PromOpHandles.emplace_back(PromOp); 13149 13150 // Replace all operations (these are all the same, but have a different 13151 // (promoted) return type). DAG.getNode will validate that the types of 13152 // a binary operator match, so go through the list in reverse so that 13153 // we've likely promoted both operands first. 13154 while (!PromOpHandles.empty()) { 13155 SDValue PromOp = PromOpHandles.back().getValue(); 13156 PromOpHandles.pop_back(); 13157 13158 unsigned C; 13159 switch (PromOp.getOpcode()) { 13160 default: C = 0; break; 13161 case ISD::SELECT: C = 1; break; 13162 case ISD::SELECT_CC: C = 2; break; 13163 } 13164 13165 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13166 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13167 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13168 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13169 // The to-be-promoted operands of this node have not yet been 13170 // promoted (this should be rare because we're going through the 13171 // list backward, but if one of the operands has several users in 13172 // this cluster of to-be-promoted nodes, it is possible). 13173 PromOpHandles.emplace_front(PromOp); 13174 continue; 13175 } 13176 13177 // For SELECT and SELECT_CC nodes, we do a similar check for any 13178 // to-be-promoted comparison inputs. 13179 if (PromOp.getOpcode() == ISD::SELECT || 13180 PromOp.getOpcode() == ISD::SELECT_CC) { 13181 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13182 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13183 (SelectTruncOp[1].count(PromOp.getNode()) && 13184 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13185 PromOpHandles.emplace_front(PromOp); 13186 continue; 13187 } 13188 } 13189 13190 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13191 PromOp.getNode()->op_end()); 13192 13193 // If this node has constant inputs, then they'll need to be promoted here. 13194 for (unsigned i = 0; i < 2; ++i) { 13195 if (!isa<ConstantSDNode>(Ops[C+i])) 13196 continue; 13197 if (Ops[C+i].getValueType() == N->getValueType(0)) 13198 continue; 13199 13200 if (N->getOpcode() == ISD::SIGN_EXTEND) 13201 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13202 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13203 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13204 else 13205 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13206 } 13207 13208 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13209 // truncate them again to the original value type. 13210 if (PromOp.getOpcode() == ISD::SELECT || 13211 PromOp.getOpcode() == ISD::SELECT_CC) { 13212 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13213 if (SI0 != SelectTruncOp[0].end()) 13214 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13215 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13216 if (SI1 != SelectTruncOp[1].end()) 13217 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13218 } 13219 13220 DAG.ReplaceAllUsesOfValueWith(PromOp, 13221 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13222 } 13223 13224 // Now we're left with the initial extension itself. 13225 if (!ReallyNeedsExt) 13226 return N->getOperand(0); 13227 13228 // To zero extend, just mask off everything except for the first bit (in the 13229 // i1 case). 13230 if (N->getOpcode() == ISD::ZERO_EXTEND) 13231 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13232 DAG.getConstant(APInt::getLowBitsSet( 13233 N->getValueSizeInBits(0), PromBits), 13234 dl, N->getValueType(0))); 13235 13236 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13237 "Invalid extension type"); 13238 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13239 SDValue ShiftCst = 13240 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13241 return DAG.getNode( 13242 ISD::SRA, dl, N->getValueType(0), 13243 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13244 ShiftCst); 13245 } 13246 13247 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13248 DAGCombinerInfo &DCI) const { 13249 assert(N->getOpcode() == ISD::SETCC && 13250 "Should be called with a SETCC node"); 13251 13252 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13253 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13254 SDValue LHS = N->getOperand(0); 13255 SDValue RHS = N->getOperand(1); 13256 13257 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13258 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13259 LHS.hasOneUse()) 13260 std::swap(LHS, RHS); 13261 13262 // x == 0-y --> x+y == 0 13263 // x != 0-y --> x+y != 0 13264 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13265 RHS.hasOneUse()) { 13266 SDLoc DL(N); 13267 SelectionDAG &DAG = DCI.DAG; 13268 EVT VT = N->getValueType(0); 13269 EVT OpVT = LHS.getValueType(); 13270 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13271 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13272 } 13273 } 13274 13275 return DAGCombineTruncBoolExt(N, DCI); 13276 } 13277 13278 // Is this an extending load from an f32 to an f64? 13279 static bool isFPExtLoad(SDValue Op) { 13280 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13281 return LD->getExtensionType() == ISD::EXTLOAD && 13282 Op.getValueType() == MVT::f64; 13283 return false; 13284 } 13285 13286 /// Reduces the number of fp-to-int conversion when building a vector. 13287 /// 13288 /// If this vector is built out of floating to integer conversions, 13289 /// transform it to a vector built out of floating point values followed by a 13290 /// single floating to integer conversion of the vector. 13291 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13292 /// becomes (fptosi (build_vector ($A, $B, ...))) 13293 SDValue PPCTargetLowering:: 13294 combineElementTruncationToVectorTruncation(SDNode *N, 13295 DAGCombinerInfo &DCI) const { 13296 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13297 "Should be called with a BUILD_VECTOR node"); 13298 13299 SelectionDAG &DAG = DCI.DAG; 13300 SDLoc dl(N); 13301 13302 SDValue FirstInput = N->getOperand(0); 13303 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13304 "The input operand must be an fp-to-int conversion."); 13305 13306 // This combine happens after legalization so the fp_to_[su]i nodes are 13307 // already converted to PPCSISD nodes. 13308 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13309 if (FirstConversion == PPCISD::FCTIDZ || 13310 FirstConversion == PPCISD::FCTIDUZ || 13311 FirstConversion == PPCISD::FCTIWZ || 13312 FirstConversion == PPCISD::FCTIWUZ) { 13313 bool IsSplat = true; 13314 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13315 FirstConversion == PPCISD::FCTIWUZ; 13316 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13317 SmallVector<SDValue, 4> Ops; 13318 EVT TargetVT = N->getValueType(0); 13319 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13320 SDValue NextOp = N->getOperand(i); 13321 if (NextOp.getOpcode() != PPCISD::MFVSR) 13322 return SDValue(); 13323 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13324 if (NextConversion != FirstConversion) 13325 return SDValue(); 13326 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13327 // This is not valid if the input was originally double precision. It is 13328 // also not profitable to do unless this is an extending load in which 13329 // case doing this combine will allow us to combine consecutive loads. 13330 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13331 return SDValue(); 13332 if (N->getOperand(i) != FirstInput) 13333 IsSplat = false; 13334 } 13335 13336 // If this is a splat, we leave it as-is since there will be only a single 13337 // fp-to-int conversion followed by a splat of the integer. This is better 13338 // for 32-bit and smaller ints and neutral for 64-bit ints. 13339 if (IsSplat) 13340 return SDValue(); 13341 13342 // Now that we know we have the right type of node, get its operands 13343 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13344 SDValue In = N->getOperand(i).getOperand(0); 13345 if (Is32Bit) { 13346 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13347 // here, we know that all inputs are extending loads so this is safe). 13348 if (In.isUndef()) 13349 Ops.push_back(DAG.getUNDEF(SrcVT)); 13350 else { 13351 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13352 MVT::f32, In.getOperand(0), 13353 DAG.getIntPtrConstant(1, dl)); 13354 Ops.push_back(Trunc); 13355 } 13356 } else 13357 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13358 } 13359 13360 unsigned Opcode; 13361 if (FirstConversion == PPCISD::FCTIDZ || 13362 FirstConversion == PPCISD::FCTIWZ) 13363 Opcode = ISD::FP_TO_SINT; 13364 else 13365 Opcode = ISD::FP_TO_UINT; 13366 13367 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13368 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13369 return DAG.getNode(Opcode, dl, TargetVT, BV); 13370 } 13371 return SDValue(); 13372 } 13373 13374 /// Reduce the number of loads when building a vector. 13375 /// 13376 /// Building a vector out of multiple loads can be converted to a load 13377 /// of the vector type if the loads are consecutive. If the loads are 13378 /// consecutive but in descending order, a shuffle is added at the end 13379 /// to reorder the vector. 13380 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13381 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13382 "Should be called with a BUILD_VECTOR node"); 13383 13384 SDLoc dl(N); 13385 13386 // Return early for non byte-sized type, as they can't be consecutive. 13387 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13388 return SDValue(); 13389 13390 bool InputsAreConsecutiveLoads = true; 13391 bool InputsAreReverseConsecutive = true; 13392 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13393 SDValue FirstInput = N->getOperand(0); 13394 bool IsRoundOfExtLoad = false; 13395 13396 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13397 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13398 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13399 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13400 } 13401 // Not a build vector of (possibly fp_rounded) loads. 13402 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13403 N->getNumOperands() == 1) 13404 return SDValue(); 13405 13406 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13407 // If any inputs are fp_round(extload), they all must be. 13408 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13409 return SDValue(); 13410 13411 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13412 N->getOperand(i); 13413 if (NextInput.getOpcode() != ISD::LOAD) 13414 return SDValue(); 13415 13416 SDValue PreviousInput = 13417 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13418 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13419 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13420 13421 // If any inputs are fp_round(extload), they all must be. 13422 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13423 return SDValue(); 13424 13425 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13426 InputsAreConsecutiveLoads = false; 13427 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13428 InputsAreReverseConsecutive = false; 13429 13430 // Exit early if the loads are neither consecutive nor reverse consecutive. 13431 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13432 return SDValue(); 13433 } 13434 13435 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13436 "The loads cannot be both consecutive and reverse consecutive."); 13437 13438 SDValue FirstLoadOp = 13439 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13440 SDValue LastLoadOp = 13441 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13442 N->getOperand(N->getNumOperands()-1); 13443 13444 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13445 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13446 if (InputsAreConsecutiveLoads) { 13447 assert(LD1 && "Input needs to be a LoadSDNode."); 13448 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13449 LD1->getBasePtr(), LD1->getPointerInfo(), 13450 LD1->getAlignment()); 13451 } 13452 if (InputsAreReverseConsecutive) { 13453 assert(LDL && "Input needs to be a LoadSDNode."); 13454 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13455 LDL->getBasePtr(), LDL->getPointerInfo(), 13456 LDL->getAlignment()); 13457 SmallVector<int, 16> Ops; 13458 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13459 Ops.push_back(i); 13460 13461 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13462 DAG.getUNDEF(N->getValueType(0)), Ops); 13463 } 13464 return SDValue(); 13465 } 13466 13467 // This function adds the required vector_shuffle needed to get 13468 // the elements of the vector extract in the correct position 13469 // as specified by the CorrectElems encoding. 13470 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13471 SDValue Input, uint64_t Elems, 13472 uint64_t CorrectElems) { 13473 SDLoc dl(N); 13474 13475 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13476 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13477 13478 // Knowing the element indices being extracted from the original 13479 // vector and the order in which they're being inserted, just put 13480 // them at element indices required for the instruction. 13481 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13482 if (DAG.getDataLayout().isLittleEndian()) 13483 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13484 else 13485 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13486 CorrectElems = CorrectElems >> 8; 13487 Elems = Elems >> 8; 13488 } 13489 13490 SDValue Shuffle = 13491 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13492 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13493 13494 EVT VT = N->getValueType(0); 13495 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13496 13497 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13498 Input.getValueType().getVectorElementType(), 13499 VT.getVectorNumElements()); 13500 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13501 DAG.getValueType(ExtVT)); 13502 } 13503 13504 // Look for build vector patterns where input operands come from sign 13505 // extended vector_extract elements of specific indices. If the correct indices 13506 // aren't used, add a vector shuffle to fix up the indices and create 13507 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13508 // during instruction selection. 13509 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13510 // This array encodes the indices that the vector sign extend instructions 13511 // extract from when extending from one type to another for both BE and LE. 13512 // The right nibble of each byte corresponds to the LE incides. 13513 // and the left nibble of each byte corresponds to the BE incides. 13514 // For example: 0x3074B8FC byte->word 13515 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13516 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13517 // For example: 0x000070F8 byte->double word 13518 // For LE: the allowed indices are: 0x0,0x8 13519 // For BE: the allowed indices are: 0x7,0xF 13520 uint64_t TargetElems[] = { 13521 0x3074B8FC, // b->w 13522 0x000070F8, // b->d 13523 0x10325476, // h->w 13524 0x00003074, // h->d 13525 0x00001032, // w->d 13526 }; 13527 13528 uint64_t Elems = 0; 13529 int Index; 13530 SDValue Input; 13531 13532 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13533 if (!Op) 13534 return false; 13535 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13536 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13537 return false; 13538 13539 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13540 // of the right width. 13541 SDValue Extract = Op.getOperand(0); 13542 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13543 Extract = Extract.getOperand(0); 13544 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13545 return false; 13546 13547 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13548 if (!ExtOp) 13549 return false; 13550 13551 Index = ExtOp->getZExtValue(); 13552 if (Input && Input != Extract.getOperand(0)) 13553 return false; 13554 13555 if (!Input) 13556 Input = Extract.getOperand(0); 13557 13558 Elems = Elems << 8; 13559 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13560 Elems |= Index; 13561 13562 return true; 13563 }; 13564 13565 // If the build vector operands aren't sign extended vector extracts, 13566 // of the same input vector, then return. 13567 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13568 if (!isSExtOfVecExtract(N->getOperand(i))) { 13569 return SDValue(); 13570 } 13571 } 13572 13573 // If the vector extract indicies are not correct, add the appropriate 13574 // vector_shuffle. 13575 int TgtElemArrayIdx; 13576 int InputSize = Input.getValueType().getScalarSizeInBits(); 13577 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13578 if (InputSize + OutputSize == 40) 13579 TgtElemArrayIdx = 0; 13580 else if (InputSize + OutputSize == 72) 13581 TgtElemArrayIdx = 1; 13582 else if (InputSize + OutputSize == 48) 13583 TgtElemArrayIdx = 2; 13584 else if (InputSize + OutputSize == 80) 13585 TgtElemArrayIdx = 3; 13586 else if (InputSize + OutputSize == 96) 13587 TgtElemArrayIdx = 4; 13588 else 13589 return SDValue(); 13590 13591 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13592 CorrectElems = DAG.getDataLayout().isLittleEndian() 13593 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13594 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13595 if (Elems != CorrectElems) { 13596 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13597 } 13598 13599 // Regular lowering will catch cases where a shuffle is not needed. 13600 return SDValue(); 13601 } 13602 13603 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13604 DAGCombinerInfo &DCI) const { 13605 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13606 "Should be called with a BUILD_VECTOR node"); 13607 13608 SelectionDAG &DAG = DCI.DAG; 13609 SDLoc dl(N); 13610 13611 if (!Subtarget.hasVSX()) 13612 return SDValue(); 13613 13614 // The target independent DAG combiner will leave a build_vector of 13615 // float-to-int conversions intact. We can generate MUCH better code for 13616 // a float-to-int conversion of a vector of floats. 13617 SDValue FirstInput = N->getOperand(0); 13618 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13619 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13620 if (Reduced) 13621 return Reduced; 13622 } 13623 13624 // If we're building a vector out of consecutive loads, just load that 13625 // vector type. 13626 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13627 if (Reduced) 13628 return Reduced; 13629 13630 // If we're building a vector out of extended elements from another vector 13631 // we have P9 vector integer extend instructions. The code assumes legal 13632 // input types (i.e. it can't handle things like v4i16) so do not run before 13633 // legalization. 13634 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13635 Reduced = combineBVOfVecSExt(N, DAG); 13636 if (Reduced) 13637 return Reduced; 13638 } 13639 13640 13641 if (N->getValueType(0) != MVT::v2f64) 13642 return SDValue(); 13643 13644 // Looking for: 13645 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13646 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13647 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13648 return SDValue(); 13649 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13650 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13651 return SDValue(); 13652 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13653 return SDValue(); 13654 13655 SDValue Ext1 = FirstInput.getOperand(0); 13656 SDValue Ext2 = N->getOperand(1).getOperand(0); 13657 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13658 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13659 return SDValue(); 13660 13661 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13662 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13663 if (!Ext1Op || !Ext2Op) 13664 return SDValue(); 13665 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13666 Ext1.getOperand(0) != Ext2.getOperand(0)) 13667 return SDValue(); 13668 13669 int FirstElem = Ext1Op->getZExtValue(); 13670 int SecondElem = Ext2Op->getZExtValue(); 13671 int SubvecIdx; 13672 if (FirstElem == 0 && SecondElem == 1) 13673 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13674 else if (FirstElem == 2 && SecondElem == 3) 13675 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13676 else 13677 return SDValue(); 13678 13679 SDValue SrcVec = Ext1.getOperand(0); 13680 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13681 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13682 return DAG.getNode(NodeType, dl, MVT::v2f64, 13683 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13684 } 13685 13686 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13687 DAGCombinerInfo &DCI) const { 13688 assert((N->getOpcode() == ISD::SINT_TO_FP || 13689 N->getOpcode() == ISD::UINT_TO_FP) && 13690 "Need an int -> FP conversion node here"); 13691 13692 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13693 return SDValue(); 13694 13695 SelectionDAG &DAG = DCI.DAG; 13696 SDLoc dl(N); 13697 SDValue Op(N, 0); 13698 13699 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13700 // from the hardware. 13701 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13702 return SDValue(); 13703 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13704 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13705 return SDValue(); 13706 13707 SDValue FirstOperand(Op.getOperand(0)); 13708 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13709 (FirstOperand.getValueType() == MVT::i8 || 13710 FirstOperand.getValueType() == MVT::i16); 13711 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13712 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13713 bool DstDouble = Op.getValueType() == MVT::f64; 13714 unsigned ConvOp = Signed ? 13715 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13716 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13717 SDValue WidthConst = 13718 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13719 dl, false); 13720 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13721 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13722 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13723 DAG.getVTList(MVT::f64, MVT::Other), 13724 Ops, MVT::i8, LDN->getMemOperand()); 13725 13726 // For signed conversion, we need to sign-extend the value in the VSR 13727 if (Signed) { 13728 SDValue ExtOps[] = { Ld, WidthConst }; 13729 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13730 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13731 } else 13732 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13733 } 13734 13735 13736 // For i32 intermediate values, unfortunately, the conversion functions 13737 // leave the upper 32 bits of the value are undefined. Within the set of 13738 // scalar instructions, we have no method for zero- or sign-extending the 13739 // value. Thus, we cannot handle i32 intermediate values here. 13740 if (Op.getOperand(0).getValueType() == MVT::i32) 13741 return SDValue(); 13742 13743 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13744 "UINT_TO_FP is supported only with FPCVT"); 13745 13746 // If we have FCFIDS, then use it when converting to single-precision. 13747 // Otherwise, convert to double-precision and then round. 13748 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13749 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13750 : PPCISD::FCFIDS) 13751 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13752 : PPCISD::FCFID); 13753 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13754 ? MVT::f32 13755 : MVT::f64; 13756 13757 // If we're converting from a float, to an int, and back to a float again, 13758 // then we don't need the store/load pair at all. 13759 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13760 Subtarget.hasFPCVT()) || 13761 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13762 SDValue Src = Op.getOperand(0).getOperand(0); 13763 if (Src.getValueType() == MVT::f32) { 13764 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13765 DCI.AddToWorklist(Src.getNode()); 13766 } else if (Src.getValueType() != MVT::f64) { 13767 // Make sure that we don't pick up a ppc_fp128 source value. 13768 return SDValue(); 13769 } 13770 13771 unsigned FCTOp = 13772 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13773 PPCISD::FCTIDUZ; 13774 13775 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13776 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13777 13778 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13779 FP = DAG.getNode(ISD::FP_ROUND, dl, 13780 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13781 DCI.AddToWorklist(FP.getNode()); 13782 } 13783 13784 return FP; 13785 } 13786 13787 return SDValue(); 13788 } 13789 13790 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13791 // builtins) into loads with swaps. 13792 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13793 DAGCombinerInfo &DCI) const { 13794 SelectionDAG &DAG = DCI.DAG; 13795 SDLoc dl(N); 13796 SDValue Chain; 13797 SDValue Base; 13798 MachineMemOperand *MMO; 13799 13800 switch (N->getOpcode()) { 13801 default: 13802 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13803 case ISD::LOAD: { 13804 LoadSDNode *LD = cast<LoadSDNode>(N); 13805 Chain = LD->getChain(); 13806 Base = LD->getBasePtr(); 13807 MMO = LD->getMemOperand(); 13808 // If the MMO suggests this isn't a load of a full vector, leave 13809 // things alone. For a built-in, we have to make the change for 13810 // correctness, so if there is a size problem that will be a bug. 13811 if (MMO->getSize() < 16) 13812 return SDValue(); 13813 break; 13814 } 13815 case ISD::INTRINSIC_W_CHAIN: { 13816 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13817 Chain = Intrin->getChain(); 13818 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13819 // us what we want. Get operand 2 instead. 13820 Base = Intrin->getOperand(2); 13821 MMO = Intrin->getMemOperand(); 13822 break; 13823 } 13824 } 13825 13826 MVT VecTy = N->getValueType(0).getSimpleVT(); 13827 13828 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13829 // aligned and the type is a vector with elements up to 4 bytes 13830 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13831 VecTy.getScalarSizeInBits() <= 32) { 13832 return SDValue(); 13833 } 13834 13835 SDValue LoadOps[] = { Chain, Base }; 13836 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13837 DAG.getVTList(MVT::v2f64, MVT::Other), 13838 LoadOps, MVT::v2f64, MMO); 13839 13840 DCI.AddToWorklist(Load.getNode()); 13841 Chain = Load.getValue(1); 13842 SDValue Swap = DAG.getNode( 13843 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13844 DCI.AddToWorklist(Swap.getNode()); 13845 13846 // Add a bitcast if the resulting load type doesn't match v2f64. 13847 if (VecTy != MVT::v2f64) { 13848 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13849 DCI.AddToWorklist(N.getNode()); 13850 // Package {bitcast value, swap's chain} to match Load's shape. 13851 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13852 N, Swap.getValue(1)); 13853 } 13854 13855 return Swap; 13856 } 13857 13858 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13859 // builtins) into stores with swaps. 13860 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13861 DAGCombinerInfo &DCI) const { 13862 SelectionDAG &DAG = DCI.DAG; 13863 SDLoc dl(N); 13864 SDValue Chain; 13865 SDValue Base; 13866 unsigned SrcOpnd; 13867 MachineMemOperand *MMO; 13868 13869 switch (N->getOpcode()) { 13870 default: 13871 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13872 case ISD::STORE: { 13873 StoreSDNode *ST = cast<StoreSDNode>(N); 13874 Chain = ST->getChain(); 13875 Base = ST->getBasePtr(); 13876 MMO = ST->getMemOperand(); 13877 SrcOpnd = 1; 13878 // If the MMO suggests this isn't a store of a full vector, leave 13879 // things alone. For a built-in, we have to make the change for 13880 // correctness, so if there is a size problem that will be a bug. 13881 if (MMO->getSize() < 16) 13882 return SDValue(); 13883 break; 13884 } 13885 case ISD::INTRINSIC_VOID: { 13886 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13887 Chain = Intrin->getChain(); 13888 // Intrin->getBasePtr() oddly does not get what we want. 13889 Base = Intrin->getOperand(3); 13890 MMO = Intrin->getMemOperand(); 13891 SrcOpnd = 2; 13892 break; 13893 } 13894 } 13895 13896 SDValue Src = N->getOperand(SrcOpnd); 13897 MVT VecTy = Src.getValueType().getSimpleVT(); 13898 13899 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13900 // aligned and the type is a vector with elements up to 4 bytes 13901 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13902 VecTy.getScalarSizeInBits() <= 32) { 13903 return SDValue(); 13904 } 13905 13906 // All stores are done as v2f64 and possible bit cast. 13907 if (VecTy != MVT::v2f64) { 13908 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13909 DCI.AddToWorklist(Src.getNode()); 13910 } 13911 13912 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13913 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13914 DCI.AddToWorklist(Swap.getNode()); 13915 Chain = Swap.getValue(1); 13916 SDValue StoreOps[] = { Chain, Swap, Base }; 13917 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13918 DAG.getVTList(MVT::Other), 13919 StoreOps, VecTy, MMO); 13920 DCI.AddToWorklist(Store.getNode()); 13921 return Store; 13922 } 13923 13924 // Handle DAG combine for STORE (FP_TO_INT F). 13925 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13926 DAGCombinerInfo &DCI) const { 13927 13928 SelectionDAG &DAG = DCI.DAG; 13929 SDLoc dl(N); 13930 unsigned Opcode = N->getOperand(1).getOpcode(); 13931 13932 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13933 && "Not a FP_TO_INT Instruction!"); 13934 13935 SDValue Val = N->getOperand(1).getOperand(0); 13936 EVT Op1VT = N->getOperand(1).getValueType(); 13937 EVT ResVT = Val.getValueType(); 13938 13939 // Floating point types smaller than 32 bits are not legal on Power. 13940 if (ResVT.getScalarSizeInBits() < 32) 13941 return SDValue(); 13942 13943 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13944 bool ValidTypeForStoreFltAsInt = 13945 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13946 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13947 13948 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13949 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13950 return SDValue(); 13951 13952 // Extend f32 values to f64 13953 if (ResVT.getScalarSizeInBits() == 32) { 13954 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13955 DCI.AddToWorklist(Val.getNode()); 13956 } 13957 13958 // Set signed or unsigned conversion opcode. 13959 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13960 PPCISD::FP_TO_SINT_IN_VSR : 13961 PPCISD::FP_TO_UINT_IN_VSR; 13962 13963 Val = DAG.getNode(ConvOpcode, 13964 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13965 DCI.AddToWorklist(Val.getNode()); 13966 13967 // Set number of bytes being converted. 13968 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13969 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13970 DAG.getIntPtrConstant(ByteSize, dl, false), 13971 DAG.getValueType(Op1VT) }; 13972 13973 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13974 DAG.getVTList(MVT::Other), Ops, 13975 cast<StoreSDNode>(N)->getMemoryVT(), 13976 cast<StoreSDNode>(N)->getMemOperand()); 13977 13978 DCI.AddToWorklist(Val.getNode()); 13979 return Val; 13980 } 13981 13982 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13983 LSBaseSDNode *LSBase, 13984 DAGCombinerInfo &DCI) const { 13985 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13986 "Not a reverse memop pattern!"); 13987 13988 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13989 auto Mask = SVN->getMask(); 13990 int i = 0; 13991 auto I = Mask.rbegin(); 13992 auto E = Mask.rend(); 13993 13994 for (; I != E; ++I) { 13995 if (*I != i) 13996 return false; 13997 i++; 13998 } 13999 return true; 14000 }; 14001 14002 SelectionDAG &DAG = DCI.DAG; 14003 EVT VT = SVN->getValueType(0); 14004 14005 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14006 return SDValue(); 14007 14008 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14009 // See comment in PPCVSXSwapRemoval.cpp. 14010 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14011 if (!Subtarget.hasP9Vector()) 14012 return SDValue(); 14013 14014 if(!IsElementReverse(SVN)) 14015 return SDValue(); 14016 14017 if (LSBase->getOpcode() == ISD::LOAD) { 14018 SDLoc dl(SVN); 14019 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14020 return DAG.getMemIntrinsicNode( 14021 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14022 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14023 } 14024 14025 if (LSBase->getOpcode() == ISD::STORE) { 14026 SDLoc dl(LSBase); 14027 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14028 LSBase->getBasePtr()}; 14029 return DAG.getMemIntrinsicNode( 14030 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14031 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14032 } 14033 14034 llvm_unreachable("Expected a load or store node here"); 14035 } 14036 14037 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14038 DAGCombinerInfo &DCI) const { 14039 SelectionDAG &DAG = DCI.DAG; 14040 SDLoc dl(N); 14041 switch (N->getOpcode()) { 14042 default: break; 14043 case ISD::ADD: 14044 return combineADD(N, DCI); 14045 case ISD::SHL: 14046 return combineSHL(N, DCI); 14047 case ISD::SRA: 14048 return combineSRA(N, DCI); 14049 case ISD::SRL: 14050 return combineSRL(N, DCI); 14051 case ISD::MUL: 14052 return combineMUL(N, DCI); 14053 case PPCISD::SHL: 14054 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14055 return N->getOperand(0); 14056 break; 14057 case PPCISD::SRL: 14058 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14059 return N->getOperand(0); 14060 break; 14061 case PPCISD::SRA: 14062 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14063 if (C->isNullValue() || // 0 >>s V -> 0. 14064 C->isAllOnesValue()) // -1 >>s V -> -1. 14065 return N->getOperand(0); 14066 } 14067 break; 14068 case ISD::SIGN_EXTEND: 14069 case ISD::ZERO_EXTEND: 14070 case ISD::ANY_EXTEND: 14071 return DAGCombineExtBoolTrunc(N, DCI); 14072 case ISD::TRUNCATE: 14073 return combineTRUNCATE(N, DCI); 14074 case ISD::SETCC: 14075 if (SDValue CSCC = combineSetCC(N, DCI)) 14076 return CSCC; 14077 LLVM_FALLTHROUGH; 14078 case ISD::SELECT_CC: 14079 return DAGCombineTruncBoolExt(N, DCI); 14080 case ISD::SINT_TO_FP: 14081 case ISD::UINT_TO_FP: 14082 return combineFPToIntToFP(N, DCI); 14083 case ISD::VECTOR_SHUFFLE: 14084 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14085 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14086 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14087 } 14088 break; 14089 case ISD::STORE: { 14090 14091 EVT Op1VT = N->getOperand(1).getValueType(); 14092 unsigned Opcode = N->getOperand(1).getOpcode(); 14093 14094 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14095 SDValue Val= combineStoreFPToInt(N, DCI); 14096 if (Val) 14097 return Val; 14098 } 14099 14100 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14101 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14102 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14103 if (Val) 14104 return Val; 14105 } 14106 14107 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14108 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14109 N->getOperand(1).getNode()->hasOneUse() && 14110 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14111 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14112 14113 // STBRX can only handle simple types and it makes no sense to store less 14114 // two bytes in byte-reversed order. 14115 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14116 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14117 break; 14118 14119 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14120 // Do an any-extend to 32-bits if this is a half-word input. 14121 if (BSwapOp.getValueType() == MVT::i16) 14122 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14123 14124 // If the type of BSWAP operand is wider than stored memory width 14125 // it need to be shifted to the right side before STBRX. 14126 if (Op1VT.bitsGT(mVT)) { 14127 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14128 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14129 DAG.getConstant(Shift, dl, MVT::i32)); 14130 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14131 if (Op1VT == MVT::i64) 14132 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14133 } 14134 14135 SDValue Ops[] = { 14136 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14137 }; 14138 return 14139 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14140 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14141 cast<StoreSDNode>(N)->getMemOperand()); 14142 } 14143 14144 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14145 // So it can increase the chance of CSE constant construction. 14146 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14147 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14148 // Need to sign-extended to 64-bits to handle negative values. 14149 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14150 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14151 MemVT.getSizeInBits()); 14152 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14153 14154 // DAG.getTruncStore() can't be used here because it doesn't accept 14155 // the general (base + offset) addressing mode. 14156 // So we use UpdateNodeOperands and setTruncatingStore instead. 14157 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14158 N->getOperand(3)); 14159 cast<StoreSDNode>(N)->setTruncatingStore(true); 14160 return SDValue(N, 0); 14161 } 14162 14163 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14164 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14165 if (Op1VT.isSimple()) { 14166 MVT StoreVT = Op1VT.getSimpleVT(); 14167 if (Subtarget.needsSwapsForVSXMemOps() && 14168 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14169 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14170 return expandVSXStoreForLE(N, DCI); 14171 } 14172 break; 14173 } 14174 case ISD::LOAD: { 14175 LoadSDNode *LD = cast<LoadSDNode>(N); 14176 EVT VT = LD->getValueType(0); 14177 14178 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14179 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14180 if (VT.isSimple()) { 14181 MVT LoadVT = VT.getSimpleVT(); 14182 if (Subtarget.needsSwapsForVSXMemOps() && 14183 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14184 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14185 return expandVSXLoadForLE(N, DCI); 14186 } 14187 14188 // We sometimes end up with a 64-bit integer load, from which we extract 14189 // two single-precision floating-point numbers. This happens with 14190 // std::complex<float>, and other similar structures, because of the way we 14191 // canonicalize structure copies. However, if we lack direct moves, 14192 // then the final bitcasts from the extracted integer values to the 14193 // floating-point numbers turn into store/load pairs. Even with direct moves, 14194 // just loading the two floating-point numbers is likely better. 14195 auto ReplaceTwoFloatLoad = [&]() { 14196 if (VT != MVT::i64) 14197 return false; 14198 14199 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14200 LD->isVolatile()) 14201 return false; 14202 14203 // We're looking for a sequence like this: 14204 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14205 // t16: i64 = srl t13, Constant:i32<32> 14206 // t17: i32 = truncate t16 14207 // t18: f32 = bitcast t17 14208 // t19: i32 = truncate t13 14209 // t20: f32 = bitcast t19 14210 14211 if (!LD->hasNUsesOfValue(2, 0)) 14212 return false; 14213 14214 auto UI = LD->use_begin(); 14215 while (UI.getUse().getResNo() != 0) ++UI; 14216 SDNode *Trunc = *UI++; 14217 while (UI.getUse().getResNo() != 0) ++UI; 14218 SDNode *RightShift = *UI; 14219 if (Trunc->getOpcode() != ISD::TRUNCATE) 14220 std::swap(Trunc, RightShift); 14221 14222 if (Trunc->getOpcode() != ISD::TRUNCATE || 14223 Trunc->getValueType(0) != MVT::i32 || 14224 !Trunc->hasOneUse()) 14225 return false; 14226 if (RightShift->getOpcode() != ISD::SRL || 14227 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14228 RightShift->getConstantOperandVal(1) != 32 || 14229 !RightShift->hasOneUse()) 14230 return false; 14231 14232 SDNode *Trunc2 = *RightShift->use_begin(); 14233 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14234 Trunc2->getValueType(0) != MVT::i32 || 14235 !Trunc2->hasOneUse()) 14236 return false; 14237 14238 SDNode *Bitcast = *Trunc->use_begin(); 14239 SDNode *Bitcast2 = *Trunc2->use_begin(); 14240 14241 if (Bitcast->getOpcode() != ISD::BITCAST || 14242 Bitcast->getValueType(0) != MVT::f32) 14243 return false; 14244 if (Bitcast2->getOpcode() != ISD::BITCAST || 14245 Bitcast2->getValueType(0) != MVT::f32) 14246 return false; 14247 14248 if (Subtarget.isLittleEndian()) 14249 std::swap(Bitcast, Bitcast2); 14250 14251 // Bitcast has the second float (in memory-layout order) and Bitcast2 14252 // has the first one. 14253 14254 SDValue BasePtr = LD->getBasePtr(); 14255 if (LD->isIndexed()) { 14256 assert(LD->getAddressingMode() == ISD::PRE_INC && 14257 "Non-pre-inc AM on PPC?"); 14258 BasePtr = 14259 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14260 LD->getOffset()); 14261 } 14262 14263 auto MMOFlags = 14264 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14265 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14266 LD->getPointerInfo(), LD->getAlignment(), 14267 MMOFlags, LD->getAAInfo()); 14268 SDValue AddPtr = 14269 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14270 BasePtr, DAG.getIntPtrConstant(4, dl)); 14271 SDValue FloatLoad2 = DAG.getLoad( 14272 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14273 LD->getPointerInfo().getWithOffset(4), 14274 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14275 14276 if (LD->isIndexed()) { 14277 // Note that DAGCombine should re-form any pre-increment load(s) from 14278 // what is produced here if that makes sense. 14279 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14280 } 14281 14282 DCI.CombineTo(Bitcast2, FloatLoad); 14283 DCI.CombineTo(Bitcast, FloatLoad2); 14284 14285 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14286 SDValue(FloatLoad2.getNode(), 1)); 14287 return true; 14288 }; 14289 14290 if (ReplaceTwoFloatLoad()) 14291 return SDValue(N, 0); 14292 14293 EVT MemVT = LD->getMemoryVT(); 14294 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14295 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14296 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14297 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14298 if (LD->isUnindexed() && VT.isVector() && 14299 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14300 // P8 and later hardware should just use LOAD. 14301 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14302 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14303 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14304 LD->getAlignment() >= ScalarABIAlignment)) && 14305 LD->getAlignment() < ABIAlignment) { 14306 // This is a type-legal unaligned Altivec or QPX load. 14307 SDValue Chain = LD->getChain(); 14308 SDValue Ptr = LD->getBasePtr(); 14309 bool isLittleEndian = Subtarget.isLittleEndian(); 14310 14311 // This implements the loading of unaligned vectors as described in 14312 // the venerable Apple Velocity Engine overview. Specifically: 14313 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14314 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14315 // 14316 // The general idea is to expand a sequence of one or more unaligned 14317 // loads into an alignment-based permutation-control instruction (lvsl 14318 // or lvsr), a series of regular vector loads (which always truncate 14319 // their input address to an aligned address), and a series of 14320 // permutations. The results of these permutations are the requested 14321 // loaded values. The trick is that the last "extra" load is not taken 14322 // from the address you might suspect (sizeof(vector) bytes after the 14323 // last requested load), but rather sizeof(vector) - 1 bytes after the 14324 // last requested vector. The point of this is to avoid a page fault if 14325 // the base address happened to be aligned. This works because if the 14326 // base address is aligned, then adding less than a full vector length 14327 // will cause the last vector in the sequence to be (re)loaded. 14328 // Otherwise, the next vector will be fetched as you might suspect was 14329 // necessary. 14330 14331 // We might be able to reuse the permutation generation from 14332 // a different base address offset from this one by an aligned amount. 14333 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14334 // optimization later. 14335 Intrinsic::ID Intr, IntrLD, IntrPerm; 14336 MVT PermCntlTy, PermTy, LDTy; 14337 if (Subtarget.hasAltivec()) { 14338 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14339 Intrinsic::ppc_altivec_lvsl; 14340 IntrLD = Intrinsic::ppc_altivec_lvx; 14341 IntrPerm = Intrinsic::ppc_altivec_vperm; 14342 PermCntlTy = MVT::v16i8; 14343 PermTy = MVT::v4i32; 14344 LDTy = MVT::v4i32; 14345 } else { 14346 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14347 Intrinsic::ppc_qpx_qvlpcls; 14348 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14349 Intrinsic::ppc_qpx_qvlfs; 14350 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14351 PermCntlTy = MVT::v4f64; 14352 PermTy = MVT::v4f64; 14353 LDTy = MemVT.getSimpleVT(); 14354 } 14355 14356 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14357 14358 // Create the new MMO for the new base load. It is like the original MMO, 14359 // but represents an area in memory almost twice the vector size centered 14360 // on the original address. If the address is unaligned, we might start 14361 // reading up to (sizeof(vector)-1) bytes below the address of the 14362 // original unaligned load. 14363 MachineFunction &MF = DAG.getMachineFunction(); 14364 MachineMemOperand *BaseMMO = 14365 MF.getMachineMemOperand(LD->getMemOperand(), 14366 -(long)MemVT.getStoreSize()+1, 14367 2*MemVT.getStoreSize()-1); 14368 14369 // Create the new base load. 14370 SDValue LDXIntID = 14371 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14372 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14373 SDValue BaseLoad = 14374 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14375 DAG.getVTList(PermTy, MVT::Other), 14376 BaseLoadOps, LDTy, BaseMMO); 14377 14378 // Note that the value of IncOffset (which is provided to the next 14379 // load's pointer info offset value, and thus used to calculate the 14380 // alignment), and the value of IncValue (which is actually used to 14381 // increment the pointer value) are different! This is because we 14382 // require the next load to appear to be aligned, even though it 14383 // is actually offset from the base pointer by a lesser amount. 14384 int IncOffset = VT.getSizeInBits() / 8; 14385 int IncValue = IncOffset; 14386 14387 // Walk (both up and down) the chain looking for another load at the real 14388 // (aligned) offset (the alignment of the other load does not matter in 14389 // this case). If found, then do not use the offset reduction trick, as 14390 // that will prevent the loads from being later combined (as they would 14391 // otherwise be duplicates). 14392 if (!findConsecutiveLoad(LD, DAG)) 14393 --IncValue; 14394 14395 SDValue Increment = 14396 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14397 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14398 14399 MachineMemOperand *ExtraMMO = 14400 MF.getMachineMemOperand(LD->getMemOperand(), 14401 1, 2*MemVT.getStoreSize()-1); 14402 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14403 SDValue ExtraLoad = 14404 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14405 DAG.getVTList(PermTy, MVT::Other), 14406 ExtraLoadOps, LDTy, ExtraMMO); 14407 14408 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14409 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14410 14411 // Because vperm has a big-endian bias, we must reverse the order 14412 // of the input vectors and complement the permute control vector 14413 // when generating little endian code. We have already handled the 14414 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14415 // and ExtraLoad here. 14416 SDValue Perm; 14417 if (isLittleEndian) 14418 Perm = BuildIntrinsicOp(IntrPerm, 14419 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14420 else 14421 Perm = BuildIntrinsicOp(IntrPerm, 14422 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14423 14424 if (VT != PermTy) 14425 Perm = Subtarget.hasAltivec() ? 14426 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14427 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14428 DAG.getTargetConstant(1, dl, MVT::i64)); 14429 // second argument is 1 because this rounding 14430 // is always exact. 14431 14432 // The output of the permutation is our loaded result, the TokenFactor is 14433 // our new chain. 14434 DCI.CombineTo(N, Perm, TF); 14435 return SDValue(N, 0); 14436 } 14437 } 14438 break; 14439 case ISD::INTRINSIC_WO_CHAIN: { 14440 bool isLittleEndian = Subtarget.isLittleEndian(); 14441 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14442 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14443 : Intrinsic::ppc_altivec_lvsl); 14444 if ((IID == Intr || 14445 IID == Intrinsic::ppc_qpx_qvlpcld || 14446 IID == Intrinsic::ppc_qpx_qvlpcls) && 14447 N->getOperand(1)->getOpcode() == ISD::ADD) { 14448 SDValue Add = N->getOperand(1); 14449 14450 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14451 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14452 14453 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14454 APInt::getAllOnesValue(Bits /* alignment */) 14455 .zext(Add.getScalarValueSizeInBits()))) { 14456 SDNode *BasePtr = Add->getOperand(0).getNode(); 14457 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14458 UE = BasePtr->use_end(); 14459 UI != UE; ++UI) { 14460 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14461 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14462 // We've found another LVSL/LVSR, and this address is an aligned 14463 // multiple of that one. The results will be the same, so use the 14464 // one we've just found instead. 14465 14466 return SDValue(*UI, 0); 14467 } 14468 } 14469 } 14470 14471 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14472 SDNode *BasePtr = Add->getOperand(0).getNode(); 14473 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14474 UE = BasePtr->use_end(); UI != UE; ++UI) { 14475 if (UI->getOpcode() == ISD::ADD && 14476 isa<ConstantSDNode>(UI->getOperand(1)) && 14477 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14478 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14479 (1ULL << Bits) == 0) { 14480 SDNode *OtherAdd = *UI; 14481 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14482 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14483 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14484 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14485 return SDValue(*VI, 0); 14486 } 14487 } 14488 } 14489 } 14490 } 14491 } 14492 14493 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14494 // Expose the vabsduw/h/b opportunity for down stream 14495 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14496 (IID == Intrinsic::ppc_altivec_vmaxsw || 14497 IID == Intrinsic::ppc_altivec_vmaxsh || 14498 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14499 SDValue V1 = N->getOperand(1); 14500 SDValue V2 = N->getOperand(2); 14501 if ((V1.getSimpleValueType() == MVT::v4i32 || 14502 V1.getSimpleValueType() == MVT::v8i16 || 14503 V1.getSimpleValueType() == MVT::v16i8) && 14504 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14505 // (0-a, a) 14506 if (V1.getOpcode() == ISD::SUB && 14507 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14508 V1.getOperand(1) == V2) { 14509 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14510 } 14511 // (a, 0-a) 14512 if (V2.getOpcode() == ISD::SUB && 14513 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14514 V2.getOperand(1) == V1) { 14515 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14516 } 14517 // (x-y, y-x) 14518 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14519 V1.getOperand(0) == V2.getOperand(1) && 14520 V1.getOperand(1) == V2.getOperand(0)) { 14521 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14522 } 14523 } 14524 } 14525 } 14526 14527 break; 14528 case ISD::INTRINSIC_W_CHAIN: 14529 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14530 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14531 if (Subtarget.needsSwapsForVSXMemOps()) { 14532 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14533 default: 14534 break; 14535 case Intrinsic::ppc_vsx_lxvw4x: 14536 case Intrinsic::ppc_vsx_lxvd2x: 14537 return expandVSXLoadForLE(N, DCI); 14538 } 14539 } 14540 break; 14541 case ISD::INTRINSIC_VOID: 14542 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14543 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14544 if (Subtarget.needsSwapsForVSXMemOps()) { 14545 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14546 default: 14547 break; 14548 case Intrinsic::ppc_vsx_stxvw4x: 14549 case Intrinsic::ppc_vsx_stxvd2x: 14550 return expandVSXStoreForLE(N, DCI); 14551 } 14552 } 14553 break; 14554 case ISD::BSWAP: 14555 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14556 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14557 N->getOperand(0).hasOneUse() && 14558 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14559 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14560 N->getValueType(0) == MVT::i64))) { 14561 SDValue Load = N->getOperand(0); 14562 LoadSDNode *LD = cast<LoadSDNode>(Load); 14563 // Create the byte-swapping load. 14564 SDValue Ops[] = { 14565 LD->getChain(), // Chain 14566 LD->getBasePtr(), // Ptr 14567 DAG.getValueType(N->getValueType(0)) // VT 14568 }; 14569 SDValue BSLoad = 14570 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14571 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14572 MVT::i64 : MVT::i32, MVT::Other), 14573 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14574 14575 // If this is an i16 load, insert the truncate. 14576 SDValue ResVal = BSLoad; 14577 if (N->getValueType(0) == MVT::i16) 14578 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14579 14580 // First, combine the bswap away. This makes the value produced by the 14581 // load dead. 14582 DCI.CombineTo(N, ResVal); 14583 14584 // Next, combine the load away, we give it a bogus result value but a real 14585 // chain result. The result value is dead because the bswap is dead. 14586 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14587 14588 // Return N so it doesn't get rechecked! 14589 return SDValue(N, 0); 14590 } 14591 break; 14592 case PPCISD::VCMP: 14593 // If a VCMPo node already exists with exactly the same operands as this 14594 // node, use its result instead of this node (VCMPo computes both a CR6 and 14595 // a normal output). 14596 // 14597 if (!N->getOperand(0).hasOneUse() && 14598 !N->getOperand(1).hasOneUse() && 14599 !N->getOperand(2).hasOneUse()) { 14600 14601 // Scan all of the users of the LHS, looking for VCMPo's that match. 14602 SDNode *VCMPoNode = nullptr; 14603 14604 SDNode *LHSN = N->getOperand(0).getNode(); 14605 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14606 UI != E; ++UI) 14607 if (UI->getOpcode() == PPCISD::VCMPo && 14608 UI->getOperand(1) == N->getOperand(1) && 14609 UI->getOperand(2) == N->getOperand(2) && 14610 UI->getOperand(0) == N->getOperand(0)) { 14611 VCMPoNode = *UI; 14612 break; 14613 } 14614 14615 // If there is no VCMPo node, or if the flag value has a single use, don't 14616 // transform this. 14617 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14618 break; 14619 14620 // Look at the (necessarily single) use of the flag value. If it has a 14621 // chain, this transformation is more complex. Note that multiple things 14622 // could use the value result, which we should ignore. 14623 SDNode *FlagUser = nullptr; 14624 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14625 FlagUser == nullptr; ++UI) { 14626 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14627 SDNode *User = *UI; 14628 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14629 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14630 FlagUser = User; 14631 break; 14632 } 14633 } 14634 } 14635 14636 // If the user is a MFOCRF instruction, we know this is safe. 14637 // Otherwise we give up for right now. 14638 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14639 return SDValue(VCMPoNode, 0); 14640 } 14641 break; 14642 case ISD::BRCOND: { 14643 SDValue Cond = N->getOperand(1); 14644 SDValue Target = N->getOperand(2); 14645 14646 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14647 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14648 Intrinsic::loop_decrement) { 14649 14650 // We now need to make the intrinsic dead (it cannot be instruction 14651 // selected). 14652 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14653 assert(Cond.getNode()->hasOneUse() && 14654 "Counter decrement has more than one use"); 14655 14656 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14657 N->getOperand(0), Target); 14658 } 14659 } 14660 break; 14661 case ISD::BR_CC: { 14662 // If this is a branch on an altivec predicate comparison, lower this so 14663 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14664 // lowering is done pre-legalize, because the legalizer lowers the predicate 14665 // compare down to code that is difficult to reassemble. 14666 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14667 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14668 14669 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14670 // value. If so, pass-through the AND to get to the intrinsic. 14671 if (LHS.getOpcode() == ISD::AND && 14672 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14673 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14674 Intrinsic::loop_decrement && 14675 isa<ConstantSDNode>(LHS.getOperand(1)) && 14676 !isNullConstant(LHS.getOperand(1))) 14677 LHS = LHS.getOperand(0); 14678 14679 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14680 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14681 Intrinsic::loop_decrement && 14682 isa<ConstantSDNode>(RHS)) { 14683 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14684 "Counter decrement comparison is not EQ or NE"); 14685 14686 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14687 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14688 (CC == ISD::SETNE && !Val); 14689 14690 // We now need to make the intrinsic dead (it cannot be instruction 14691 // selected). 14692 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14693 assert(LHS.getNode()->hasOneUse() && 14694 "Counter decrement has more than one use"); 14695 14696 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14697 N->getOperand(0), N->getOperand(4)); 14698 } 14699 14700 int CompareOpc; 14701 bool isDot; 14702 14703 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14704 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14705 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14706 assert(isDot && "Can't compare against a vector result!"); 14707 14708 // If this is a comparison against something other than 0/1, then we know 14709 // that the condition is never/always true. 14710 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14711 if (Val != 0 && Val != 1) { 14712 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14713 return N->getOperand(0); 14714 // Always !=, turn it into an unconditional branch. 14715 return DAG.getNode(ISD::BR, dl, MVT::Other, 14716 N->getOperand(0), N->getOperand(4)); 14717 } 14718 14719 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14720 14721 // Create the PPCISD altivec 'dot' comparison node. 14722 SDValue Ops[] = { 14723 LHS.getOperand(2), // LHS of compare 14724 LHS.getOperand(3), // RHS of compare 14725 DAG.getConstant(CompareOpc, dl, MVT::i32) 14726 }; 14727 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14728 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14729 14730 // Unpack the result based on how the target uses it. 14731 PPC::Predicate CompOpc; 14732 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14733 default: // Can't happen, don't crash on invalid number though. 14734 case 0: // Branch on the value of the EQ bit of CR6. 14735 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14736 break; 14737 case 1: // Branch on the inverted value of the EQ bit of CR6. 14738 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14739 break; 14740 case 2: // Branch on the value of the LT bit of CR6. 14741 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14742 break; 14743 case 3: // Branch on the inverted value of the LT bit of CR6. 14744 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14745 break; 14746 } 14747 14748 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14749 DAG.getConstant(CompOpc, dl, MVT::i32), 14750 DAG.getRegister(PPC::CR6, MVT::i32), 14751 N->getOperand(4), CompNode.getValue(1)); 14752 } 14753 break; 14754 } 14755 case ISD::BUILD_VECTOR: 14756 return DAGCombineBuildVector(N, DCI); 14757 case ISD::ABS: 14758 return combineABS(N, DCI); 14759 case ISD::VSELECT: 14760 return combineVSelect(N, DCI); 14761 } 14762 14763 return SDValue(); 14764 } 14765 14766 SDValue 14767 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14768 SelectionDAG &DAG, 14769 SmallVectorImpl<SDNode *> &Created) const { 14770 // fold (sdiv X, pow2) 14771 EVT VT = N->getValueType(0); 14772 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14773 return SDValue(); 14774 if ((VT != MVT::i32 && VT != MVT::i64) || 14775 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14776 return SDValue(); 14777 14778 SDLoc DL(N); 14779 SDValue N0 = N->getOperand(0); 14780 14781 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14782 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14783 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14784 14785 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14786 Created.push_back(Op.getNode()); 14787 14788 if (IsNegPow2) { 14789 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14790 Created.push_back(Op.getNode()); 14791 } 14792 14793 return Op; 14794 } 14795 14796 //===----------------------------------------------------------------------===// 14797 // Inline Assembly Support 14798 //===----------------------------------------------------------------------===// 14799 14800 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14801 KnownBits &Known, 14802 const APInt &DemandedElts, 14803 const SelectionDAG &DAG, 14804 unsigned Depth) const { 14805 Known.resetAll(); 14806 switch (Op.getOpcode()) { 14807 default: break; 14808 case PPCISD::LBRX: { 14809 // lhbrx is known to have the top bits cleared out. 14810 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14811 Known.Zero = 0xFFFF0000; 14812 break; 14813 } 14814 case ISD::INTRINSIC_WO_CHAIN: { 14815 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14816 default: break; 14817 case Intrinsic::ppc_altivec_vcmpbfp_p: 14818 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14819 case Intrinsic::ppc_altivec_vcmpequb_p: 14820 case Intrinsic::ppc_altivec_vcmpequh_p: 14821 case Intrinsic::ppc_altivec_vcmpequw_p: 14822 case Intrinsic::ppc_altivec_vcmpequd_p: 14823 case Intrinsic::ppc_altivec_vcmpgefp_p: 14824 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14825 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14826 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14827 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14828 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14829 case Intrinsic::ppc_altivec_vcmpgtub_p: 14830 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14831 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14832 case Intrinsic::ppc_altivec_vcmpgtud_p: 14833 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14834 break; 14835 } 14836 } 14837 } 14838 } 14839 14840 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14841 switch (Subtarget.getCPUDirective()) { 14842 default: break; 14843 case PPC::DIR_970: 14844 case PPC::DIR_PWR4: 14845 case PPC::DIR_PWR5: 14846 case PPC::DIR_PWR5X: 14847 case PPC::DIR_PWR6: 14848 case PPC::DIR_PWR6X: 14849 case PPC::DIR_PWR7: 14850 case PPC::DIR_PWR8: 14851 case PPC::DIR_PWR9: 14852 case PPC::DIR_PWR_FUTURE: { 14853 if (!ML) 14854 break; 14855 14856 if (!DisableInnermostLoopAlign32) { 14857 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14858 // so that we can decrease cache misses and branch-prediction misses. 14859 // Actual alignment of the loop will depend on the hotness check and other 14860 // logic in alignBlocks. 14861 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14862 return Align(32); 14863 } 14864 14865 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14866 14867 // For small loops (between 5 and 8 instructions), align to a 32-byte 14868 // boundary so that the entire loop fits in one instruction-cache line. 14869 uint64_t LoopSize = 0; 14870 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14871 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14872 LoopSize += TII->getInstSizeInBytes(*J); 14873 if (LoopSize > 32) 14874 break; 14875 } 14876 14877 if (LoopSize > 16 && LoopSize <= 32) 14878 return Align(32); 14879 14880 break; 14881 } 14882 } 14883 14884 return TargetLowering::getPrefLoopAlignment(ML); 14885 } 14886 14887 /// getConstraintType - Given a constraint, return the type of 14888 /// constraint it is for this target. 14889 PPCTargetLowering::ConstraintType 14890 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14891 if (Constraint.size() == 1) { 14892 switch (Constraint[0]) { 14893 default: break; 14894 case 'b': 14895 case 'r': 14896 case 'f': 14897 case 'd': 14898 case 'v': 14899 case 'y': 14900 return C_RegisterClass; 14901 case 'Z': 14902 // FIXME: While Z does indicate a memory constraint, it specifically 14903 // indicates an r+r address (used in conjunction with the 'y' modifier 14904 // in the replacement string). Currently, we're forcing the base 14905 // register to be r0 in the asm printer (which is interpreted as zero) 14906 // and forming the complete address in the second register. This is 14907 // suboptimal. 14908 return C_Memory; 14909 } 14910 } else if (Constraint == "wc") { // individual CR bits. 14911 return C_RegisterClass; 14912 } else if (Constraint == "wa" || Constraint == "wd" || 14913 Constraint == "wf" || Constraint == "ws" || 14914 Constraint == "wi" || Constraint == "ww") { 14915 return C_RegisterClass; // VSX registers. 14916 } 14917 return TargetLowering::getConstraintType(Constraint); 14918 } 14919 14920 /// Examine constraint type and operand type and determine a weight value. 14921 /// This object must already have been set up with the operand type 14922 /// and the current alternative constraint selected. 14923 TargetLowering::ConstraintWeight 14924 PPCTargetLowering::getSingleConstraintMatchWeight( 14925 AsmOperandInfo &info, const char *constraint) const { 14926 ConstraintWeight weight = CW_Invalid; 14927 Value *CallOperandVal = info.CallOperandVal; 14928 // If we don't have a value, we can't do a match, 14929 // but allow it at the lowest weight. 14930 if (!CallOperandVal) 14931 return CW_Default; 14932 Type *type = CallOperandVal->getType(); 14933 14934 // Look at the constraint type. 14935 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14936 return CW_Register; // an individual CR bit. 14937 else if ((StringRef(constraint) == "wa" || 14938 StringRef(constraint) == "wd" || 14939 StringRef(constraint) == "wf") && 14940 type->isVectorTy()) 14941 return CW_Register; 14942 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14943 return CW_Register; // just hold 64-bit integers data. 14944 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14945 return CW_Register; 14946 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14947 return CW_Register; 14948 14949 switch (*constraint) { 14950 default: 14951 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14952 break; 14953 case 'b': 14954 if (type->isIntegerTy()) 14955 weight = CW_Register; 14956 break; 14957 case 'f': 14958 if (type->isFloatTy()) 14959 weight = CW_Register; 14960 break; 14961 case 'd': 14962 if (type->isDoubleTy()) 14963 weight = CW_Register; 14964 break; 14965 case 'v': 14966 if (type->isVectorTy()) 14967 weight = CW_Register; 14968 break; 14969 case 'y': 14970 weight = CW_Register; 14971 break; 14972 case 'Z': 14973 weight = CW_Memory; 14974 break; 14975 } 14976 return weight; 14977 } 14978 14979 std::pair<unsigned, const TargetRegisterClass *> 14980 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14981 StringRef Constraint, 14982 MVT VT) const { 14983 if (Constraint.size() == 1) { 14984 // GCC RS6000 Constraint Letters 14985 switch (Constraint[0]) { 14986 case 'b': // R1-R31 14987 if (VT == MVT::i64 && Subtarget.isPPC64()) 14988 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14989 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14990 case 'r': // R0-R31 14991 if (VT == MVT::i64 && Subtarget.isPPC64()) 14992 return std::make_pair(0U, &PPC::G8RCRegClass); 14993 return std::make_pair(0U, &PPC::GPRCRegClass); 14994 // 'd' and 'f' constraints are both defined to be "the floating point 14995 // registers", where one is for 32-bit and the other for 64-bit. We don't 14996 // really care overly much here so just give them all the same reg classes. 14997 case 'd': 14998 case 'f': 14999 if (Subtarget.hasSPE()) { 15000 if (VT == MVT::f32 || VT == MVT::i32) 15001 return std::make_pair(0U, &PPC::GPRCRegClass); 15002 if (VT == MVT::f64 || VT == MVT::i64) 15003 return std::make_pair(0U, &PPC::SPERCRegClass); 15004 } else { 15005 if (VT == MVT::f32 || VT == MVT::i32) 15006 return std::make_pair(0U, &PPC::F4RCRegClass); 15007 if (VT == MVT::f64 || VT == MVT::i64) 15008 return std::make_pair(0U, &PPC::F8RCRegClass); 15009 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15010 return std::make_pair(0U, &PPC::QFRCRegClass); 15011 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15012 return std::make_pair(0U, &PPC::QSRCRegClass); 15013 } 15014 break; 15015 case 'v': 15016 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15017 return std::make_pair(0U, &PPC::QFRCRegClass); 15018 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15019 return std::make_pair(0U, &PPC::QSRCRegClass); 15020 if (Subtarget.hasAltivec()) 15021 return std::make_pair(0U, &PPC::VRRCRegClass); 15022 break; 15023 case 'y': // crrc 15024 return std::make_pair(0U, &PPC::CRRCRegClass); 15025 } 15026 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15027 // An individual CR bit. 15028 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15029 } else if ((Constraint == "wa" || Constraint == "wd" || 15030 Constraint == "wf" || Constraint == "wi") && 15031 Subtarget.hasVSX()) { 15032 return std::make_pair(0U, &PPC::VSRCRegClass); 15033 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15034 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15035 return std::make_pair(0U, &PPC::VSSRCRegClass); 15036 else 15037 return std::make_pair(0U, &PPC::VSFRCRegClass); 15038 } 15039 15040 // If we name a VSX register, we can't defer to the base class because it 15041 // will not recognize the correct register (their names will be VSL{0-31} 15042 // and V{0-31} so they won't match). So we match them here. 15043 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15044 int VSNum = atoi(Constraint.data() + 3); 15045 assert(VSNum >= 0 && VSNum <= 63 && 15046 "Attempted to access a vsr out of range"); 15047 if (VSNum < 32) 15048 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15049 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15050 } 15051 std::pair<unsigned, const TargetRegisterClass *> R = 15052 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15053 15054 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15055 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15056 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15057 // register. 15058 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15059 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15060 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15061 PPC::GPRCRegClass.contains(R.first)) 15062 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15063 PPC::sub_32, &PPC::G8RCRegClass), 15064 &PPC::G8RCRegClass); 15065 15066 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15067 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15068 R.first = PPC::CR0; 15069 R.second = &PPC::CRRCRegClass; 15070 } 15071 15072 return R; 15073 } 15074 15075 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15076 /// vector. If it is invalid, don't add anything to Ops. 15077 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15078 std::string &Constraint, 15079 std::vector<SDValue>&Ops, 15080 SelectionDAG &DAG) const { 15081 SDValue Result; 15082 15083 // Only support length 1 constraints. 15084 if (Constraint.length() > 1) return; 15085 15086 char Letter = Constraint[0]; 15087 switch (Letter) { 15088 default: break; 15089 case 'I': 15090 case 'J': 15091 case 'K': 15092 case 'L': 15093 case 'M': 15094 case 'N': 15095 case 'O': 15096 case 'P': { 15097 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15098 if (!CST) return; // Must be an immediate to match. 15099 SDLoc dl(Op); 15100 int64_t Value = CST->getSExtValue(); 15101 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15102 // numbers are printed as such. 15103 switch (Letter) { 15104 default: llvm_unreachable("Unknown constraint letter!"); 15105 case 'I': // "I" is a signed 16-bit constant. 15106 if (isInt<16>(Value)) 15107 Result = DAG.getTargetConstant(Value, dl, TCVT); 15108 break; 15109 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15110 if (isShiftedUInt<16, 16>(Value)) 15111 Result = DAG.getTargetConstant(Value, dl, TCVT); 15112 break; 15113 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15114 if (isShiftedInt<16, 16>(Value)) 15115 Result = DAG.getTargetConstant(Value, dl, TCVT); 15116 break; 15117 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15118 if (isUInt<16>(Value)) 15119 Result = DAG.getTargetConstant(Value, dl, TCVT); 15120 break; 15121 case 'M': // "M" is a constant that is greater than 31. 15122 if (Value > 31) 15123 Result = DAG.getTargetConstant(Value, dl, TCVT); 15124 break; 15125 case 'N': // "N" is a positive constant that is an exact power of two. 15126 if (Value > 0 && isPowerOf2_64(Value)) 15127 Result = DAG.getTargetConstant(Value, dl, TCVT); 15128 break; 15129 case 'O': // "O" is the constant zero. 15130 if (Value == 0) 15131 Result = DAG.getTargetConstant(Value, dl, TCVT); 15132 break; 15133 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15134 if (isInt<16>(-Value)) 15135 Result = DAG.getTargetConstant(Value, dl, TCVT); 15136 break; 15137 } 15138 break; 15139 } 15140 } 15141 15142 if (Result.getNode()) { 15143 Ops.push_back(Result); 15144 return; 15145 } 15146 15147 // Handle standard constraint letters. 15148 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15149 } 15150 15151 // isLegalAddressingMode - Return true if the addressing mode represented 15152 // by AM is legal for this target, for a load/store of the specified type. 15153 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15154 const AddrMode &AM, Type *Ty, 15155 unsigned AS, Instruction *I) const { 15156 // PPC does not allow r+i addressing modes for vectors! 15157 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15158 return false; 15159 15160 // PPC allows a sign-extended 16-bit immediate field. 15161 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15162 return false; 15163 15164 // No global is ever allowed as a base. 15165 if (AM.BaseGV) 15166 return false; 15167 15168 // PPC only support r+r, 15169 switch (AM.Scale) { 15170 case 0: // "r+i" or just "i", depending on HasBaseReg. 15171 break; 15172 case 1: 15173 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15174 return false; 15175 // Otherwise we have r+r or r+i. 15176 break; 15177 case 2: 15178 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15179 return false; 15180 // Allow 2*r as r+r. 15181 break; 15182 default: 15183 // No other scales are supported. 15184 return false; 15185 } 15186 15187 return true; 15188 } 15189 15190 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15191 SelectionDAG &DAG) const { 15192 MachineFunction &MF = DAG.getMachineFunction(); 15193 MachineFrameInfo &MFI = MF.getFrameInfo(); 15194 MFI.setReturnAddressIsTaken(true); 15195 15196 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15197 return SDValue(); 15198 15199 SDLoc dl(Op); 15200 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15201 15202 // Make sure the function does not optimize away the store of the RA to 15203 // the stack. 15204 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15205 FuncInfo->setLRStoreRequired(); 15206 bool isPPC64 = Subtarget.isPPC64(); 15207 auto PtrVT = getPointerTy(MF.getDataLayout()); 15208 15209 if (Depth > 0) { 15210 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15211 SDValue Offset = 15212 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15213 isPPC64 ? MVT::i64 : MVT::i32); 15214 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15215 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15216 MachinePointerInfo()); 15217 } 15218 15219 // Just load the return address off the stack. 15220 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15221 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15222 MachinePointerInfo()); 15223 } 15224 15225 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15226 SelectionDAG &DAG) const { 15227 SDLoc dl(Op); 15228 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15229 15230 MachineFunction &MF = DAG.getMachineFunction(); 15231 MachineFrameInfo &MFI = MF.getFrameInfo(); 15232 MFI.setFrameAddressIsTaken(true); 15233 15234 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15235 bool isPPC64 = PtrVT == MVT::i64; 15236 15237 // Naked functions never have a frame pointer, and so we use r1. For all 15238 // other functions, this decision must be delayed until during PEI. 15239 unsigned FrameReg; 15240 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15241 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15242 else 15243 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15244 15245 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15246 PtrVT); 15247 while (Depth--) 15248 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15249 FrameAddr, MachinePointerInfo()); 15250 return FrameAddr; 15251 } 15252 15253 // FIXME? Maybe this could be a TableGen attribute on some registers and 15254 // this table could be generated automatically from RegInfo. 15255 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15256 const MachineFunction &MF) const { 15257 bool isPPC64 = Subtarget.isPPC64(); 15258 15259 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15260 if (!is64Bit && VT != LLT::scalar(32)) 15261 report_fatal_error("Invalid register global variable type"); 15262 15263 Register Reg = StringSwitch<Register>(RegName) 15264 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15265 .Case("r2", isPPC64 ? Register() : PPC::R2) 15266 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15267 .Default(Register()); 15268 15269 if (Reg) 15270 return Reg; 15271 report_fatal_error("Invalid register name global variable"); 15272 } 15273 15274 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15275 // 32-bit SVR4 ABI access everything as got-indirect. 15276 if (Subtarget.is32BitELFABI()) 15277 return true; 15278 15279 // AIX accesses everything indirectly through the TOC, which is similar to 15280 // the GOT. 15281 if (Subtarget.isAIXABI()) 15282 return true; 15283 15284 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15285 // If it is small or large code model, module locals are accessed 15286 // indirectly by loading their address from .toc/.got. 15287 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15288 return true; 15289 15290 // JumpTable and BlockAddress are accessed as got-indirect. 15291 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15292 return true; 15293 15294 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15295 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15296 15297 return false; 15298 } 15299 15300 bool 15301 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15302 // The PowerPC target isn't yet aware of offsets. 15303 return false; 15304 } 15305 15306 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15307 const CallInst &I, 15308 MachineFunction &MF, 15309 unsigned Intrinsic) const { 15310 switch (Intrinsic) { 15311 case Intrinsic::ppc_qpx_qvlfd: 15312 case Intrinsic::ppc_qpx_qvlfs: 15313 case Intrinsic::ppc_qpx_qvlfcd: 15314 case Intrinsic::ppc_qpx_qvlfcs: 15315 case Intrinsic::ppc_qpx_qvlfiwa: 15316 case Intrinsic::ppc_qpx_qvlfiwz: 15317 case Intrinsic::ppc_altivec_lvx: 15318 case Intrinsic::ppc_altivec_lvxl: 15319 case Intrinsic::ppc_altivec_lvebx: 15320 case Intrinsic::ppc_altivec_lvehx: 15321 case Intrinsic::ppc_altivec_lvewx: 15322 case Intrinsic::ppc_vsx_lxvd2x: 15323 case Intrinsic::ppc_vsx_lxvw4x: { 15324 EVT VT; 15325 switch (Intrinsic) { 15326 case Intrinsic::ppc_altivec_lvebx: 15327 VT = MVT::i8; 15328 break; 15329 case Intrinsic::ppc_altivec_lvehx: 15330 VT = MVT::i16; 15331 break; 15332 case Intrinsic::ppc_altivec_lvewx: 15333 VT = MVT::i32; 15334 break; 15335 case Intrinsic::ppc_vsx_lxvd2x: 15336 VT = MVT::v2f64; 15337 break; 15338 case Intrinsic::ppc_qpx_qvlfd: 15339 VT = MVT::v4f64; 15340 break; 15341 case Intrinsic::ppc_qpx_qvlfs: 15342 VT = MVT::v4f32; 15343 break; 15344 case Intrinsic::ppc_qpx_qvlfcd: 15345 VT = MVT::v2f64; 15346 break; 15347 case Intrinsic::ppc_qpx_qvlfcs: 15348 VT = MVT::v2f32; 15349 break; 15350 default: 15351 VT = MVT::v4i32; 15352 break; 15353 } 15354 15355 Info.opc = ISD::INTRINSIC_W_CHAIN; 15356 Info.memVT = VT; 15357 Info.ptrVal = I.getArgOperand(0); 15358 Info.offset = -VT.getStoreSize()+1; 15359 Info.size = 2*VT.getStoreSize()-1; 15360 Info.align = Align(1); 15361 Info.flags = MachineMemOperand::MOLoad; 15362 return true; 15363 } 15364 case Intrinsic::ppc_qpx_qvlfda: 15365 case Intrinsic::ppc_qpx_qvlfsa: 15366 case Intrinsic::ppc_qpx_qvlfcda: 15367 case Intrinsic::ppc_qpx_qvlfcsa: 15368 case Intrinsic::ppc_qpx_qvlfiwaa: 15369 case Intrinsic::ppc_qpx_qvlfiwza: { 15370 EVT VT; 15371 switch (Intrinsic) { 15372 case Intrinsic::ppc_qpx_qvlfda: 15373 VT = MVT::v4f64; 15374 break; 15375 case Intrinsic::ppc_qpx_qvlfsa: 15376 VT = MVT::v4f32; 15377 break; 15378 case Intrinsic::ppc_qpx_qvlfcda: 15379 VT = MVT::v2f64; 15380 break; 15381 case Intrinsic::ppc_qpx_qvlfcsa: 15382 VT = MVT::v2f32; 15383 break; 15384 default: 15385 VT = MVT::v4i32; 15386 break; 15387 } 15388 15389 Info.opc = ISD::INTRINSIC_W_CHAIN; 15390 Info.memVT = VT; 15391 Info.ptrVal = I.getArgOperand(0); 15392 Info.offset = 0; 15393 Info.size = VT.getStoreSize(); 15394 Info.align = Align(1); 15395 Info.flags = MachineMemOperand::MOLoad; 15396 return true; 15397 } 15398 case Intrinsic::ppc_qpx_qvstfd: 15399 case Intrinsic::ppc_qpx_qvstfs: 15400 case Intrinsic::ppc_qpx_qvstfcd: 15401 case Intrinsic::ppc_qpx_qvstfcs: 15402 case Intrinsic::ppc_qpx_qvstfiw: 15403 case Intrinsic::ppc_altivec_stvx: 15404 case Intrinsic::ppc_altivec_stvxl: 15405 case Intrinsic::ppc_altivec_stvebx: 15406 case Intrinsic::ppc_altivec_stvehx: 15407 case Intrinsic::ppc_altivec_stvewx: 15408 case Intrinsic::ppc_vsx_stxvd2x: 15409 case Intrinsic::ppc_vsx_stxvw4x: { 15410 EVT VT; 15411 switch (Intrinsic) { 15412 case Intrinsic::ppc_altivec_stvebx: 15413 VT = MVT::i8; 15414 break; 15415 case Intrinsic::ppc_altivec_stvehx: 15416 VT = MVT::i16; 15417 break; 15418 case Intrinsic::ppc_altivec_stvewx: 15419 VT = MVT::i32; 15420 break; 15421 case Intrinsic::ppc_vsx_stxvd2x: 15422 VT = MVT::v2f64; 15423 break; 15424 case Intrinsic::ppc_qpx_qvstfd: 15425 VT = MVT::v4f64; 15426 break; 15427 case Intrinsic::ppc_qpx_qvstfs: 15428 VT = MVT::v4f32; 15429 break; 15430 case Intrinsic::ppc_qpx_qvstfcd: 15431 VT = MVT::v2f64; 15432 break; 15433 case Intrinsic::ppc_qpx_qvstfcs: 15434 VT = MVT::v2f32; 15435 break; 15436 default: 15437 VT = MVT::v4i32; 15438 break; 15439 } 15440 15441 Info.opc = ISD::INTRINSIC_VOID; 15442 Info.memVT = VT; 15443 Info.ptrVal = I.getArgOperand(1); 15444 Info.offset = -VT.getStoreSize()+1; 15445 Info.size = 2*VT.getStoreSize()-1; 15446 Info.align = Align(1); 15447 Info.flags = MachineMemOperand::MOStore; 15448 return true; 15449 } 15450 case Intrinsic::ppc_qpx_qvstfda: 15451 case Intrinsic::ppc_qpx_qvstfsa: 15452 case Intrinsic::ppc_qpx_qvstfcda: 15453 case Intrinsic::ppc_qpx_qvstfcsa: 15454 case Intrinsic::ppc_qpx_qvstfiwa: { 15455 EVT VT; 15456 switch (Intrinsic) { 15457 case Intrinsic::ppc_qpx_qvstfda: 15458 VT = MVT::v4f64; 15459 break; 15460 case Intrinsic::ppc_qpx_qvstfsa: 15461 VT = MVT::v4f32; 15462 break; 15463 case Intrinsic::ppc_qpx_qvstfcda: 15464 VT = MVT::v2f64; 15465 break; 15466 case Intrinsic::ppc_qpx_qvstfcsa: 15467 VT = MVT::v2f32; 15468 break; 15469 default: 15470 VT = MVT::v4i32; 15471 break; 15472 } 15473 15474 Info.opc = ISD::INTRINSIC_VOID; 15475 Info.memVT = VT; 15476 Info.ptrVal = I.getArgOperand(1); 15477 Info.offset = 0; 15478 Info.size = VT.getStoreSize(); 15479 Info.align = Align(1); 15480 Info.flags = MachineMemOperand::MOStore; 15481 return true; 15482 } 15483 default: 15484 break; 15485 } 15486 15487 return false; 15488 } 15489 15490 /// It returns EVT::Other if the type should be determined using generic 15491 /// target-independent logic. 15492 EVT PPCTargetLowering::getOptimalMemOpType( 15493 const MemOp &Op, const AttributeList &FuncAttributes) const { 15494 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15495 // When expanding a memset, require at least two QPX instructions to cover 15496 // the cost of loading the value to be stored from the constant pool. 15497 if (Subtarget.hasQPX() && Op.size() >= 32 && 15498 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15499 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15500 return MVT::v4f64; 15501 } 15502 15503 // We should use Altivec/VSX loads and stores when available. For unaligned 15504 // addresses, unaligned VSX loads are only fast starting with the P8. 15505 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15506 (Op.isAligned(Align(16)) || 15507 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15508 return MVT::v4i32; 15509 } 15510 15511 if (Subtarget.isPPC64()) { 15512 return MVT::i64; 15513 } 15514 15515 return MVT::i32; 15516 } 15517 15518 /// Returns true if it is beneficial to convert a load of a constant 15519 /// to just the constant itself. 15520 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15521 Type *Ty) const { 15522 assert(Ty->isIntegerTy()); 15523 15524 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15525 return !(BitSize == 0 || BitSize > 64); 15526 } 15527 15528 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15529 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15530 return false; 15531 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15532 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15533 return NumBits1 == 64 && NumBits2 == 32; 15534 } 15535 15536 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15537 if (!VT1.isInteger() || !VT2.isInteger()) 15538 return false; 15539 unsigned NumBits1 = VT1.getSizeInBits(); 15540 unsigned NumBits2 = VT2.getSizeInBits(); 15541 return NumBits1 == 64 && NumBits2 == 32; 15542 } 15543 15544 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15545 // Generally speaking, zexts are not free, but they are free when they can be 15546 // folded with other operations. 15547 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15548 EVT MemVT = LD->getMemoryVT(); 15549 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15550 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15551 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15552 LD->getExtensionType() == ISD::ZEXTLOAD)) 15553 return true; 15554 } 15555 15556 // FIXME: Add other cases... 15557 // - 32-bit shifts with a zext to i64 15558 // - zext after ctlz, bswap, etc. 15559 // - zext after and by a constant mask 15560 15561 return TargetLowering::isZExtFree(Val, VT2); 15562 } 15563 15564 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15565 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15566 "invalid fpext types"); 15567 // Extending to float128 is not free. 15568 if (DestVT == MVT::f128) 15569 return false; 15570 return true; 15571 } 15572 15573 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15574 return isInt<16>(Imm) || isUInt<16>(Imm); 15575 } 15576 15577 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15578 return isInt<16>(Imm) || isUInt<16>(Imm); 15579 } 15580 15581 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15582 unsigned, 15583 unsigned, 15584 MachineMemOperand::Flags, 15585 bool *Fast) const { 15586 if (DisablePPCUnaligned) 15587 return false; 15588 15589 // PowerPC supports unaligned memory access for simple non-vector types. 15590 // Although accessing unaligned addresses is not as efficient as accessing 15591 // aligned addresses, it is generally more efficient than manual expansion, 15592 // and generally only traps for software emulation when crossing page 15593 // boundaries. 15594 15595 if (!VT.isSimple()) 15596 return false; 15597 15598 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15599 return false; 15600 15601 if (VT.getSimpleVT().isVector()) { 15602 if (Subtarget.hasVSX()) { 15603 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15604 VT != MVT::v4f32 && VT != MVT::v4i32) 15605 return false; 15606 } else { 15607 return false; 15608 } 15609 } 15610 15611 if (VT == MVT::ppcf128) 15612 return false; 15613 15614 if (Fast) 15615 *Fast = true; 15616 15617 return true; 15618 } 15619 15620 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15621 EVT VT) const { 15622 return isFMAFasterThanFMulAndFAdd( 15623 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15624 } 15625 15626 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15627 Type *Ty) const { 15628 switch (Ty->getScalarType()->getTypeID()) { 15629 case Type::FloatTyID: 15630 case Type::DoubleTyID: 15631 return true; 15632 case Type::FP128TyID: 15633 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15634 default: 15635 return false; 15636 } 15637 } 15638 15639 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15640 // FIXME: add more patterns which are profitable to hoist. 15641 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15642 if (I->getOpcode() != Instruction::FMul) 15643 return true; 15644 15645 if (!I->hasOneUse()) 15646 return true; 15647 15648 Instruction *User = I->user_back(); 15649 assert(User && "A single use instruction with no uses."); 15650 15651 if (User->getOpcode() != Instruction::FSub && 15652 User->getOpcode() != Instruction::FAdd) 15653 return true; 15654 15655 const TargetOptions &Options = getTargetMachine().Options; 15656 const Function *F = I->getFunction(); 15657 const DataLayout &DL = F->getParent()->getDataLayout(); 15658 Type *Ty = User->getOperand(0)->getType(); 15659 15660 return !( 15661 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15662 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15663 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15664 } 15665 15666 const MCPhysReg * 15667 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15668 // LR is a callee-save register, but we must treat it as clobbered by any call 15669 // site. Hence we include LR in the scratch registers, which are in turn added 15670 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15671 // to CTR, which is used by any indirect call. 15672 static const MCPhysReg ScratchRegs[] = { 15673 PPC::X12, PPC::LR8, PPC::CTR8, 0 15674 }; 15675 15676 return ScratchRegs; 15677 } 15678 15679 Register PPCTargetLowering::getExceptionPointerRegister( 15680 const Constant *PersonalityFn) const { 15681 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15682 } 15683 15684 Register PPCTargetLowering::getExceptionSelectorRegister( 15685 const Constant *PersonalityFn) const { 15686 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15687 } 15688 15689 bool 15690 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15691 EVT VT , unsigned DefinedValues) const { 15692 if (VT == MVT::v2i64) 15693 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15694 15695 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15696 return true; 15697 15698 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15699 } 15700 15701 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15702 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15703 return TargetLowering::getSchedulingPreference(N); 15704 15705 return Sched::ILP; 15706 } 15707 15708 // Create a fast isel object. 15709 FastISel * 15710 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15711 const TargetLibraryInfo *LibInfo) const { 15712 return PPC::createFastISel(FuncInfo, LibInfo); 15713 } 15714 15715 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15716 if (!Subtarget.isPPC64()) return; 15717 15718 // Update IsSplitCSR in PPCFunctionInfo 15719 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15720 PFI->setIsSplitCSR(true); 15721 } 15722 15723 void PPCTargetLowering::insertCopiesSplitCSR( 15724 MachineBasicBlock *Entry, 15725 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15726 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15727 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15728 if (!IStart) 15729 return; 15730 15731 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15732 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15733 MachineBasicBlock::iterator MBBI = Entry->begin(); 15734 for (const MCPhysReg *I = IStart; *I; ++I) { 15735 const TargetRegisterClass *RC = nullptr; 15736 if (PPC::G8RCRegClass.contains(*I)) 15737 RC = &PPC::G8RCRegClass; 15738 else if (PPC::F8RCRegClass.contains(*I)) 15739 RC = &PPC::F8RCRegClass; 15740 else if (PPC::CRRCRegClass.contains(*I)) 15741 RC = &PPC::CRRCRegClass; 15742 else if (PPC::VRRCRegClass.contains(*I)) 15743 RC = &PPC::VRRCRegClass; 15744 else 15745 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15746 15747 Register NewVR = MRI->createVirtualRegister(RC); 15748 // Create copy from CSR to a virtual register. 15749 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15750 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15751 // nounwind. If we want to generalize this later, we may need to emit 15752 // CFI pseudo-instructions. 15753 assert(Entry->getParent()->getFunction().hasFnAttribute( 15754 Attribute::NoUnwind) && 15755 "Function should be nounwind in insertCopiesSplitCSR!"); 15756 Entry->addLiveIn(*I); 15757 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15758 .addReg(*I); 15759 15760 // Insert the copy-back instructions right before the terminator. 15761 for (auto *Exit : Exits) 15762 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15763 TII->get(TargetOpcode::COPY), *I) 15764 .addReg(NewVR); 15765 } 15766 } 15767 15768 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15769 bool PPCTargetLowering::useLoadStackGuardNode() const { 15770 if (!Subtarget.isTargetLinux()) 15771 return TargetLowering::useLoadStackGuardNode(); 15772 return true; 15773 } 15774 15775 // Override to disable global variable loading on Linux. 15776 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15777 if (!Subtarget.isTargetLinux()) 15778 return TargetLowering::insertSSPDeclarations(M); 15779 } 15780 15781 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15782 bool ForCodeSize) const { 15783 if (!VT.isSimple() || !Subtarget.hasVSX()) 15784 return false; 15785 15786 switch(VT.getSimpleVT().SimpleTy) { 15787 default: 15788 // For FP types that are currently not supported by PPC backend, return 15789 // false. Examples: f16, f80. 15790 return false; 15791 case MVT::f32: 15792 case MVT::f64: 15793 case MVT::ppcf128: 15794 return Imm.isPosZero(); 15795 } 15796 } 15797 15798 // For vector shift operation op, fold 15799 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15800 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15801 SelectionDAG &DAG) { 15802 SDValue N0 = N->getOperand(0); 15803 SDValue N1 = N->getOperand(1); 15804 EVT VT = N0.getValueType(); 15805 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15806 unsigned Opcode = N->getOpcode(); 15807 unsigned TargetOpcode; 15808 15809 switch (Opcode) { 15810 default: 15811 llvm_unreachable("Unexpected shift operation"); 15812 case ISD::SHL: 15813 TargetOpcode = PPCISD::SHL; 15814 break; 15815 case ISD::SRL: 15816 TargetOpcode = PPCISD::SRL; 15817 break; 15818 case ISD::SRA: 15819 TargetOpcode = PPCISD::SRA; 15820 break; 15821 } 15822 15823 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15824 N1->getOpcode() == ISD::AND) 15825 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15826 if (Mask->getZExtValue() == OpSizeInBits - 1) 15827 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15828 15829 return SDValue(); 15830 } 15831 15832 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15833 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15834 return Value; 15835 15836 SDValue N0 = N->getOperand(0); 15837 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15838 if (!Subtarget.isISA3_0() || 15839 N0.getOpcode() != ISD::SIGN_EXTEND || 15840 N0.getOperand(0).getValueType() != MVT::i32 || 15841 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15842 return SDValue(); 15843 15844 // We can't save an operation here if the value is already extended, and 15845 // the existing shift is easier to combine. 15846 SDValue ExtsSrc = N0.getOperand(0); 15847 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15848 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15849 return SDValue(); 15850 15851 SDLoc DL(N0); 15852 SDValue ShiftBy = SDValue(CN1, 0); 15853 // We want the shift amount to be i32 on the extswli, but the shift could 15854 // have an i64. 15855 if (ShiftBy.getValueType() == MVT::i64) 15856 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15857 15858 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15859 ShiftBy); 15860 } 15861 15862 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15863 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15864 return Value; 15865 15866 return SDValue(); 15867 } 15868 15869 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15870 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15871 return Value; 15872 15873 return SDValue(); 15874 } 15875 15876 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15877 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15878 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15879 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15880 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15881 const PPCSubtarget &Subtarget) { 15882 if (!Subtarget.isPPC64()) 15883 return SDValue(); 15884 15885 SDValue LHS = N->getOperand(0); 15886 SDValue RHS = N->getOperand(1); 15887 15888 auto isZextOfCompareWithConstant = [](SDValue Op) { 15889 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15890 Op.getValueType() != MVT::i64) 15891 return false; 15892 15893 SDValue Cmp = Op.getOperand(0); 15894 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15895 Cmp.getOperand(0).getValueType() != MVT::i64) 15896 return false; 15897 15898 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15899 int64_t NegConstant = 0 - Constant->getSExtValue(); 15900 // Due to the limitations of the addi instruction, 15901 // -C is required to be [-32768, 32767]. 15902 return isInt<16>(NegConstant); 15903 } 15904 15905 return false; 15906 }; 15907 15908 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15909 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15910 15911 // If there is a pattern, canonicalize a zext operand to the RHS. 15912 if (LHSHasPattern && !RHSHasPattern) 15913 std::swap(LHS, RHS); 15914 else if (!LHSHasPattern && !RHSHasPattern) 15915 return SDValue(); 15916 15917 SDLoc DL(N); 15918 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15919 SDValue Cmp = RHS.getOperand(0); 15920 SDValue Z = Cmp.getOperand(0); 15921 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15922 15923 assert(Constant && "Constant Should not be a null pointer."); 15924 int64_t NegConstant = 0 - Constant->getSExtValue(); 15925 15926 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15927 default: break; 15928 case ISD::SETNE: { 15929 // when C == 0 15930 // --> addze X, (addic Z, -1).carry 15931 // / 15932 // add X, (zext(setne Z, C))-- 15933 // \ when -32768 <= -C <= 32767 && C != 0 15934 // --> addze X, (addic (addi Z, -C), -1).carry 15935 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15936 DAG.getConstant(NegConstant, DL, MVT::i64)); 15937 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15938 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15939 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15940 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15941 SDValue(Addc.getNode(), 1)); 15942 } 15943 case ISD::SETEQ: { 15944 // when C == 0 15945 // --> addze X, (subfic Z, 0).carry 15946 // / 15947 // add X, (zext(sete Z, C))-- 15948 // \ when -32768 <= -C <= 32767 && C != 0 15949 // --> addze X, (subfic (addi Z, -C), 0).carry 15950 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15951 DAG.getConstant(NegConstant, DL, MVT::i64)); 15952 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15953 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15954 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15955 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15956 SDValue(Subc.getNode(), 1)); 15957 } 15958 } 15959 15960 return SDValue(); 15961 } 15962 15963 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15964 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15965 return Value; 15966 15967 return SDValue(); 15968 } 15969 15970 // Detect TRUNCATE operations on bitcasts of float128 values. 15971 // What we are looking for here is the situtation where we extract a subset 15972 // of bits from a 128 bit float. 15973 // This can be of two forms: 15974 // 1) BITCAST of f128 feeding TRUNCATE 15975 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15976 // The reason this is required is because we do not have a legal i128 type 15977 // and so we want to prevent having to store the f128 and then reload part 15978 // of it. 15979 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15980 DAGCombinerInfo &DCI) const { 15981 // If we are using CRBits then try that first. 15982 if (Subtarget.useCRBits()) { 15983 // Check if CRBits did anything and return that if it did. 15984 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15985 return CRTruncValue; 15986 } 15987 15988 SDLoc dl(N); 15989 SDValue Op0 = N->getOperand(0); 15990 15991 // Looking for a truncate of i128 to i64. 15992 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15993 return SDValue(); 15994 15995 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15996 15997 // SRL feeding TRUNCATE. 15998 if (Op0.getOpcode() == ISD::SRL) { 15999 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16000 // The right shift has to be by 64 bits. 16001 if (!ConstNode || ConstNode->getZExtValue() != 64) 16002 return SDValue(); 16003 16004 // Switch the element number to extract. 16005 EltToExtract = EltToExtract ? 0 : 1; 16006 // Update Op0 past the SRL. 16007 Op0 = Op0.getOperand(0); 16008 } 16009 16010 // BITCAST feeding a TRUNCATE possibly via SRL. 16011 if (Op0.getOpcode() == ISD::BITCAST && 16012 Op0.getValueType() == MVT::i128 && 16013 Op0.getOperand(0).getValueType() == MVT::f128) { 16014 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16015 return DCI.DAG.getNode( 16016 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16017 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16018 } 16019 return SDValue(); 16020 } 16021 16022 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16023 SelectionDAG &DAG = DCI.DAG; 16024 16025 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16026 if (!ConstOpOrElement) 16027 return SDValue(); 16028 16029 // An imul is usually smaller than the alternative sequence for legal type. 16030 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16031 isOperationLegal(ISD::MUL, N->getValueType(0))) 16032 return SDValue(); 16033 16034 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16035 switch (this->Subtarget.getCPUDirective()) { 16036 default: 16037 // TODO: enhance the condition for subtarget before pwr8 16038 return false; 16039 case PPC::DIR_PWR8: 16040 // type mul add shl 16041 // scalar 4 1 1 16042 // vector 7 2 2 16043 return true; 16044 case PPC::DIR_PWR9: 16045 case PPC::DIR_PWR_FUTURE: 16046 // type mul add shl 16047 // scalar 5 2 2 16048 // vector 7 2 2 16049 16050 // The cycle RATIO of related operations are showed as a table above. 16051 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16052 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16053 // are 4, it is always profitable; but for 3 instrs patterns 16054 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16055 // So we should only do it for vector type. 16056 return IsAddOne && IsNeg ? VT.isVector() : true; 16057 } 16058 }; 16059 16060 EVT VT = N->getValueType(0); 16061 SDLoc DL(N); 16062 16063 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16064 bool IsNeg = MulAmt.isNegative(); 16065 APInt MulAmtAbs = MulAmt.abs(); 16066 16067 if ((MulAmtAbs - 1).isPowerOf2()) { 16068 // (mul x, 2^N + 1) => (add (shl x, N), x) 16069 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16070 16071 if (!IsProfitable(IsNeg, true, VT)) 16072 return SDValue(); 16073 16074 SDValue Op0 = N->getOperand(0); 16075 SDValue Op1 = 16076 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16077 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16078 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16079 16080 if (!IsNeg) 16081 return Res; 16082 16083 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16084 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16085 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16086 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16087 16088 if (!IsProfitable(IsNeg, false, VT)) 16089 return SDValue(); 16090 16091 SDValue Op0 = N->getOperand(0); 16092 SDValue Op1 = 16093 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16094 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16095 16096 if (!IsNeg) 16097 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16098 else 16099 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16100 16101 } else { 16102 return SDValue(); 16103 } 16104 } 16105 16106 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16107 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16108 if (!Subtarget.is64BitELFABI()) 16109 return false; 16110 16111 // If not a tail call then no need to proceed. 16112 if (!CI->isTailCall()) 16113 return false; 16114 16115 // If sibling calls have been disabled and tail-calls aren't guaranteed 16116 // there is no reason to duplicate. 16117 auto &TM = getTargetMachine(); 16118 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16119 return false; 16120 16121 // Can't tail call a function called indirectly, or if it has variadic args. 16122 const Function *Callee = CI->getCalledFunction(); 16123 if (!Callee || Callee->isVarArg()) 16124 return false; 16125 16126 // Make sure the callee and caller calling conventions are eligible for tco. 16127 const Function *Caller = CI->getParent()->getParent(); 16128 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16129 CI->getCallingConv())) 16130 return false; 16131 16132 // If the function is local then we have a good chance at tail-calling it 16133 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16134 } 16135 16136 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16137 if (!Subtarget.hasVSX()) 16138 return false; 16139 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16140 return true; 16141 return VT == MVT::f32 || VT == MVT::f64 || 16142 VT == MVT::v4f32 || VT == MVT::v2f64; 16143 } 16144 16145 bool PPCTargetLowering:: 16146 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16147 const Value *Mask = AndI.getOperand(1); 16148 // If the mask is suitable for andi. or andis. we should sink the and. 16149 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16150 // Can't handle constants wider than 64-bits. 16151 if (CI->getBitWidth() > 64) 16152 return false; 16153 int64_t ConstVal = CI->getZExtValue(); 16154 return isUInt<16>(ConstVal) || 16155 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16156 } 16157 16158 // For non-constant masks, we can always use the record-form and. 16159 return true; 16160 } 16161 16162 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16163 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16164 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16165 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16166 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16167 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16168 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16169 assert(Subtarget.hasP9Altivec() && 16170 "Only combine this when P9 altivec supported!"); 16171 EVT VT = N->getValueType(0); 16172 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16173 return SDValue(); 16174 16175 SelectionDAG &DAG = DCI.DAG; 16176 SDLoc dl(N); 16177 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16178 // Even for signed integers, if it's known to be positive (as signed 16179 // integer) due to zero-extended inputs. 16180 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16181 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16182 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16183 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16184 (SubOpcd1 == ISD::ZERO_EXTEND || 16185 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16186 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16187 N->getOperand(0)->getOperand(0), 16188 N->getOperand(0)->getOperand(1), 16189 DAG.getTargetConstant(0, dl, MVT::i32)); 16190 } 16191 16192 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16193 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16194 N->getOperand(0).hasOneUse()) { 16195 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16196 N->getOperand(0)->getOperand(0), 16197 N->getOperand(0)->getOperand(1), 16198 DAG.getTargetConstant(1, dl, MVT::i32)); 16199 } 16200 } 16201 16202 return SDValue(); 16203 } 16204 16205 // For type v4i32/v8ii16/v16i8, transform 16206 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16207 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16208 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16209 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16210 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16211 DAGCombinerInfo &DCI) const { 16212 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16213 assert(Subtarget.hasP9Altivec() && 16214 "Only combine this when P9 altivec supported!"); 16215 16216 SelectionDAG &DAG = DCI.DAG; 16217 SDLoc dl(N); 16218 SDValue Cond = N->getOperand(0); 16219 SDValue TrueOpnd = N->getOperand(1); 16220 SDValue FalseOpnd = N->getOperand(2); 16221 EVT VT = N->getOperand(1).getValueType(); 16222 16223 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16224 FalseOpnd.getOpcode() != ISD::SUB) 16225 return SDValue(); 16226 16227 // ABSD only available for type v4i32/v8i16/v16i8 16228 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16229 return SDValue(); 16230 16231 // At least to save one more dependent computation 16232 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16233 return SDValue(); 16234 16235 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16236 16237 // Can only handle unsigned comparison here 16238 switch (CC) { 16239 default: 16240 return SDValue(); 16241 case ISD::SETUGT: 16242 case ISD::SETUGE: 16243 break; 16244 case ISD::SETULT: 16245 case ISD::SETULE: 16246 std::swap(TrueOpnd, FalseOpnd); 16247 break; 16248 } 16249 16250 SDValue CmpOpnd1 = Cond.getOperand(0); 16251 SDValue CmpOpnd2 = Cond.getOperand(1); 16252 16253 // SETCC CmpOpnd1 CmpOpnd2 cond 16254 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16255 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16256 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16257 TrueOpnd.getOperand(1) == CmpOpnd2 && 16258 FalseOpnd.getOperand(0) == CmpOpnd2 && 16259 FalseOpnd.getOperand(1) == CmpOpnd1) { 16260 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16261 CmpOpnd1, CmpOpnd2, 16262 DAG.getTargetConstant(0, dl, MVT::i32)); 16263 } 16264 16265 return SDValue(); 16266 } 16267