1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <utility> 99 #include <vector> 100 101 using namespace llvm; 102 103 #define DEBUG_TYPE "ppc-lowering" 104 105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 113 114 static cl::opt<bool> DisableSCO("disable-ppc-sco", 115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 116 117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 119 120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 121 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 122 123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 124 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 125 126 STATISTIC(NumTailCalls, "Number of tail calls"); 127 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 if (Subtarget.isISA3_0()) { 170 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 171 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 172 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 174 } else { 175 // No extending loads from f16 or HW conversions back and forth. 176 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 177 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 178 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 179 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 180 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 181 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 182 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 184 } 185 186 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 187 188 // PowerPC has pre-inc load and store's. 189 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 194 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 199 if (!Subtarget.hasSPE()) { 200 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 204 } 205 206 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 207 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 208 for (MVT VT : ScalarIntVTs) { 209 setOperationAction(ISD::ADDC, VT, Legal); 210 setOperationAction(ISD::ADDE, VT, Legal); 211 setOperationAction(ISD::SUBC, VT, Legal); 212 setOperationAction(ISD::SUBE, VT, Legal); 213 } 214 215 if (Subtarget.useCRBits()) { 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 217 218 if (isPPC64 || Subtarget.hasFPCVT()) { 219 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 220 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 221 isPPC64 ? MVT::i64 : MVT::i32); 222 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 223 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 224 isPPC64 ? MVT::i64 : MVT::i32); 225 } else { 226 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 228 } 229 230 // PowerPC does not support direct load/store of condition registers. 231 setOperationAction(ISD::LOAD, MVT::i1, Custom); 232 setOperationAction(ISD::STORE, MVT::i1, Custom); 233 234 // FIXME: Remove this once the ANDI glue bug is fixed: 235 if (ANDIGlueBug) 236 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 237 238 for (MVT VT : MVT::integer_valuetypes()) { 239 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 241 setTruncStoreAction(VT, MVT::i1, Expand); 242 } 243 244 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 245 } 246 247 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 248 // PPC (the libcall is not available). 249 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 250 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 251 252 // We do not currently implement these libm ops for PowerPC. 253 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 254 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 259 260 // PowerPC has no SREM/UREM instructions unless we are on P9 261 // On P9 we may use a hardware instruction to compute the remainder. 262 // The instructions are not legalized directly because in the cases where the 263 // result of both the remainder and the division is required it is more 264 // efficient to compute the remainder from the result of the division rather 265 // than use the remainder instruction. 266 if (Subtarget.isISA3_0()) { 267 setOperationAction(ISD::SREM, MVT::i32, Custom); 268 setOperationAction(ISD::UREM, MVT::i32, Custom); 269 setOperationAction(ISD::SREM, MVT::i64, Custom); 270 setOperationAction(ISD::UREM, MVT::i64, Custom); 271 } else { 272 setOperationAction(ISD::SREM, MVT::i32, Expand); 273 setOperationAction(ISD::UREM, MVT::i32, Expand); 274 setOperationAction(ISD::SREM, MVT::i64, Expand); 275 setOperationAction(ISD::UREM, MVT::i64, Expand); 276 } 277 278 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 279 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 280 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 282 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 284 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 287 288 // Handle constrained floating-point operations of scalar. 289 // TODO: Handle SPE specific operation. 290 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 291 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 294 295 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 296 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 299 300 // We don't support sin/cos/sqrt/fmod/pow 301 setOperationAction(ISD::FSIN , MVT::f64, Expand); 302 setOperationAction(ISD::FCOS , MVT::f64, Expand); 303 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 304 setOperationAction(ISD::FREM , MVT::f64, Expand); 305 setOperationAction(ISD::FPOW , MVT::f64, Expand); 306 setOperationAction(ISD::FSIN , MVT::f32, Expand); 307 setOperationAction(ISD::FCOS , MVT::f32, Expand); 308 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 309 setOperationAction(ISD::FREM , MVT::f32, Expand); 310 setOperationAction(ISD::FPOW , MVT::f32, Expand); 311 if (Subtarget.hasSPE()) { 312 setOperationAction(ISD::FMA , MVT::f64, Expand); 313 setOperationAction(ISD::FMA , MVT::f32, Expand); 314 } else { 315 setOperationAction(ISD::FMA , MVT::f64, Legal); 316 setOperationAction(ISD::FMA , MVT::f32, Legal); 317 } 318 319 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 320 321 // If we're enabling GP optimizations, use hardware square root 322 if (!Subtarget.hasFSQRT() && 323 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 324 Subtarget.hasFRE())) 325 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 326 327 if (!Subtarget.hasFSQRT() && 328 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 329 Subtarget.hasFRES())) 330 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 331 332 if (Subtarget.hasFCPSGN()) { 333 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 334 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 335 } else { 336 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 337 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 338 } 339 340 if (Subtarget.hasFPRND()) { 341 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 342 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 343 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 344 setOperationAction(ISD::FROUND, MVT::f64, Legal); 345 346 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 347 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 348 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 349 setOperationAction(ISD::FROUND, MVT::f32, Legal); 350 } 351 352 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 353 // to speed up scalar BSWAP64. 354 // CTPOP or CTTZ were introduced in P8/P9 respectively 355 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 356 if (Subtarget.hasP9Vector()) 357 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 358 else 359 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 360 if (Subtarget.isISA3_0()) { 361 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 362 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 363 } else { 364 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 365 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 366 } 367 368 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 369 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 370 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 371 } else { 372 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 373 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 374 } 375 376 // PowerPC does not have ROTR 377 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 378 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 379 380 if (!Subtarget.useCRBits()) { 381 // PowerPC does not have Select 382 setOperationAction(ISD::SELECT, MVT::i32, Expand); 383 setOperationAction(ISD::SELECT, MVT::i64, Expand); 384 setOperationAction(ISD::SELECT, MVT::f32, Expand); 385 setOperationAction(ISD::SELECT, MVT::f64, Expand); 386 } 387 388 // PowerPC wants to turn select_cc of FP into fsel when possible. 389 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 390 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 391 392 // PowerPC wants to optimize integer setcc a bit 393 if (!Subtarget.useCRBits()) 394 setOperationAction(ISD::SETCC, MVT::i32, Custom); 395 396 // PowerPC does not have BRCOND which requires SetCC 397 if (!Subtarget.useCRBits()) 398 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 399 400 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 401 402 if (Subtarget.hasSPE()) { 403 // SPE has built-in conversions 404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 405 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 406 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 407 } else { 408 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 409 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 410 411 // PowerPC does not have [U|S]INT_TO_FP 412 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 413 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 414 } 415 416 if (Subtarget.hasDirectMove() && isPPC64) { 417 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 418 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 419 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 420 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 421 if (TM.Options.UnsafeFPMath) { 422 setOperationAction(ISD::LRINT, MVT::f64, Legal); 423 setOperationAction(ISD::LRINT, MVT::f32, Legal); 424 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 425 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 426 setOperationAction(ISD::LROUND, MVT::f64, Legal); 427 setOperationAction(ISD::LROUND, MVT::f32, Legal); 428 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 429 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 430 } 431 } else { 432 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 433 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 434 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 435 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 436 } 437 438 // We cannot sextinreg(i1). Expand to shifts. 439 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 440 441 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 442 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 443 // support continuation, user-level threading, and etc.. As a result, no 444 // other SjLj exception interfaces are implemented and please don't build 445 // your own exception handling based on them. 446 // LLVM/Clang supports zero-cost DWARF exception handling. 447 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 448 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 449 450 // We want to legalize GlobalAddress and ConstantPool nodes into the 451 // appropriate instructions to materialize the address. 452 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 453 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 454 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 455 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 456 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 457 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 459 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 460 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 461 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 462 463 // TRAP is legal. 464 setOperationAction(ISD::TRAP, MVT::Other, Legal); 465 466 // TRAMPOLINE is custom lowered. 467 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 468 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 469 470 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 471 setOperationAction(ISD::VASTART , MVT::Other, Custom); 472 473 if (Subtarget.is64BitELFABI()) { 474 // VAARG always uses double-word chunks, so promote anything smaller. 475 setOperationAction(ISD::VAARG, MVT::i1, Promote); 476 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 477 setOperationAction(ISD::VAARG, MVT::i8, Promote); 478 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 479 setOperationAction(ISD::VAARG, MVT::i16, Promote); 480 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 481 setOperationAction(ISD::VAARG, MVT::i32, Promote); 482 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 483 setOperationAction(ISD::VAARG, MVT::Other, Expand); 484 } else if (Subtarget.is32BitELFABI()) { 485 // VAARG is custom lowered with the 32-bit SVR4 ABI. 486 setOperationAction(ISD::VAARG, MVT::Other, Custom); 487 setOperationAction(ISD::VAARG, MVT::i64, Custom); 488 } else 489 setOperationAction(ISD::VAARG, MVT::Other, Expand); 490 491 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 492 if (Subtarget.is32BitELFABI()) 493 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 494 else 495 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 496 497 // Use the default implementation. 498 setOperationAction(ISD::VAEND , MVT::Other, Expand); 499 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 500 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 501 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 502 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 503 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 504 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 505 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 506 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 507 508 // We want to custom lower some of our intrinsics. 509 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 510 511 // To handle counter-based loop conditions. 512 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 513 514 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 515 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 516 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 517 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 518 519 // Comparisons that require checking two conditions. 520 if (Subtarget.hasSPE()) { 521 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 522 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 523 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 524 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 525 } 526 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 527 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 528 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 529 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 530 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 531 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 532 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 533 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 534 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 535 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 536 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 537 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 538 539 if (Subtarget.has64BitSupport()) { 540 // They also have instructions for converting between i64 and fp. 541 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 542 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 543 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 544 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 545 // This is just the low 32 bits of a (signed) fp->i64 conversion. 546 // We cannot do this with Promote because i64 is not a legal type. 547 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 548 549 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 550 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 551 } else { 552 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 553 if (Subtarget.hasSPE()) 554 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 555 else 556 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 557 } 558 559 // With the instructions enabled under FPCVT, we can do everything. 560 if (Subtarget.hasFPCVT()) { 561 if (Subtarget.has64BitSupport()) { 562 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 563 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 564 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 565 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 566 } 567 568 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 569 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 570 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 571 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 572 } 573 574 if (Subtarget.use64BitRegs()) { 575 // 64-bit PowerPC implementations can support i64 types directly 576 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 577 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 578 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 579 // 64-bit PowerPC wants to expand i128 shifts itself. 580 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 581 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 582 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 583 } else { 584 // 32-bit PowerPC wants to expand i64 shifts itself. 585 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 586 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 587 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 588 } 589 590 if (Subtarget.hasVSX()) { 591 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 592 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 593 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 594 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 595 } 596 597 if (Subtarget.hasAltivec()) { 598 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 599 setOperationAction(ISD::SADDSAT, VT, Legal); 600 setOperationAction(ISD::SSUBSAT, VT, Legal); 601 setOperationAction(ISD::UADDSAT, VT, Legal); 602 setOperationAction(ISD::USUBSAT, VT, Legal); 603 } 604 // First set operation action for all vector types to expand. Then we 605 // will selectively turn on ones that can be effectively codegen'd. 606 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 607 // add/sub are legal for all supported vector VT's. 608 setOperationAction(ISD::ADD, VT, Legal); 609 setOperationAction(ISD::SUB, VT, Legal); 610 611 // For v2i64, these are only valid with P8Vector. This is corrected after 612 // the loop. 613 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 614 setOperationAction(ISD::SMAX, VT, Legal); 615 setOperationAction(ISD::SMIN, VT, Legal); 616 setOperationAction(ISD::UMAX, VT, Legal); 617 setOperationAction(ISD::UMIN, VT, Legal); 618 } 619 else { 620 setOperationAction(ISD::SMAX, VT, Expand); 621 setOperationAction(ISD::SMIN, VT, Expand); 622 setOperationAction(ISD::UMAX, VT, Expand); 623 setOperationAction(ISD::UMIN, VT, Expand); 624 } 625 626 if (Subtarget.hasVSX()) { 627 setOperationAction(ISD::FMAXNUM, VT, Legal); 628 setOperationAction(ISD::FMINNUM, VT, Legal); 629 } 630 631 // Vector instructions introduced in P8 632 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 633 setOperationAction(ISD::CTPOP, VT, Legal); 634 setOperationAction(ISD::CTLZ, VT, Legal); 635 } 636 else { 637 setOperationAction(ISD::CTPOP, VT, Expand); 638 setOperationAction(ISD::CTLZ, VT, Expand); 639 } 640 641 // Vector instructions introduced in P9 642 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 643 setOperationAction(ISD::CTTZ, VT, Legal); 644 else 645 setOperationAction(ISD::CTTZ, VT, Expand); 646 647 // We promote all shuffles to v16i8. 648 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 649 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 650 651 // We promote all non-typed operations to v4i32. 652 setOperationAction(ISD::AND , VT, Promote); 653 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 654 setOperationAction(ISD::OR , VT, Promote); 655 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 656 setOperationAction(ISD::XOR , VT, Promote); 657 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 658 setOperationAction(ISD::LOAD , VT, Promote); 659 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 660 setOperationAction(ISD::SELECT, VT, Promote); 661 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 662 setOperationAction(ISD::VSELECT, VT, Legal); 663 setOperationAction(ISD::SELECT_CC, VT, Promote); 664 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 665 setOperationAction(ISD::STORE, VT, Promote); 666 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 667 668 // No other operations are legal. 669 setOperationAction(ISD::MUL , VT, Expand); 670 setOperationAction(ISD::SDIV, VT, Expand); 671 setOperationAction(ISD::SREM, VT, Expand); 672 setOperationAction(ISD::UDIV, VT, Expand); 673 setOperationAction(ISD::UREM, VT, Expand); 674 setOperationAction(ISD::FDIV, VT, Expand); 675 setOperationAction(ISD::FREM, VT, Expand); 676 setOperationAction(ISD::FNEG, VT, Expand); 677 setOperationAction(ISD::FSQRT, VT, Expand); 678 setOperationAction(ISD::FLOG, VT, Expand); 679 setOperationAction(ISD::FLOG10, VT, Expand); 680 setOperationAction(ISD::FLOG2, VT, Expand); 681 setOperationAction(ISD::FEXP, VT, Expand); 682 setOperationAction(ISD::FEXP2, VT, Expand); 683 setOperationAction(ISD::FSIN, VT, Expand); 684 setOperationAction(ISD::FCOS, VT, Expand); 685 setOperationAction(ISD::FABS, VT, Expand); 686 setOperationAction(ISD::FFLOOR, VT, Expand); 687 setOperationAction(ISD::FCEIL, VT, Expand); 688 setOperationAction(ISD::FTRUNC, VT, Expand); 689 setOperationAction(ISD::FRINT, VT, Expand); 690 setOperationAction(ISD::FNEARBYINT, VT, Expand); 691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 692 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 693 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 694 setOperationAction(ISD::MULHU, VT, Expand); 695 setOperationAction(ISD::MULHS, VT, Expand); 696 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 697 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 698 setOperationAction(ISD::UDIVREM, VT, Expand); 699 setOperationAction(ISD::SDIVREM, VT, Expand); 700 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 701 setOperationAction(ISD::FPOW, VT, Expand); 702 setOperationAction(ISD::BSWAP, VT, Expand); 703 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 704 setOperationAction(ISD::ROTL, VT, Expand); 705 setOperationAction(ISD::ROTR, VT, Expand); 706 707 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 708 setTruncStoreAction(VT, InnerVT, Expand); 709 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 710 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 711 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 712 } 713 } 714 if (!Subtarget.hasP8Vector()) { 715 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 716 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 717 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 718 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 719 } 720 721 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 722 setOperationAction(ISD::ABS, VT, Custom); 723 724 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 725 // with merges, splats, etc. 726 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 727 728 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 729 // are cheap, so handle them before they get expanded to scalar. 730 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 731 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 732 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 733 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 734 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 735 736 setOperationAction(ISD::AND , MVT::v4i32, Legal); 737 setOperationAction(ISD::OR , MVT::v4i32, Legal); 738 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 739 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 740 setOperationAction(ISD::SELECT, MVT::v4i32, 741 Subtarget.useCRBits() ? Legal : Expand); 742 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 743 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 744 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 745 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 746 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 747 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 748 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 749 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 750 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 751 752 // Without hasP8Altivec set, v2i64 SMAX isn't available. 753 // But ABS custom lowering requires SMAX support. 754 if (!Subtarget.hasP8Altivec()) 755 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 756 757 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 758 if (Subtarget.hasAltivec()) 759 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 760 setOperationAction(ISD::ROTL, VT, Legal); 761 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 762 if (Subtarget.hasP8Altivec()) 763 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 764 765 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 766 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 767 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 768 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 769 770 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 771 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 772 773 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 774 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 775 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 776 } 777 778 if (Subtarget.hasP8Altivec()) 779 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 780 else 781 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 782 783 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 784 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 785 786 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 787 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 788 789 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 790 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 791 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 792 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 793 794 // Altivec does not contain unordered floating-point compare instructions 795 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 796 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 797 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 798 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 799 800 if (Subtarget.hasVSX()) { 801 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 802 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 803 if (Subtarget.hasP8Vector()) { 804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 805 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 806 } 807 if (Subtarget.hasDirectMove() && isPPC64) { 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 809 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 810 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 813 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 816 } 817 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 818 819 // The nearbyint variants are not allowed to raise the inexact exception 820 // so we can only code-gen them with unsafe math. 821 if (TM.Options.UnsafeFPMath) { 822 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 823 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 824 } 825 826 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 827 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 828 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 829 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 830 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 831 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 832 setOperationAction(ISD::FROUND, MVT::f64, Legal); 833 setOperationAction(ISD::FRINT, MVT::f64, Legal); 834 835 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 836 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 837 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 838 setOperationAction(ISD::FROUND, MVT::f32, Legal); 839 setOperationAction(ISD::FRINT, MVT::f32, Legal); 840 841 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 842 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 843 844 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 845 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 846 847 // Share the Altivec comparison restrictions. 848 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 849 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 850 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 851 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 852 853 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 854 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 855 856 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 857 858 if (Subtarget.hasP8Vector()) 859 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 860 861 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 862 863 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 864 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 865 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 866 867 if (Subtarget.hasP8Altivec()) { 868 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 869 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 870 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 871 872 // 128 bit shifts can be accomplished via 3 instructions for SHL and 873 // SRL, but not for SRA because of the instructions available: 874 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 875 // doing 876 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 877 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 878 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 879 880 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 881 } 882 else { 883 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 884 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 885 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 886 887 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 888 889 // VSX v2i64 only supports non-arithmetic operations. 890 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 891 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 892 } 893 894 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 895 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 896 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 897 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 898 899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 900 901 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 902 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 903 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 904 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 905 906 // Custom handling for partial vectors of integers converted to 907 // floating point. We already have optimal handling for v2i32 through 908 // the DAG combine, so those aren't necessary. 909 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 911 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 912 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 913 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 914 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 915 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 916 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 917 918 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 919 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 920 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 921 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 922 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 923 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 924 925 if (Subtarget.hasDirectMove()) 926 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 927 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 928 929 // Handle constrained floating-point operations of vector. 930 // The predictor is `hasVSX` because altivec instruction has 931 // no exception but VSX vector instruction has. 932 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 933 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 934 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 935 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 936 937 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 938 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 939 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 940 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 941 942 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 943 } 944 945 if (Subtarget.hasP8Altivec()) { 946 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 947 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 948 } 949 950 if (Subtarget.hasP9Vector()) { 951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 953 954 // 128 bit shifts can be accomplished via 3 instructions for SHL and 955 // SRL, but not for SRA because of the instructions available: 956 // VS{RL} and VS{RL}O. 957 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 958 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 959 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 960 961 if (EnableQuadPrecision) { 962 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 963 setOperationAction(ISD::FADD, MVT::f128, Legal); 964 setOperationAction(ISD::FSUB, MVT::f128, Legal); 965 setOperationAction(ISD::FDIV, MVT::f128, Legal); 966 setOperationAction(ISD::FMUL, MVT::f128, Legal); 967 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 968 // No extending loads to f128 on PPC. 969 for (MVT FPT : MVT::fp_valuetypes()) 970 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 971 setOperationAction(ISD::FMA, MVT::f128, Legal); 972 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 973 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 974 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 975 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 976 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 977 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 978 979 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 980 setOperationAction(ISD::FRINT, MVT::f128, Legal); 981 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 982 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 983 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 984 setOperationAction(ISD::FROUND, MVT::f128, Legal); 985 986 setOperationAction(ISD::SELECT, MVT::f128, Expand); 987 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 988 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 989 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 990 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 991 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 992 // No implementation for these ops for PowerPC. 993 setOperationAction(ISD::FSIN , MVT::f128, Expand); 994 setOperationAction(ISD::FCOS , MVT::f128, Expand); 995 setOperationAction(ISD::FPOW, MVT::f128, Expand); 996 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 997 setOperationAction(ISD::FREM, MVT::f128, Expand); 998 999 // Handle constrained floating-point operations of fp128 1000 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1001 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1002 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1003 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1004 } 1005 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1006 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1007 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1008 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1009 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1010 } 1011 1012 if (Subtarget.hasP9Altivec()) { 1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1014 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1015 1016 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1017 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1018 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1019 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1020 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1021 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1022 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1023 } 1024 } 1025 1026 if (Subtarget.hasQPX()) { 1027 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1028 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1029 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1030 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1031 1032 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1033 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1034 1035 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1036 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1037 1038 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1039 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1040 1041 if (!Subtarget.useCRBits()) 1042 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1043 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1044 1045 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1046 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1047 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1048 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1049 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1050 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1051 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1052 1053 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1054 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1055 1056 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1057 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1058 1059 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1060 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1061 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1062 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1063 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1064 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1065 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1066 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1067 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1068 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1069 1070 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1071 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1072 1073 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1074 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1075 1076 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1077 1078 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1079 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1080 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1081 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1082 1083 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1084 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1085 1086 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1087 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1088 1089 if (!Subtarget.useCRBits()) 1090 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1091 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1092 1093 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1094 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1095 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1096 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1097 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1098 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1099 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1100 1101 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1102 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1103 1104 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1105 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1106 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1107 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1108 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1109 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1110 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1111 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1112 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1113 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1114 1115 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1117 1118 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1119 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1120 1121 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1122 1123 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1124 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1125 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1126 1127 if (!Subtarget.useCRBits()) 1128 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1129 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1130 1131 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1132 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1133 1134 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1135 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1136 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1137 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1138 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1139 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1140 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1141 1142 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1143 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1144 1145 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1146 1147 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1148 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1149 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1150 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1151 1152 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1153 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1154 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1155 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1156 1157 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1158 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1159 1160 // These need to set FE_INEXACT, and so cannot be vectorized here. 1161 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1162 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1163 1164 if (TM.Options.UnsafeFPMath) { 1165 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1167 1168 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1169 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1170 } else { 1171 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1172 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1173 1174 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1175 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1176 } 1177 1178 // TODO: Handle constrained floating-point operations of v4f64 1179 } 1180 1181 if (Subtarget.has64BitSupport()) 1182 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1183 1184 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1185 1186 if (!isPPC64) { 1187 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1188 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1189 } 1190 1191 setBooleanContents(ZeroOrOneBooleanContent); 1192 1193 if (Subtarget.hasAltivec()) { 1194 // Altivec instructions set fields to all zeros or all ones. 1195 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1196 } 1197 1198 if (!isPPC64) { 1199 // These libcalls are not available in 32-bit. 1200 setLibcallName(RTLIB::SHL_I128, nullptr); 1201 setLibcallName(RTLIB::SRL_I128, nullptr); 1202 setLibcallName(RTLIB::SRA_I128, nullptr); 1203 } 1204 1205 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1206 1207 // We have target-specific dag combine patterns for the following nodes: 1208 setTargetDAGCombine(ISD::ADD); 1209 setTargetDAGCombine(ISD::SHL); 1210 setTargetDAGCombine(ISD::SRA); 1211 setTargetDAGCombine(ISD::SRL); 1212 setTargetDAGCombine(ISD::MUL); 1213 setTargetDAGCombine(ISD::SINT_TO_FP); 1214 setTargetDAGCombine(ISD::BUILD_VECTOR); 1215 if (Subtarget.hasFPCVT()) 1216 setTargetDAGCombine(ISD::UINT_TO_FP); 1217 setTargetDAGCombine(ISD::LOAD); 1218 setTargetDAGCombine(ISD::STORE); 1219 setTargetDAGCombine(ISD::BR_CC); 1220 if (Subtarget.useCRBits()) 1221 setTargetDAGCombine(ISD::BRCOND); 1222 setTargetDAGCombine(ISD::BSWAP); 1223 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1224 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1225 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1226 1227 setTargetDAGCombine(ISD::SIGN_EXTEND); 1228 setTargetDAGCombine(ISD::ZERO_EXTEND); 1229 setTargetDAGCombine(ISD::ANY_EXTEND); 1230 1231 setTargetDAGCombine(ISD::TRUNCATE); 1232 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1233 1234 1235 if (Subtarget.useCRBits()) { 1236 setTargetDAGCombine(ISD::TRUNCATE); 1237 setTargetDAGCombine(ISD::SETCC); 1238 setTargetDAGCombine(ISD::SELECT_CC); 1239 } 1240 1241 // Use reciprocal estimates. 1242 if (TM.Options.UnsafeFPMath) { 1243 setTargetDAGCombine(ISD::FDIV); 1244 setTargetDAGCombine(ISD::FSQRT); 1245 } 1246 1247 if (Subtarget.hasP9Altivec()) { 1248 setTargetDAGCombine(ISD::ABS); 1249 setTargetDAGCombine(ISD::VSELECT); 1250 } 1251 1252 if (EnableQuadPrecision) { 1253 setLibcallName(RTLIB::LOG_F128, "logf128"); 1254 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1255 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1256 setLibcallName(RTLIB::EXP_F128, "expf128"); 1257 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1258 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1259 setLibcallName(RTLIB::COS_F128, "cosf128"); 1260 setLibcallName(RTLIB::POW_F128, "powf128"); 1261 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1262 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1263 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1264 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1265 } 1266 1267 // With 32 condition bits, we don't need to sink (and duplicate) compares 1268 // aggressively in CodeGenPrep. 1269 if (Subtarget.useCRBits()) { 1270 setHasMultipleConditionRegisters(); 1271 setJumpIsExpensive(); 1272 } 1273 1274 setMinFunctionAlignment(Align(4)); 1275 1276 switch (Subtarget.getCPUDirective()) { 1277 default: break; 1278 case PPC::DIR_970: 1279 case PPC::DIR_A2: 1280 case PPC::DIR_E500: 1281 case PPC::DIR_E500mc: 1282 case PPC::DIR_E5500: 1283 case PPC::DIR_PWR4: 1284 case PPC::DIR_PWR5: 1285 case PPC::DIR_PWR5X: 1286 case PPC::DIR_PWR6: 1287 case PPC::DIR_PWR6X: 1288 case PPC::DIR_PWR7: 1289 case PPC::DIR_PWR8: 1290 case PPC::DIR_PWR9: 1291 case PPC::DIR_PWR_FUTURE: 1292 setPrefLoopAlignment(Align(16)); 1293 setPrefFunctionAlignment(Align(16)); 1294 break; 1295 } 1296 1297 if (Subtarget.enableMachineScheduler()) 1298 setSchedulingPreference(Sched::Source); 1299 else 1300 setSchedulingPreference(Sched::Hybrid); 1301 1302 computeRegisterProperties(STI.getRegisterInfo()); 1303 1304 // The Freescale cores do better with aggressive inlining of memcpy and 1305 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1306 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1307 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1308 MaxStoresPerMemset = 32; 1309 MaxStoresPerMemsetOptSize = 16; 1310 MaxStoresPerMemcpy = 32; 1311 MaxStoresPerMemcpyOptSize = 8; 1312 MaxStoresPerMemmove = 32; 1313 MaxStoresPerMemmoveOptSize = 8; 1314 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1315 // The A2 also benefits from (very) aggressive inlining of memcpy and 1316 // friends. The overhead of a the function call, even when warm, can be 1317 // over one hundred cycles. 1318 MaxStoresPerMemset = 128; 1319 MaxStoresPerMemcpy = 128; 1320 MaxStoresPerMemmove = 128; 1321 MaxLoadsPerMemcmp = 128; 1322 } else { 1323 MaxLoadsPerMemcmp = 8; 1324 MaxLoadsPerMemcmpOptSize = 4; 1325 } 1326 } 1327 1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1329 /// the desired ByVal argument alignment. 1330 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1331 unsigned MaxMaxAlign) { 1332 if (MaxAlign == MaxMaxAlign) 1333 return; 1334 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1335 if (MaxMaxAlign >= 32 && 1336 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1337 MaxAlign = 32; 1338 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1339 MaxAlign < 16) 1340 MaxAlign = 16; 1341 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1342 unsigned EltAlign = 0; 1343 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1344 if (EltAlign > MaxAlign) 1345 MaxAlign = EltAlign; 1346 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1347 for (auto *EltTy : STy->elements()) { 1348 unsigned EltAlign = 0; 1349 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1350 if (EltAlign > MaxAlign) 1351 MaxAlign = EltAlign; 1352 if (MaxAlign == MaxMaxAlign) 1353 break; 1354 } 1355 } 1356 } 1357 1358 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1359 /// function arguments in the caller parameter area. 1360 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1361 const DataLayout &DL) const { 1362 // 16byte and wider vectors are passed on 16byte boundary. 1363 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1364 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1365 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1366 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1367 return Align; 1368 } 1369 1370 bool PPCTargetLowering::useSoftFloat() const { 1371 return Subtarget.useSoftFloat(); 1372 } 1373 1374 bool PPCTargetLowering::hasSPE() const { 1375 return Subtarget.hasSPE(); 1376 } 1377 1378 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1379 return VT.isScalarInteger(); 1380 } 1381 1382 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1383 switch ((PPCISD::NodeType)Opcode) { 1384 case PPCISD::FIRST_NUMBER: break; 1385 case PPCISD::FSEL: return "PPCISD::FSEL"; 1386 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1387 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1388 case PPCISD::FCFID: return "PPCISD::FCFID"; 1389 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1390 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1391 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1392 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1393 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1394 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1395 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1396 case PPCISD::FP_TO_UINT_IN_VSR: 1397 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1398 case PPCISD::FP_TO_SINT_IN_VSR: 1399 return "PPCISD::FP_TO_SINT_IN_VSR"; 1400 case PPCISD::FRE: return "PPCISD::FRE"; 1401 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1402 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1403 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1404 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1405 case PPCISD::VPERM: return "PPCISD::VPERM"; 1406 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1407 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1408 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1409 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1410 case PPCISD::CMPB: return "PPCISD::CMPB"; 1411 case PPCISD::Hi: return "PPCISD::Hi"; 1412 case PPCISD::Lo: return "PPCISD::Lo"; 1413 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1414 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1415 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1416 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1417 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1418 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1419 case PPCISD::SRL: return "PPCISD::SRL"; 1420 case PPCISD::SRA: return "PPCISD::SRA"; 1421 case PPCISD::SHL: return "PPCISD::SHL"; 1422 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1423 case PPCISD::CALL: return "PPCISD::CALL"; 1424 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1425 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1426 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1427 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1428 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1429 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1430 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1431 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1432 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1433 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1434 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1435 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1436 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1437 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1438 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1439 case PPCISD::ANDI_rec_1_EQ_BIT: 1440 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1441 case PPCISD::ANDI_rec_1_GT_BIT: 1442 return "PPCISD::ANDI_rec_1_GT_BIT"; 1443 case PPCISD::VCMP: return "PPCISD::VCMP"; 1444 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1445 case PPCISD::LBRX: return "PPCISD::LBRX"; 1446 case PPCISD::STBRX: return "PPCISD::STBRX"; 1447 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1448 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1449 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1450 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1451 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1452 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1453 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1454 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1455 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1456 case PPCISD::ST_VSR_SCAL_INT: 1457 return "PPCISD::ST_VSR_SCAL_INT"; 1458 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1459 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1460 case PPCISD::BDZ: return "PPCISD::BDZ"; 1461 case PPCISD::MFFS: return "PPCISD::MFFS"; 1462 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1463 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1464 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1465 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1466 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1467 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1468 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1469 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1470 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1471 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1472 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1473 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1474 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1475 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1476 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1477 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1478 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1479 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1480 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1481 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1482 case PPCISD::SC: return "PPCISD::SC"; 1483 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1484 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1485 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1486 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1487 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1488 case PPCISD::VABSD: return "PPCISD::VABSD"; 1489 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1490 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1491 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1492 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1493 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1494 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1495 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1496 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1497 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1498 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1499 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1500 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1501 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1502 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1503 } 1504 return nullptr; 1505 } 1506 1507 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1508 EVT VT) const { 1509 if (!VT.isVector()) 1510 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1511 1512 if (Subtarget.hasQPX()) 1513 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1514 1515 return VT.changeVectorElementTypeToInteger(); 1516 } 1517 1518 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1519 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1520 return true; 1521 } 1522 1523 //===----------------------------------------------------------------------===// 1524 // Node matching predicates, for use by the tblgen matching code. 1525 //===----------------------------------------------------------------------===// 1526 1527 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1528 static bool isFloatingPointZero(SDValue Op) { 1529 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1530 return CFP->getValueAPF().isZero(); 1531 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1532 // Maybe this has already been legalized into the constant pool? 1533 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1534 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1535 return CFP->getValueAPF().isZero(); 1536 } 1537 return false; 1538 } 1539 1540 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1541 /// true if Op is undef or if it matches the specified value. 1542 static bool isConstantOrUndef(int Op, int Val) { 1543 return Op < 0 || Op == Val; 1544 } 1545 1546 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1547 /// VPKUHUM instruction. 1548 /// The ShuffleKind distinguishes between big-endian operations with 1549 /// two different inputs (0), either-endian operations with two identical 1550 /// inputs (1), and little-endian operations with two different inputs (2). 1551 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1552 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1553 SelectionDAG &DAG) { 1554 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1555 if (ShuffleKind == 0) { 1556 if (IsLE) 1557 return false; 1558 for (unsigned i = 0; i != 16; ++i) 1559 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1560 return false; 1561 } else if (ShuffleKind == 2) { 1562 if (!IsLE) 1563 return false; 1564 for (unsigned i = 0; i != 16; ++i) 1565 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1566 return false; 1567 } else if (ShuffleKind == 1) { 1568 unsigned j = IsLE ? 0 : 1; 1569 for (unsigned i = 0; i != 8; ++i) 1570 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1571 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1572 return false; 1573 } 1574 return true; 1575 } 1576 1577 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1578 /// VPKUWUM instruction. 1579 /// The ShuffleKind distinguishes between big-endian operations with 1580 /// two different inputs (0), either-endian operations with two identical 1581 /// inputs (1), and little-endian operations with two different inputs (2). 1582 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1583 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1584 SelectionDAG &DAG) { 1585 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1586 if (ShuffleKind == 0) { 1587 if (IsLE) 1588 return false; 1589 for (unsigned i = 0; i != 16; i += 2) 1590 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1591 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1592 return false; 1593 } else if (ShuffleKind == 2) { 1594 if (!IsLE) 1595 return false; 1596 for (unsigned i = 0; i != 16; i += 2) 1597 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1598 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1599 return false; 1600 } else if (ShuffleKind == 1) { 1601 unsigned j = IsLE ? 0 : 2; 1602 for (unsigned i = 0; i != 8; i += 2) 1603 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1604 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1605 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1606 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1607 return false; 1608 } 1609 return true; 1610 } 1611 1612 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1613 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1614 /// current subtarget. 1615 /// 1616 /// The ShuffleKind distinguishes between big-endian operations with 1617 /// two different inputs (0), either-endian operations with two identical 1618 /// inputs (1), and little-endian operations with two different inputs (2). 1619 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1620 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1621 SelectionDAG &DAG) { 1622 const PPCSubtarget& Subtarget = 1623 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1624 if (!Subtarget.hasP8Vector()) 1625 return false; 1626 1627 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1628 if (ShuffleKind == 0) { 1629 if (IsLE) 1630 return false; 1631 for (unsigned i = 0; i != 16; i += 4) 1632 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1633 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1634 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1635 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1636 return false; 1637 } else if (ShuffleKind == 2) { 1638 if (!IsLE) 1639 return false; 1640 for (unsigned i = 0; i != 16; i += 4) 1641 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1642 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1643 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1644 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1645 return false; 1646 } else if (ShuffleKind == 1) { 1647 unsigned j = IsLE ? 0 : 4; 1648 for (unsigned i = 0; i != 8; i += 4) 1649 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1650 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1651 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1652 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1653 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1654 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1655 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1656 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1657 return false; 1658 } 1659 return true; 1660 } 1661 1662 /// isVMerge - Common function, used to match vmrg* shuffles. 1663 /// 1664 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1665 unsigned LHSStart, unsigned RHSStart) { 1666 if (N->getValueType(0) != MVT::v16i8) 1667 return false; 1668 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1669 "Unsupported merge size!"); 1670 1671 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1672 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1673 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1674 LHSStart+j+i*UnitSize) || 1675 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1676 RHSStart+j+i*UnitSize)) 1677 return false; 1678 } 1679 return true; 1680 } 1681 1682 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1683 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1684 /// The ShuffleKind distinguishes between big-endian merges with two 1685 /// different inputs (0), either-endian merges with two identical inputs (1), 1686 /// and little-endian merges with two different inputs (2). For the latter, 1687 /// the input operands are swapped (see PPCInstrAltivec.td). 1688 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1689 unsigned ShuffleKind, SelectionDAG &DAG) { 1690 if (DAG.getDataLayout().isLittleEndian()) { 1691 if (ShuffleKind == 1) // unary 1692 return isVMerge(N, UnitSize, 0, 0); 1693 else if (ShuffleKind == 2) // swapped 1694 return isVMerge(N, UnitSize, 0, 16); 1695 else 1696 return false; 1697 } else { 1698 if (ShuffleKind == 1) // unary 1699 return isVMerge(N, UnitSize, 8, 8); 1700 else if (ShuffleKind == 0) // normal 1701 return isVMerge(N, UnitSize, 8, 24); 1702 else 1703 return false; 1704 } 1705 } 1706 1707 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1708 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1709 /// The ShuffleKind distinguishes between big-endian merges with two 1710 /// different inputs (0), either-endian merges with two identical inputs (1), 1711 /// and little-endian merges with two different inputs (2). For the latter, 1712 /// the input operands are swapped (see PPCInstrAltivec.td). 1713 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1714 unsigned ShuffleKind, SelectionDAG &DAG) { 1715 if (DAG.getDataLayout().isLittleEndian()) { 1716 if (ShuffleKind == 1) // unary 1717 return isVMerge(N, UnitSize, 8, 8); 1718 else if (ShuffleKind == 2) // swapped 1719 return isVMerge(N, UnitSize, 8, 24); 1720 else 1721 return false; 1722 } else { 1723 if (ShuffleKind == 1) // unary 1724 return isVMerge(N, UnitSize, 0, 0); 1725 else if (ShuffleKind == 0) // normal 1726 return isVMerge(N, UnitSize, 0, 16); 1727 else 1728 return false; 1729 } 1730 } 1731 1732 /** 1733 * Common function used to match vmrgew and vmrgow shuffles 1734 * 1735 * The indexOffset determines whether to look for even or odd words in 1736 * the shuffle mask. This is based on the of the endianness of the target 1737 * machine. 1738 * - Little Endian: 1739 * - Use offset of 0 to check for odd elements 1740 * - Use offset of 4 to check for even elements 1741 * - Big Endian: 1742 * - Use offset of 0 to check for even elements 1743 * - Use offset of 4 to check for odd elements 1744 * A detailed description of the vector element ordering for little endian and 1745 * big endian can be found at 1746 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1747 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1748 * compiler differences mean to you 1749 * 1750 * The mask to the shuffle vector instruction specifies the indices of the 1751 * elements from the two input vectors to place in the result. The elements are 1752 * numbered in array-access order, starting with the first vector. These vectors 1753 * are always of type v16i8, thus each vector will contain 16 elements of size 1754 * 8. More info on the shuffle vector can be found in the 1755 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1756 * Language Reference. 1757 * 1758 * The RHSStartValue indicates whether the same input vectors are used (unary) 1759 * or two different input vectors are used, based on the following: 1760 * - If the instruction uses the same vector for both inputs, the range of the 1761 * indices will be 0 to 15. In this case, the RHSStart value passed should 1762 * be 0. 1763 * - If the instruction has two different vectors then the range of the 1764 * indices will be 0 to 31. In this case, the RHSStart value passed should 1765 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1766 * to 31 specify elements in the second vector). 1767 * 1768 * \param[in] N The shuffle vector SD Node to analyze 1769 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1770 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1771 * vector to the shuffle_vector instruction 1772 * \return true iff this shuffle vector represents an even or odd word merge 1773 */ 1774 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1775 unsigned RHSStartValue) { 1776 if (N->getValueType(0) != MVT::v16i8) 1777 return false; 1778 1779 for (unsigned i = 0; i < 2; ++i) 1780 for (unsigned j = 0; j < 4; ++j) 1781 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1782 i*RHSStartValue+j+IndexOffset) || 1783 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1784 i*RHSStartValue+j+IndexOffset+8)) 1785 return false; 1786 return true; 1787 } 1788 1789 /** 1790 * Determine if the specified shuffle mask is suitable for the vmrgew or 1791 * vmrgow instructions. 1792 * 1793 * \param[in] N The shuffle vector SD Node to analyze 1794 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1795 * \param[in] ShuffleKind Identify the type of merge: 1796 * - 0 = big-endian merge with two different inputs; 1797 * - 1 = either-endian merge with two identical inputs; 1798 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1799 * little-endian merges). 1800 * \param[in] DAG The current SelectionDAG 1801 * \return true iff this shuffle mask 1802 */ 1803 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1804 unsigned ShuffleKind, SelectionDAG &DAG) { 1805 if (DAG.getDataLayout().isLittleEndian()) { 1806 unsigned indexOffset = CheckEven ? 4 : 0; 1807 if (ShuffleKind == 1) // Unary 1808 return isVMerge(N, indexOffset, 0); 1809 else if (ShuffleKind == 2) // swapped 1810 return isVMerge(N, indexOffset, 16); 1811 else 1812 return false; 1813 } 1814 else { 1815 unsigned indexOffset = CheckEven ? 0 : 4; 1816 if (ShuffleKind == 1) // Unary 1817 return isVMerge(N, indexOffset, 0); 1818 else if (ShuffleKind == 0) // Normal 1819 return isVMerge(N, indexOffset, 16); 1820 else 1821 return false; 1822 } 1823 return false; 1824 } 1825 1826 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1827 /// amount, otherwise return -1. 1828 /// The ShuffleKind distinguishes between big-endian operations with two 1829 /// different inputs (0), either-endian operations with two identical inputs 1830 /// (1), and little-endian operations with two different inputs (2). For the 1831 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1832 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1833 SelectionDAG &DAG) { 1834 if (N->getValueType(0) != MVT::v16i8) 1835 return -1; 1836 1837 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1838 1839 // Find the first non-undef value in the shuffle mask. 1840 unsigned i; 1841 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1842 /*search*/; 1843 1844 if (i == 16) return -1; // all undef. 1845 1846 // Otherwise, check to see if the rest of the elements are consecutively 1847 // numbered from this value. 1848 unsigned ShiftAmt = SVOp->getMaskElt(i); 1849 if (ShiftAmt < i) return -1; 1850 1851 ShiftAmt -= i; 1852 bool isLE = DAG.getDataLayout().isLittleEndian(); 1853 1854 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1855 // Check the rest of the elements to see if they are consecutive. 1856 for (++i; i != 16; ++i) 1857 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1858 return -1; 1859 } else if (ShuffleKind == 1) { 1860 // Check the rest of the elements to see if they are consecutive. 1861 for (++i; i != 16; ++i) 1862 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1863 return -1; 1864 } else 1865 return -1; 1866 1867 if (isLE) 1868 ShiftAmt = 16 - ShiftAmt; 1869 1870 return ShiftAmt; 1871 } 1872 1873 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1874 /// specifies a splat of a single element that is suitable for input to 1875 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1876 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1877 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1878 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1879 1880 // The consecutive indices need to specify an element, not part of two 1881 // different elements. So abandon ship early if this isn't the case. 1882 if (N->getMaskElt(0) % EltSize != 0) 1883 return false; 1884 1885 // This is a splat operation if each element of the permute is the same, and 1886 // if the value doesn't reference the second vector. 1887 unsigned ElementBase = N->getMaskElt(0); 1888 1889 // FIXME: Handle UNDEF elements too! 1890 if (ElementBase >= 16) 1891 return false; 1892 1893 // Check that the indices are consecutive, in the case of a multi-byte element 1894 // splatted with a v16i8 mask. 1895 for (unsigned i = 1; i != EltSize; ++i) 1896 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1897 return false; 1898 1899 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1900 if (N->getMaskElt(i) < 0) continue; 1901 for (unsigned j = 0; j != EltSize; ++j) 1902 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1903 return false; 1904 } 1905 return true; 1906 } 1907 1908 /// Check that the mask is shuffling N byte elements. Within each N byte 1909 /// element of the mask, the indices could be either in increasing or 1910 /// decreasing order as long as they are consecutive. 1911 /// \param[in] N the shuffle vector SD Node to analyze 1912 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1913 /// Word/DoubleWord/QuadWord). 1914 /// \param[in] StepLen the delta indices number among the N byte element, if 1915 /// the mask is in increasing/decreasing order then it is 1/-1. 1916 /// \return true iff the mask is shuffling N byte elements. 1917 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1918 int StepLen) { 1919 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1920 "Unexpected element width."); 1921 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1922 1923 unsigned NumOfElem = 16 / Width; 1924 unsigned MaskVal[16]; // Width is never greater than 16 1925 for (unsigned i = 0; i < NumOfElem; ++i) { 1926 MaskVal[0] = N->getMaskElt(i * Width); 1927 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1928 return false; 1929 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1930 return false; 1931 } 1932 1933 for (unsigned int j = 1; j < Width; ++j) { 1934 MaskVal[j] = N->getMaskElt(i * Width + j); 1935 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1936 return false; 1937 } 1938 } 1939 } 1940 1941 return true; 1942 } 1943 1944 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1945 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1946 if (!isNByteElemShuffleMask(N, 4, 1)) 1947 return false; 1948 1949 // Now we look at mask elements 0,4,8,12 1950 unsigned M0 = N->getMaskElt(0) / 4; 1951 unsigned M1 = N->getMaskElt(4) / 4; 1952 unsigned M2 = N->getMaskElt(8) / 4; 1953 unsigned M3 = N->getMaskElt(12) / 4; 1954 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1955 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1956 1957 // Below, let H and L be arbitrary elements of the shuffle mask 1958 // where H is in the range [4,7] and L is in the range [0,3]. 1959 // H, 1, 2, 3 or L, 5, 6, 7 1960 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1961 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1962 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1963 InsertAtByte = IsLE ? 12 : 0; 1964 Swap = M0 < 4; 1965 return true; 1966 } 1967 // 0, H, 2, 3 or 4, L, 6, 7 1968 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1969 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1970 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1971 InsertAtByte = IsLE ? 8 : 4; 1972 Swap = M1 < 4; 1973 return true; 1974 } 1975 // 0, 1, H, 3 or 4, 5, L, 7 1976 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1977 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1978 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1979 InsertAtByte = IsLE ? 4 : 8; 1980 Swap = M2 < 4; 1981 return true; 1982 } 1983 // 0, 1, 2, H or 4, 5, 6, L 1984 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1985 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1986 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1987 InsertAtByte = IsLE ? 0 : 12; 1988 Swap = M3 < 4; 1989 return true; 1990 } 1991 1992 // If both vector operands for the shuffle are the same vector, the mask will 1993 // contain only elements from the first one and the second one will be undef. 1994 if (N->getOperand(1).isUndef()) { 1995 ShiftElts = 0; 1996 Swap = true; 1997 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1998 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1999 InsertAtByte = IsLE ? 12 : 0; 2000 return true; 2001 } 2002 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2003 InsertAtByte = IsLE ? 8 : 4; 2004 return true; 2005 } 2006 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2007 InsertAtByte = IsLE ? 4 : 8; 2008 return true; 2009 } 2010 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2011 InsertAtByte = IsLE ? 0 : 12; 2012 return true; 2013 } 2014 } 2015 2016 return false; 2017 } 2018 2019 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2020 bool &Swap, bool IsLE) { 2021 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2022 // Ensure each byte index of the word is consecutive. 2023 if (!isNByteElemShuffleMask(N, 4, 1)) 2024 return false; 2025 2026 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2027 unsigned M0 = N->getMaskElt(0) / 4; 2028 unsigned M1 = N->getMaskElt(4) / 4; 2029 unsigned M2 = N->getMaskElt(8) / 4; 2030 unsigned M3 = N->getMaskElt(12) / 4; 2031 2032 // If both vector operands for the shuffle are the same vector, the mask will 2033 // contain only elements from the first one and the second one will be undef. 2034 if (N->getOperand(1).isUndef()) { 2035 assert(M0 < 4 && "Indexing into an undef vector?"); 2036 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2037 return false; 2038 2039 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2040 Swap = false; 2041 return true; 2042 } 2043 2044 // Ensure each word index of the ShuffleVector Mask is consecutive. 2045 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2046 return false; 2047 2048 if (IsLE) { 2049 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2050 // Input vectors don't need to be swapped if the leading element 2051 // of the result is one of the 3 left elements of the second vector 2052 // (or if there is no shift to be done at all). 2053 Swap = false; 2054 ShiftElts = (8 - M0) % 8; 2055 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2056 // Input vectors need to be swapped if the leading element 2057 // of the result is one of the 3 left elements of the first vector 2058 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2059 Swap = true; 2060 ShiftElts = (4 - M0) % 4; 2061 } 2062 2063 return true; 2064 } else { // BE 2065 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2066 // Input vectors don't need to be swapped if the leading element 2067 // of the result is one of the 4 elements of the first vector. 2068 Swap = false; 2069 ShiftElts = M0; 2070 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2071 // Input vectors need to be swapped if the leading element 2072 // of the result is one of the 4 elements of the right vector. 2073 Swap = true; 2074 ShiftElts = M0 - 4; 2075 } 2076 2077 return true; 2078 } 2079 } 2080 2081 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2082 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2083 2084 if (!isNByteElemShuffleMask(N, Width, -1)) 2085 return false; 2086 2087 for (int i = 0; i < 16; i += Width) 2088 if (N->getMaskElt(i) != i + Width - 1) 2089 return false; 2090 2091 return true; 2092 } 2093 2094 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2095 return isXXBRShuffleMaskHelper(N, 2); 2096 } 2097 2098 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2099 return isXXBRShuffleMaskHelper(N, 4); 2100 } 2101 2102 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2103 return isXXBRShuffleMaskHelper(N, 8); 2104 } 2105 2106 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2107 return isXXBRShuffleMaskHelper(N, 16); 2108 } 2109 2110 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2111 /// if the inputs to the instruction should be swapped and set \p DM to the 2112 /// value for the immediate. 2113 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2114 /// AND element 0 of the result comes from the first input (LE) or second input 2115 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2116 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2117 /// mask. 2118 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2119 bool &Swap, bool IsLE) { 2120 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2121 2122 // Ensure each byte index of the double word is consecutive. 2123 if (!isNByteElemShuffleMask(N, 8, 1)) 2124 return false; 2125 2126 unsigned M0 = N->getMaskElt(0) / 8; 2127 unsigned M1 = N->getMaskElt(8) / 8; 2128 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2129 2130 // If both vector operands for the shuffle are the same vector, the mask will 2131 // contain only elements from the first one and the second one will be undef. 2132 if (N->getOperand(1).isUndef()) { 2133 if ((M0 | M1) < 2) { 2134 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2135 Swap = false; 2136 return true; 2137 } else 2138 return false; 2139 } 2140 2141 if (IsLE) { 2142 if (M0 > 1 && M1 < 2) { 2143 Swap = false; 2144 } else if (M0 < 2 && M1 > 1) { 2145 M0 = (M0 + 2) % 4; 2146 M1 = (M1 + 2) % 4; 2147 Swap = true; 2148 } else 2149 return false; 2150 2151 // Note: if control flow comes here that means Swap is already set above 2152 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2153 return true; 2154 } else { // BE 2155 if (M0 < 2 && M1 > 1) { 2156 Swap = false; 2157 } else if (M0 > 1 && M1 < 2) { 2158 M0 = (M0 + 2) % 4; 2159 M1 = (M1 + 2) % 4; 2160 Swap = true; 2161 } else 2162 return false; 2163 2164 // Note: if control flow comes here that means Swap is already set above 2165 DM = (M0 << 1) + (M1 & 1); 2166 return true; 2167 } 2168 } 2169 2170 2171 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2172 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2173 /// elements are counted from the left of the vector register). 2174 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2175 SelectionDAG &DAG) { 2176 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2177 assert(isSplatShuffleMask(SVOp, EltSize)); 2178 if (DAG.getDataLayout().isLittleEndian()) 2179 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2180 else 2181 return SVOp->getMaskElt(0) / EltSize; 2182 } 2183 2184 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2185 /// by using a vspltis[bhw] instruction of the specified element size, return 2186 /// the constant being splatted. The ByteSize field indicates the number of 2187 /// bytes of each element [124] -> [bhw]. 2188 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2189 SDValue OpVal(nullptr, 0); 2190 2191 // If ByteSize of the splat is bigger than the element size of the 2192 // build_vector, then we have a case where we are checking for a splat where 2193 // multiple elements of the buildvector are folded together into a single 2194 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2195 unsigned EltSize = 16/N->getNumOperands(); 2196 if (EltSize < ByteSize) { 2197 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2198 SDValue UniquedVals[4]; 2199 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2200 2201 // See if all of the elements in the buildvector agree across. 2202 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2203 if (N->getOperand(i).isUndef()) continue; 2204 // If the element isn't a constant, bail fully out. 2205 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2206 2207 if (!UniquedVals[i&(Multiple-1)].getNode()) 2208 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2209 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2210 return SDValue(); // no match. 2211 } 2212 2213 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2214 // either constant or undef values that are identical for each chunk. See 2215 // if these chunks can form into a larger vspltis*. 2216 2217 // Check to see if all of the leading entries are either 0 or -1. If 2218 // neither, then this won't fit into the immediate field. 2219 bool LeadingZero = true; 2220 bool LeadingOnes = true; 2221 for (unsigned i = 0; i != Multiple-1; ++i) { 2222 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2223 2224 LeadingZero &= isNullConstant(UniquedVals[i]); 2225 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2226 } 2227 // Finally, check the least significant entry. 2228 if (LeadingZero) { 2229 if (!UniquedVals[Multiple-1].getNode()) 2230 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2231 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2232 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2233 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2234 } 2235 if (LeadingOnes) { 2236 if (!UniquedVals[Multiple-1].getNode()) 2237 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2238 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2239 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2240 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2241 } 2242 2243 return SDValue(); 2244 } 2245 2246 // Check to see if this buildvec has a single non-undef value in its elements. 2247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2248 if (N->getOperand(i).isUndef()) continue; 2249 if (!OpVal.getNode()) 2250 OpVal = N->getOperand(i); 2251 else if (OpVal != N->getOperand(i)) 2252 return SDValue(); 2253 } 2254 2255 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2256 2257 unsigned ValSizeInBytes = EltSize; 2258 uint64_t Value = 0; 2259 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2260 Value = CN->getZExtValue(); 2261 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2262 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2263 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2264 } 2265 2266 // If the splat value is larger than the element value, then we can never do 2267 // this splat. The only case that we could fit the replicated bits into our 2268 // immediate field for would be zero, and we prefer to use vxor for it. 2269 if (ValSizeInBytes < ByteSize) return SDValue(); 2270 2271 // If the element value is larger than the splat value, check if it consists 2272 // of a repeated bit pattern of size ByteSize. 2273 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2274 return SDValue(); 2275 2276 // Properly sign extend the value. 2277 int MaskVal = SignExtend32(Value, ByteSize * 8); 2278 2279 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2280 if (MaskVal == 0) return SDValue(); 2281 2282 // Finally, if this value fits in a 5 bit sext field, return it 2283 if (SignExtend32<5>(MaskVal) == MaskVal) 2284 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2285 return SDValue(); 2286 } 2287 2288 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2289 /// amount, otherwise return -1. 2290 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2291 EVT VT = N->getValueType(0); 2292 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2293 return -1; 2294 2295 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2296 2297 // Find the first non-undef value in the shuffle mask. 2298 unsigned i; 2299 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2300 /*search*/; 2301 2302 if (i == 4) return -1; // all undef. 2303 2304 // Otherwise, check to see if the rest of the elements are consecutively 2305 // numbered from this value. 2306 unsigned ShiftAmt = SVOp->getMaskElt(i); 2307 if (ShiftAmt < i) return -1; 2308 ShiftAmt -= i; 2309 2310 // Check the rest of the elements to see if they are consecutive. 2311 for (++i; i != 4; ++i) 2312 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2313 return -1; 2314 2315 return ShiftAmt; 2316 } 2317 2318 //===----------------------------------------------------------------------===// 2319 // Addressing Mode Selection 2320 //===----------------------------------------------------------------------===// 2321 2322 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2323 /// or 64-bit immediate, and if the value can be accurately represented as a 2324 /// sign extension from a 16-bit value. If so, this returns true and the 2325 /// immediate. 2326 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2327 if (!isa<ConstantSDNode>(N)) 2328 return false; 2329 2330 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2331 if (N->getValueType(0) == MVT::i32) 2332 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2333 else 2334 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2335 } 2336 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2337 return isIntS16Immediate(Op.getNode(), Imm); 2338 } 2339 2340 2341 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2342 /// be represented as an indexed [r+r] operation. 2343 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2344 SDValue &Index, 2345 SelectionDAG &DAG) const { 2346 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2347 UI != E; ++UI) { 2348 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2349 if (Memop->getMemoryVT() == MVT::f64) { 2350 Base = N.getOperand(0); 2351 Index = N.getOperand(1); 2352 return true; 2353 } 2354 } 2355 } 2356 return false; 2357 } 2358 2359 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2360 /// can be represented as an indexed [r+r] operation. Returns false if it 2361 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2362 /// non-zero and N can be represented by a base register plus a signed 16-bit 2363 /// displacement, make a more precise judgement by checking (displacement % \p 2364 /// EncodingAlignment). 2365 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2366 SDValue &Index, SelectionDAG &DAG, 2367 unsigned EncodingAlignment) const { 2368 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2369 // a [pc+imm]. 2370 if (SelectAddressPCRel(N, Base)) 2371 return false; 2372 2373 int16_t imm = 0; 2374 if (N.getOpcode() == ISD::ADD) { 2375 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2376 // SPE load/store can only handle 8-bit offsets. 2377 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2378 return true; 2379 if (isIntS16Immediate(N.getOperand(1), imm) && 2380 (!EncodingAlignment || !(imm % EncodingAlignment))) 2381 return false; // r+i 2382 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2383 return false; // r+i 2384 2385 Base = N.getOperand(0); 2386 Index = N.getOperand(1); 2387 return true; 2388 } else if (N.getOpcode() == ISD::OR) { 2389 if (isIntS16Immediate(N.getOperand(1), imm) && 2390 (!EncodingAlignment || !(imm % EncodingAlignment))) 2391 return false; // r+i can fold it if we can. 2392 2393 // If this is an or of disjoint bitfields, we can codegen this as an add 2394 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2395 // disjoint. 2396 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2397 2398 if (LHSKnown.Zero.getBoolValue()) { 2399 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2400 // If all of the bits are known zero on the LHS or RHS, the add won't 2401 // carry. 2402 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2403 Base = N.getOperand(0); 2404 Index = N.getOperand(1); 2405 return true; 2406 } 2407 } 2408 } 2409 2410 return false; 2411 } 2412 2413 // If we happen to be doing an i64 load or store into a stack slot that has 2414 // less than a 4-byte alignment, then the frame-index elimination may need to 2415 // use an indexed load or store instruction (because the offset may not be a 2416 // multiple of 4). The extra register needed to hold the offset comes from the 2417 // register scavenger, and it is possible that the scavenger will need to use 2418 // an emergency spill slot. As a result, we need to make sure that a spill slot 2419 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2420 // stack slot. 2421 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2422 // FIXME: This does not handle the LWA case. 2423 if (VT != MVT::i64) 2424 return; 2425 2426 // NOTE: We'll exclude negative FIs here, which come from argument 2427 // lowering, because there are no known test cases triggering this problem 2428 // using packed structures (or similar). We can remove this exclusion if 2429 // we find such a test case. The reason why this is so test-case driven is 2430 // because this entire 'fixup' is only to prevent crashes (from the 2431 // register scavenger) on not-really-valid inputs. For example, if we have: 2432 // %a = alloca i1 2433 // %b = bitcast i1* %a to i64* 2434 // store i64* a, i64 b 2435 // then the store should really be marked as 'align 1', but is not. If it 2436 // were marked as 'align 1' then the indexed form would have been 2437 // instruction-selected initially, and the problem this 'fixup' is preventing 2438 // won't happen regardless. 2439 if (FrameIdx < 0) 2440 return; 2441 2442 MachineFunction &MF = DAG.getMachineFunction(); 2443 MachineFrameInfo &MFI = MF.getFrameInfo(); 2444 2445 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2446 return; 2447 2448 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2449 FuncInfo->setHasNonRISpills(); 2450 } 2451 2452 /// Returns true if the address N can be represented by a base register plus 2453 /// a signed 16-bit displacement [r+imm], and if it is not better 2454 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2455 /// displacements that are multiples of that value. 2456 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2457 SDValue &Base, 2458 SelectionDAG &DAG, 2459 unsigned EncodingAlignment) const { 2460 // FIXME dl should come from parent load or store, not from address 2461 SDLoc dl(N); 2462 2463 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2464 // a [pc+imm]. 2465 if (SelectAddressPCRel(N, Base)) 2466 return false; 2467 2468 // If this can be more profitably realized as r+r, fail. 2469 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2470 return false; 2471 2472 if (N.getOpcode() == ISD::ADD) { 2473 int16_t imm = 0; 2474 if (isIntS16Immediate(N.getOperand(1), imm) && 2475 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2476 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2477 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2478 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2479 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2480 } else { 2481 Base = N.getOperand(0); 2482 } 2483 return true; // [r+i] 2484 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2485 // Match LOAD (ADD (X, Lo(G))). 2486 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2487 && "Cannot handle constant offsets yet!"); 2488 Disp = N.getOperand(1).getOperand(0); // The global address. 2489 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2490 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2491 Disp.getOpcode() == ISD::TargetConstantPool || 2492 Disp.getOpcode() == ISD::TargetJumpTable); 2493 Base = N.getOperand(0); 2494 return true; // [&g+r] 2495 } 2496 } else if (N.getOpcode() == ISD::OR) { 2497 int16_t imm = 0; 2498 if (isIntS16Immediate(N.getOperand(1), imm) && 2499 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2500 // If this is an or of disjoint bitfields, we can codegen this as an add 2501 // (for better address arithmetic) if the LHS and RHS of the OR are 2502 // provably disjoint. 2503 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2504 2505 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2506 // If all of the bits are known zero on the LHS or RHS, the add won't 2507 // carry. 2508 if (FrameIndexSDNode *FI = 2509 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2510 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2511 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2512 } else { 2513 Base = N.getOperand(0); 2514 } 2515 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2516 return true; 2517 } 2518 } 2519 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2520 // Loading from a constant address. 2521 2522 // If this address fits entirely in a 16-bit sext immediate field, codegen 2523 // this as "d, 0" 2524 int16_t Imm; 2525 if (isIntS16Immediate(CN, Imm) && 2526 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2527 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2528 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2529 CN->getValueType(0)); 2530 return true; 2531 } 2532 2533 // Handle 32-bit sext immediates with LIS + addr mode. 2534 if ((CN->getValueType(0) == MVT::i32 || 2535 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2536 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2537 int Addr = (int)CN->getZExtValue(); 2538 2539 // Otherwise, break this down into an LIS + disp. 2540 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2541 2542 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2543 MVT::i32); 2544 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2545 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2546 return true; 2547 } 2548 } 2549 2550 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2551 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2552 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2553 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2554 } else 2555 Base = N; 2556 return true; // [r+0] 2557 } 2558 2559 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2560 /// represented as an indexed [r+r] operation. 2561 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2562 SDValue &Index, 2563 SelectionDAG &DAG) const { 2564 // Check to see if we can easily represent this as an [r+r] address. This 2565 // will fail if it thinks that the address is more profitably represented as 2566 // reg+imm, e.g. where imm = 0. 2567 if (SelectAddressRegReg(N, Base, Index, DAG)) 2568 return true; 2569 2570 // If the address is the result of an add, we will utilize the fact that the 2571 // address calculation includes an implicit add. However, we can reduce 2572 // register pressure if we do not materialize a constant just for use as the 2573 // index register. We only get rid of the add if it is not an add of a 2574 // value and a 16-bit signed constant and both have a single use. 2575 int16_t imm = 0; 2576 if (N.getOpcode() == ISD::ADD && 2577 (!isIntS16Immediate(N.getOperand(1), imm) || 2578 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2579 Base = N.getOperand(0); 2580 Index = N.getOperand(1); 2581 return true; 2582 } 2583 2584 // Otherwise, do it the hard way, using R0 as the base register. 2585 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2586 N.getValueType()); 2587 Index = N; 2588 return true; 2589 } 2590 2591 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2592 Ty *PCRelCand = dyn_cast<Ty>(N); 2593 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2594 } 2595 2596 /// Returns true if this address is a PC Relative address. 2597 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2598 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2599 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2600 // This is a materialize PC Relative node. Always select this as PC Relative. 2601 Base = N; 2602 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2603 return true; 2604 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2605 isValidPCRelNode<GlobalAddressSDNode>(N) || 2606 isValidPCRelNode<JumpTableSDNode>(N) || 2607 isValidPCRelNode<BlockAddressSDNode>(N)) 2608 return true; 2609 return false; 2610 } 2611 2612 /// Returns true if we should use a direct load into vector instruction 2613 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2614 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2615 2616 // If there are any other uses other than scalar to vector, then we should 2617 // keep it as a scalar load -> direct move pattern to prevent multiple 2618 // loads. 2619 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2620 if (!LD) 2621 return false; 2622 2623 EVT MemVT = LD->getMemoryVT(); 2624 if (!MemVT.isSimple()) 2625 return false; 2626 switch(MemVT.getSimpleVT().SimpleTy) { 2627 case MVT::i64: 2628 break; 2629 case MVT::i32: 2630 if (!ST.hasP8Vector()) 2631 return false; 2632 break; 2633 case MVT::i16: 2634 case MVT::i8: 2635 if (!ST.hasP9Vector()) 2636 return false; 2637 break; 2638 default: 2639 return false; 2640 } 2641 2642 SDValue LoadedVal(N, 0); 2643 if (!LoadedVal.hasOneUse()) 2644 return false; 2645 2646 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2647 UI != UE; ++UI) 2648 if (UI.getUse().get().getResNo() == 0 && 2649 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2650 return false; 2651 2652 return true; 2653 } 2654 2655 /// getPreIndexedAddressParts - returns true by value, base pointer and 2656 /// offset pointer and addressing mode by reference if the node's address 2657 /// can be legally represented as pre-indexed load / store address. 2658 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2659 SDValue &Offset, 2660 ISD::MemIndexedMode &AM, 2661 SelectionDAG &DAG) const { 2662 if (DisablePPCPreinc) return false; 2663 2664 bool isLoad = true; 2665 SDValue Ptr; 2666 EVT VT; 2667 unsigned Alignment; 2668 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2669 Ptr = LD->getBasePtr(); 2670 VT = LD->getMemoryVT(); 2671 Alignment = LD->getAlignment(); 2672 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2673 Ptr = ST->getBasePtr(); 2674 VT = ST->getMemoryVT(); 2675 Alignment = ST->getAlignment(); 2676 isLoad = false; 2677 } else 2678 return false; 2679 2680 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2681 // instructions because we can fold these into a more efficient instruction 2682 // instead, (such as LXSD). 2683 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2684 return false; 2685 } 2686 2687 // PowerPC doesn't have preinc load/store instructions for vectors (except 2688 // for QPX, which does have preinc r+r forms). 2689 if (VT.isVector()) { 2690 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2691 return false; 2692 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2693 AM = ISD::PRE_INC; 2694 return true; 2695 } 2696 } 2697 2698 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2699 // Common code will reject creating a pre-inc form if the base pointer 2700 // is a frame index, or if N is a store and the base pointer is either 2701 // the same as or a predecessor of the value being stored. Check for 2702 // those situations here, and try with swapped Base/Offset instead. 2703 bool Swap = false; 2704 2705 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2706 Swap = true; 2707 else if (!isLoad) { 2708 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2709 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2710 Swap = true; 2711 } 2712 2713 if (Swap) 2714 std::swap(Base, Offset); 2715 2716 AM = ISD::PRE_INC; 2717 return true; 2718 } 2719 2720 // LDU/STU can only handle immediates that are a multiple of 4. 2721 if (VT != MVT::i64) { 2722 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2723 return false; 2724 } else { 2725 // LDU/STU need an address with at least 4-byte alignment. 2726 if (Alignment < 4) 2727 return false; 2728 2729 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2730 return false; 2731 } 2732 2733 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2734 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2735 // sext i32 to i64 when addr mode is r+i. 2736 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2737 LD->getExtensionType() == ISD::SEXTLOAD && 2738 isa<ConstantSDNode>(Offset)) 2739 return false; 2740 } 2741 2742 AM = ISD::PRE_INC; 2743 return true; 2744 } 2745 2746 //===----------------------------------------------------------------------===// 2747 // LowerOperation implementation 2748 //===----------------------------------------------------------------------===// 2749 2750 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2751 /// and LoOpFlags to the target MO flags. 2752 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2753 unsigned &HiOpFlags, unsigned &LoOpFlags, 2754 const GlobalValue *GV = nullptr) { 2755 HiOpFlags = PPCII::MO_HA; 2756 LoOpFlags = PPCII::MO_LO; 2757 2758 // Don't use the pic base if not in PIC relocation model. 2759 if (IsPIC) { 2760 HiOpFlags |= PPCII::MO_PIC_FLAG; 2761 LoOpFlags |= PPCII::MO_PIC_FLAG; 2762 } 2763 } 2764 2765 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2766 SelectionDAG &DAG) { 2767 SDLoc DL(HiPart); 2768 EVT PtrVT = HiPart.getValueType(); 2769 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2770 2771 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2772 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2773 2774 // With PIC, the first instruction is actually "GR+hi(&G)". 2775 if (isPIC) 2776 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2777 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2778 2779 // Generate non-pic code that has direct accesses to the constant pool. 2780 // The address of the global is just (hi(&g)+lo(&g)). 2781 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2782 } 2783 2784 static void setUsesTOCBasePtr(MachineFunction &MF) { 2785 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2786 FuncInfo->setUsesTOCBasePtr(); 2787 } 2788 2789 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2790 setUsesTOCBasePtr(DAG.getMachineFunction()); 2791 } 2792 2793 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2794 SDValue GA) const { 2795 const bool Is64Bit = Subtarget.isPPC64(); 2796 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2797 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2798 : Subtarget.isAIXABI() 2799 ? DAG.getRegister(PPC::R2, VT) 2800 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2801 SDValue Ops[] = { GA, Reg }; 2802 return DAG.getMemIntrinsicNode( 2803 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2804 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2805 MachineMemOperand::MOLoad); 2806 } 2807 2808 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2809 SelectionDAG &DAG) const { 2810 EVT PtrVT = Op.getValueType(); 2811 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2812 const Constant *C = CP->getConstVal(); 2813 2814 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2815 // The actual address of the GlobalValue is stored in the TOC. 2816 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2817 if (Subtarget.isUsingPCRelativeCalls()) { 2818 SDLoc DL(CP); 2819 EVT Ty = getPointerTy(DAG.getDataLayout()); 2820 SDValue ConstPool = DAG.getTargetConstantPool(C, Ty, 2821 CP->getAlignment(), 2822 CP->getOffset(), 2823 PPCII::MO_PCREL_FLAG); 2824 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2825 } 2826 setUsesTOCBasePtr(DAG); 2827 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2828 return getTOCEntry(DAG, SDLoc(CP), GA); 2829 } 2830 2831 unsigned MOHiFlag, MOLoFlag; 2832 bool IsPIC = isPositionIndependent(); 2833 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2834 2835 if (IsPIC && Subtarget.isSVR4ABI()) { 2836 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2837 PPCII::MO_PIC_FLAG); 2838 return getTOCEntry(DAG, SDLoc(CP), GA); 2839 } 2840 2841 SDValue CPIHi = 2842 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2843 SDValue CPILo = 2844 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2845 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2846 } 2847 2848 // For 64-bit PowerPC, prefer the more compact relative encodings. 2849 // This trades 32 bits per jump table entry for one or two instructions 2850 // on the jump site. 2851 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2852 if (isJumpTableRelative()) 2853 return MachineJumpTableInfo::EK_LabelDifference32; 2854 2855 return TargetLowering::getJumpTableEncoding(); 2856 } 2857 2858 bool PPCTargetLowering::isJumpTableRelative() const { 2859 if (UseAbsoluteJumpTables) 2860 return false; 2861 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2862 return true; 2863 return TargetLowering::isJumpTableRelative(); 2864 } 2865 2866 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2867 SelectionDAG &DAG) const { 2868 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2869 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2870 2871 switch (getTargetMachine().getCodeModel()) { 2872 case CodeModel::Small: 2873 case CodeModel::Medium: 2874 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2875 default: 2876 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2877 getPointerTy(DAG.getDataLayout())); 2878 } 2879 } 2880 2881 const MCExpr * 2882 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2883 unsigned JTI, 2884 MCContext &Ctx) const { 2885 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2886 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2887 2888 switch (getTargetMachine().getCodeModel()) { 2889 case CodeModel::Small: 2890 case CodeModel::Medium: 2891 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2892 default: 2893 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2894 } 2895 } 2896 2897 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2898 EVT PtrVT = Op.getValueType(); 2899 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2900 2901 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2902 if (Subtarget.isUsingPCRelativeCalls()) { 2903 SDLoc DL(JT); 2904 EVT Ty = getPointerTy(DAG.getDataLayout()); 2905 SDValue GA = 2906 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2907 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2908 return MatAddr; 2909 } 2910 2911 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2912 // The actual address of the GlobalValue is stored in the TOC. 2913 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2914 setUsesTOCBasePtr(DAG); 2915 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2916 return getTOCEntry(DAG, SDLoc(JT), GA); 2917 } 2918 2919 unsigned MOHiFlag, MOLoFlag; 2920 bool IsPIC = isPositionIndependent(); 2921 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2922 2923 if (IsPIC && Subtarget.isSVR4ABI()) { 2924 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2925 PPCII::MO_PIC_FLAG); 2926 return getTOCEntry(DAG, SDLoc(GA), GA); 2927 } 2928 2929 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2930 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2931 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2932 } 2933 2934 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2935 SelectionDAG &DAG) const { 2936 EVT PtrVT = Op.getValueType(); 2937 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2938 const BlockAddress *BA = BASDN->getBlockAddress(); 2939 2940 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2941 if (Subtarget.isUsingPCRelativeCalls()) { 2942 SDLoc DL(BASDN); 2943 EVT Ty = getPointerTy(DAG.getDataLayout()); 2944 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2945 PPCII::MO_PCREL_FLAG); 2946 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2947 return MatAddr; 2948 } 2949 2950 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2951 // The actual BlockAddress is stored in the TOC. 2952 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2953 setUsesTOCBasePtr(DAG); 2954 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2955 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2956 } 2957 2958 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2959 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2960 return getTOCEntry( 2961 DAG, SDLoc(BASDN), 2962 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2963 2964 unsigned MOHiFlag, MOLoFlag; 2965 bool IsPIC = isPositionIndependent(); 2966 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2967 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2968 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2969 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2970 } 2971 2972 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2973 SelectionDAG &DAG) const { 2974 // FIXME: TLS addresses currently use medium model code sequences, 2975 // which is the most useful form. Eventually support for small and 2976 // large models could be added if users need it, at the cost of 2977 // additional complexity. 2978 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2979 if (DAG.getTarget().useEmulatedTLS()) 2980 return LowerToTLSEmulatedModel(GA, DAG); 2981 2982 SDLoc dl(GA); 2983 const GlobalValue *GV = GA->getGlobal(); 2984 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2985 bool is64bit = Subtarget.isPPC64(); 2986 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2987 PICLevel::Level picLevel = M->getPICLevel(); 2988 2989 const TargetMachine &TM = getTargetMachine(); 2990 TLSModel::Model Model = TM.getTLSModel(GV); 2991 2992 if (Model == TLSModel::LocalExec) { 2993 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2994 PPCII::MO_TPREL_HA); 2995 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2996 PPCII::MO_TPREL_LO); 2997 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2998 : DAG.getRegister(PPC::R2, MVT::i32); 2999 3000 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3001 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3002 } 3003 3004 if (Model == TLSModel::InitialExec) { 3005 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3006 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3007 PPCII::MO_TLS); 3008 SDValue GOTPtr; 3009 if (is64bit) { 3010 setUsesTOCBasePtr(DAG); 3011 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3012 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3013 PtrVT, GOTReg, TGA); 3014 } else { 3015 if (!TM.isPositionIndependent()) 3016 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3017 else if (picLevel == PICLevel::SmallPIC) 3018 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3019 else 3020 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3021 } 3022 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3023 PtrVT, TGA, GOTPtr); 3024 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3025 } 3026 3027 if (Model == TLSModel::GeneralDynamic) { 3028 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3029 SDValue GOTPtr; 3030 if (is64bit) { 3031 setUsesTOCBasePtr(DAG); 3032 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3033 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3034 GOTReg, TGA); 3035 } else { 3036 if (picLevel == PICLevel::SmallPIC) 3037 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3038 else 3039 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3040 } 3041 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3042 GOTPtr, TGA, TGA); 3043 } 3044 3045 if (Model == TLSModel::LocalDynamic) { 3046 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3047 SDValue GOTPtr; 3048 if (is64bit) { 3049 setUsesTOCBasePtr(DAG); 3050 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3051 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3052 GOTReg, TGA); 3053 } else { 3054 if (picLevel == PICLevel::SmallPIC) 3055 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3056 else 3057 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3058 } 3059 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3060 PtrVT, GOTPtr, TGA, TGA); 3061 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3062 PtrVT, TLSAddr, TGA); 3063 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3064 } 3065 3066 llvm_unreachable("Unknown TLS model!"); 3067 } 3068 3069 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3070 SelectionDAG &DAG) const { 3071 EVT PtrVT = Op.getValueType(); 3072 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3073 SDLoc DL(GSDN); 3074 const GlobalValue *GV = GSDN->getGlobal(); 3075 3076 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3077 // The actual address of the GlobalValue is stored in the TOC. 3078 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3079 if (Subtarget.isUsingPCRelativeCalls()) { 3080 EVT Ty = getPointerTy(DAG.getDataLayout()); 3081 if (isAccessedAsGotIndirect(Op)) { 3082 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3083 PPCII::MO_PCREL_FLAG | 3084 PPCII::MO_GOT_FLAG); 3085 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3086 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3087 MachinePointerInfo()); 3088 return Load; 3089 } else { 3090 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3091 PPCII::MO_PCREL_FLAG); 3092 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3093 } 3094 } 3095 setUsesTOCBasePtr(DAG); 3096 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3097 return getTOCEntry(DAG, DL, GA); 3098 } 3099 3100 unsigned MOHiFlag, MOLoFlag; 3101 bool IsPIC = isPositionIndependent(); 3102 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3103 3104 if (IsPIC && Subtarget.isSVR4ABI()) { 3105 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3106 GSDN->getOffset(), 3107 PPCII::MO_PIC_FLAG); 3108 return getTOCEntry(DAG, DL, GA); 3109 } 3110 3111 SDValue GAHi = 3112 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3113 SDValue GALo = 3114 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3115 3116 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3117 } 3118 3119 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3120 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3121 SDLoc dl(Op); 3122 3123 if (Op.getValueType() == MVT::v2i64) { 3124 // When the operands themselves are v2i64 values, we need to do something 3125 // special because VSX has no underlying comparison operations for these. 3126 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3127 // Equality can be handled by casting to the legal type for Altivec 3128 // comparisons, everything else needs to be expanded. 3129 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3130 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3131 DAG.getSetCC(dl, MVT::v4i32, 3132 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3133 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3134 CC)); 3135 } 3136 3137 return SDValue(); 3138 } 3139 3140 // We handle most of these in the usual way. 3141 return Op; 3142 } 3143 3144 // If we're comparing for equality to zero, expose the fact that this is 3145 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3146 // fold the new nodes. 3147 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3148 return V; 3149 3150 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3151 // Leave comparisons against 0 and -1 alone for now, since they're usually 3152 // optimized. FIXME: revisit this when we can custom lower all setcc 3153 // optimizations. 3154 if (C->isAllOnesValue() || C->isNullValue()) 3155 return SDValue(); 3156 } 3157 3158 // If we have an integer seteq/setne, turn it into a compare against zero 3159 // by xor'ing the rhs with the lhs, which is faster than setting a 3160 // condition register, reading it back out, and masking the correct bit. The 3161 // normal approach here uses sub to do this instead of xor. Using xor exposes 3162 // the result to other bit-twiddling opportunities. 3163 EVT LHSVT = Op.getOperand(0).getValueType(); 3164 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3165 EVT VT = Op.getValueType(); 3166 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3167 Op.getOperand(1)); 3168 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3169 } 3170 return SDValue(); 3171 } 3172 3173 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3174 SDNode *Node = Op.getNode(); 3175 EVT VT = Node->getValueType(0); 3176 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3177 SDValue InChain = Node->getOperand(0); 3178 SDValue VAListPtr = Node->getOperand(1); 3179 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3180 SDLoc dl(Node); 3181 3182 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3183 3184 // gpr_index 3185 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3186 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3187 InChain = GprIndex.getValue(1); 3188 3189 if (VT == MVT::i64) { 3190 // Check if GprIndex is even 3191 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3192 DAG.getConstant(1, dl, MVT::i32)); 3193 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3194 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3195 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3196 DAG.getConstant(1, dl, MVT::i32)); 3197 // Align GprIndex to be even if it isn't 3198 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3199 GprIndex); 3200 } 3201 3202 // fpr index is 1 byte after gpr 3203 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3204 DAG.getConstant(1, dl, MVT::i32)); 3205 3206 // fpr 3207 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3208 FprPtr, MachinePointerInfo(SV), MVT::i8); 3209 InChain = FprIndex.getValue(1); 3210 3211 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3212 DAG.getConstant(8, dl, MVT::i32)); 3213 3214 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3215 DAG.getConstant(4, dl, MVT::i32)); 3216 3217 // areas 3218 SDValue OverflowArea = 3219 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3220 InChain = OverflowArea.getValue(1); 3221 3222 SDValue RegSaveArea = 3223 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3224 InChain = RegSaveArea.getValue(1); 3225 3226 // select overflow_area if index > 8 3227 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3228 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3229 3230 // adjustment constant gpr_index * 4/8 3231 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3232 VT.isInteger() ? GprIndex : FprIndex, 3233 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3234 MVT::i32)); 3235 3236 // OurReg = RegSaveArea + RegConstant 3237 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3238 RegConstant); 3239 3240 // Floating types are 32 bytes into RegSaveArea 3241 if (VT.isFloatingPoint()) 3242 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3243 DAG.getConstant(32, dl, MVT::i32)); 3244 3245 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3246 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3247 VT.isInteger() ? GprIndex : FprIndex, 3248 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3249 MVT::i32)); 3250 3251 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3252 VT.isInteger() ? VAListPtr : FprPtr, 3253 MachinePointerInfo(SV), MVT::i8); 3254 3255 // determine if we should load from reg_save_area or overflow_area 3256 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3257 3258 // increase overflow_area by 4/8 if gpr/fpr > 8 3259 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3260 DAG.getConstant(VT.isInteger() ? 4 : 8, 3261 dl, MVT::i32)); 3262 3263 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3264 OverflowAreaPlusN); 3265 3266 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3267 MachinePointerInfo(), MVT::i32); 3268 3269 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3270 } 3271 3272 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3273 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3274 3275 // We have to copy the entire va_list struct: 3276 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3277 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3278 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3279 false, true, false, MachinePointerInfo(), 3280 MachinePointerInfo()); 3281 } 3282 3283 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3284 SelectionDAG &DAG) const { 3285 if (Subtarget.isAIXABI()) 3286 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3287 3288 return Op.getOperand(0); 3289 } 3290 3291 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3292 SelectionDAG &DAG) const { 3293 if (Subtarget.isAIXABI()) 3294 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3295 3296 SDValue Chain = Op.getOperand(0); 3297 SDValue Trmp = Op.getOperand(1); // trampoline 3298 SDValue FPtr = Op.getOperand(2); // nested function 3299 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3300 SDLoc dl(Op); 3301 3302 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3303 bool isPPC64 = (PtrVT == MVT::i64); 3304 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3305 3306 TargetLowering::ArgListTy Args; 3307 TargetLowering::ArgListEntry Entry; 3308 3309 Entry.Ty = IntPtrTy; 3310 Entry.Node = Trmp; Args.push_back(Entry); 3311 3312 // TrampSize == (isPPC64 ? 48 : 40); 3313 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3314 isPPC64 ? MVT::i64 : MVT::i32); 3315 Args.push_back(Entry); 3316 3317 Entry.Node = FPtr; Args.push_back(Entry); 3318 Entry.Node = Nest; Args.push_back(Entry); 3319 3320 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3321 TargetLowering::CallLoweringInfo CLI(DAG); 3322 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3323 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3324 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3325 3326 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3327 return CallResult.second; 3328 } 3329 3330 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3331 MachineFunction &MF = DAG.getMachineFunction(); 3332 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3333 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3334 3335 SDLoc dl(Op); 3336 3337 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3338 // vastart just stores the address of the VarArgsFrameIndex slot into the 3339 // memory location argument. 3340 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3341 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3342 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3343 MachinePointerInfo(SV)); 3344 } 3345 3346 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3347 // We suppose the given va_list is already allocated. 3348 // 3349 // typedef struct { 3350 // char gpr; /* index into the array of 8 GPRs 3351 // * stored in the register save area 3352 // * gpr=0 corresponds to r3, 3353 // * gpr=1 to r4, etc. 3354 // */ 3355 // char fpr; /* index into the array of 8 FPRs 3356 // * stored in the register save area 3357 // * fpr=0 corresponds to f1, 3358 // * fpr=1 to f2, etc. 3359 // */ 3360 // char *overflow_arg_area; 3361 // /* location on stack that holds 3362 // * the next overflow argument 3363 // */ 3364 // char *reg_save_area; 3365 // /* where r3:r10 and f1:f8 (if saved) 3366 // * are stored 3367 // */ 3368 // } va_list[1]; 3369 3370 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3371 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3372 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3373 PtrVT); 3374 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3375 PtrVT); 3376 3377 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3378 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3379 3380 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3381 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3382 3383 uint64_t FPROffset = 1; 3384 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3385 3386 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3387 3388 // Store first byte : number of int regs 3389 SDValue firstStore = 3390 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3391 MachinePointerInfo(SV), MVT::i8); 3392 uint64_t nextOffset = FPROffset; 3393 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3394 ConstFPROffset); 3395 3396 // Store second byte : number of float regs 3397 SDValue secondStore = 3398 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3399 MachinePointerInfo(SV, nextOffset), MVT::i8); 3400 nextOffset += StackOffset; 3401 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3402 3403 // Store second word : arguments given on stack 3404 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3405 MachinePointerInfo(SV, nextOffset)); 3406 nextOffset += FrameOffset; 3407 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3408 3409 // Store third word : arguments given in registers 3410 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3411 MachinePointerInfo(SV, nextOffset)); 3412 } 3413 3414 /// FPR - The set of FP registers that should be allocated for arguments 3415 /// on Darwin and AIX. 3416 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3417 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3418 PPC::F11, PPC::F12, PPC::F13}; 3419 3420 /// QFPR - The set of QPX registers that should be allocated for arguments. 3421 static const MCPhysReg QFPR[] = { 3422 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3423 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3424 3425 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3426 /// the stack. 3427 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3428 unsigned PtrByteSize) { 3429 unsigned ArgSize = ArgVT.getStoreSize(); 3430 if (Flags.isByVal()) 3431 ArgSize = Flags.getByValSize(); 3432 3433 // Round up to multiples of the pointer size, except for array members, 3434 // which are always packed. 3435 if (!Flags.isInConsecutiveRegs()) 3436 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3437 3438 return ArgSize; 3439 } 3440 3441 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3442 /// on the stack. 3443 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3444 ISD::ArgFlagsTy Flags, 3445 unsigned PtrByteSize) { 3446 Align Alignment(PtrByteSize); 3447 3448 // Altivec parameters are padded to a 16 byte boundary. 3449 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3450 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3451 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3452 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3453 Alignment = Align(16); 3454 // QPX vector types stored in double-precision are padded to a 32 byte 3455 // boundary. 3456 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3457 Alignment = Align(32); 3458 3459 // ByVal parameters are aligned as requested. 3460 if (Flags.isByVal()) { 3461 auto BVAlign = Flags.getNonZeroByValAlign(); 3462 if (BVAlign > PtrByteSize) { 3463 if (BVAlign.value() % PtrByteSize != 0) 3464 llvm_unreachable( 3465 "ByVal alignment is not a multiple of the pointer size"); 3466 3467 Alignment = BVAlign; 3468 } 3469 } 3470 3471 // Array members are always packed to their original alignment. 3472 if (Flags.isInConsecutiveRegs()) { 3473 // If the array member was split into multiple registers, the first 3474 // needs to be aligned to the size of the full type. (Except for 3475 // ppcf128, which is only aligned as its f64 components.) 3476 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3477 Alignment = Align(OrigVT.getStoreSize()); 3478 else 3479 Alignment = Align(ArgVT.getStoreSize()); 3480 } 3481 3482 return Alignment; 3483 } 3484 3485 /// CalculateStackSlotUsed - Return whether this argument will use its 3486 /// stack slot (instead of being passed in registers). ArgOffset, 3487 /// AvailableFPRs, and AvailableVRs must hold the current argument 3488 /// position, and will be updated to account for this argument. 3489 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3490 ISD::ArgFlagsTy Flags, 3491 unsigned PtrByteSize, 3492 unsigned LinkageSize, 3493 unsigned ParamAreaSize, 3494 unsigned &ArgOffset, 3495 unsigned &AvailableFPRs, 3496 unsigned &AvailableVRs, bool HasQPX) { 3497 bool UseMemory = false; 3498 3499 // Respect alignment of argument on the stack. 3500 Align Alignment = 3501 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3502 ArgOffset = alignTo(ArgOffset, Alignment); 3503 // If there's no space left in the argument save area, we must 3504 // use memory (this check also catches zero-sized arguments). 3505 if (ArgOffset >= LinkageSize + ParamAreaSize) 3506 UseMemory = true; 3507 3508 // Allocate argument on the stack. 3509 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3510 if (Flags.isInConsecutiveRegsLast()) 3511 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3512 // If we overran the argument save area, we must use memory 3513 // (this check catches arguments passed partially in memory) 3514 if (ArgOffset > LinkageSize + ParamAreaSize) 3515 UseMemory = true; 3516 3517 // However, if the argument is actually passed in an FPR or a VR, 3518 // we don't use memory after all. 3519 if (!Flags.isByVal()) { 3520 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3521 // QPX registers overlap with the scalar FP registers. 3522 (HasQPX && (ArgVT == MVT::v4f32 || 3523 ArgVT == MVT::v4f64 || 3524 ArgVT == MVT::v4i1))) 3525 if (AvailableFPRs > 0) { 3526 --AvailableFPRs; 3527 return false; 3528 } 3529 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3530 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3531 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3532 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3533 if (AvailableVRs > 0) { 3534 --AvailableVRs; 3535 return false; 3536 } 3537 } 3538 3539 return UseMemory; 3540 } 3541 3542 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3543 /// ensure minimum alignment required for target. 3544 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3545 unsigned NumBytes) { 3546 return alignTo(NumBytes, Lowering->getStackAlign()); 3547 } 3548 3549 SDValue PPCTargetLowering::LowerFormalArguments( 3550 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3551 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3552 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3553 if (Subtarget.isAIXABI()) 3554 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3555 InVals); 3556 if (Subtarget.is64BitELFABI()) 3557 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3558 InVals); 3559 if (Subtarget.is32BitELFABI()) 3560 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3561 InVals); 3562 3563 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3564 InVals); 3565 } 3566 3567 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3568 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3569 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3570 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3571 3572 // 32-bit SVR4 ABI Stack Frame Layout: 3573 // +-----------------------------------+ 3574 // +--> | Back chain | 3575 // | +-----------------------------------+ 3576 // | | Floating-point register save area | 3577 // | +-----------------------------------+ 3578 // | | General register save area | 3579 // | +-----------------------------------+ 3580 // | | CR save word | 3581 // | +-----------------------------------+ 3582 // | | VRSAVE save word | 3583 // | +-----------------------------------+ 3584 // | | Alignment padding | 3585 // | +-----------------------------------+ 3586 // | | Vector register save area | 3587 // | +-----------------------------------+ 3588 // | | Local variable space | 3589 // | +-----------------------------------+ 3590 // | | Parameter list area | 3591 // | +-----------------------------------+ 3592 // | | LR save word | 3593 // | +-----------------------------------+ 3594 // SP--> +--- | Back chain | 3595 // +-----------------------------------+ 3596 // 3597 // Specifications: 3598 // System V Application Binary Interface PowerPC Processor Supplement 3599 // AltiVec Technology Programming Interface Manual 3600 3601 MachineFunction &MF = DAG.getMachineFunction(); 3602 MachineFrameInfo &MFI = MF.getFrameInfo(); 3603 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3604 3605 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3606 // Potential tail calls could cause overwriting of argument stack slots. 3607 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3608 (CallConv == CallingConv::Fast)); 3609 unsigned PtrByteSize = 4; 3610 3611 // Assign locations to all of the incoming arguments. 3612 SmallVector<CCValAssign, 16> ArgLocs; 3613 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3614 *DAG.getContext()); 3615 3616 // Reserve space for the linkage area on the stack. 3617 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3618 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3619 if (useSoftFloat()) 3620 CCInfo.PreAnalyzeFormalArguments(Ins); 3621 3622 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3623 CCInfo.clearWasPPCF128(); 3624 3625 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3626 CCValAssign &VA = ArgLocs[i]; 3627 3628 // Arguments stored in registers. 3629 if (VA.isRegLoc()) { 3630 const TargetRegisterClass *RC; 3631 EVT ValVT = VA.getValVT(); 3632 3633 switch (ValVT.getSimpleVT().SimpleTy) { 3634 default: 3635 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3636 case MVT::i1: 3637 case MVT::i32: 3638 RC = &PPC::GPRCRegClass; 3639 break; 3640 case MVT::f32: 3641 if (Subtarget.hasP8Vector()) 3642 RC = &PPC::VSSRCRegClass; 3643 else if (Subtarget.hasSPE()) 3644 RC = &PPC::GPRCRegClass; 3645 else 3646 RC = &PPC::F4RCRegClass; 3647 break; 3648 case MVT::f64: 3649 if (Subtarget.hasVSX()) 3650 RC = &PPC::VSFRCRegClass; 3651 else if (Subtarget.hasSPE()) 3652 // SPE passes doubles in GPR pairs. 3653 RC = &PPC::GPRCRegClass; 3654 else 3655 RC = &PPC::F8RCRegClass; 3656 break; 3657 case MVT::v16i8: 3658 case MVT::v8i16: 3659 case MVT::v4i32: 3660 RC = &PPC::VRRCRegClass; 3661 break; 3662 case MVT::v4f32: 3663 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3664 break; 3665 case MVT::v2f64: 3666 case MVT::v2i64: 3667 RC = &PPC::VRRCRegClass; 3668 break; 3669 case MVT::v4f64: 3670 RC = &PPC::QFRCRegClass; 3671 break; 3672 case MVT::v4i1: 3673 RC = &PPC::QBRCRegClass; 3674 break; 3675 } 3676 3677 SDValue ArgValue; 3678 // Transform the arguments stored in physical registers into 3679 // virtual ones. 3680 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3681 assert(i + 1 < e && "No second half of double precision argument"); 3682 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3683 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3684 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3685 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3686 if (!Subtarget.isLittleEndian()) 3687 std::swap (ArgValueLo, ArgValueHi); 3688 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3689 ArgValueHi); 3690 } else { 3691 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3692 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3693 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3694 if (ValVT == MVT::i1) 3695 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3696 } 3697 3698 InVals.push_back(ArgValue); 3699 } else { 3700 // Argument stored in memory. 3701 assert(VA.isMemLoc()); 3702 3703 // Get the extended size of the argument type in stack 3704 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3705 // Get the actual size of the argument type 3706 unsigned ObjSize = VA.getValVT().getStoreSize(); 3707 unsigned ArgOffset = VA.getLocMemOffset(); 3708 // Stack objects in PPC32 are right justified. 3709 ArgOffset += ArgSize - ObjSize; 3710 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3711 3712 // Create load nodes to retrieve arguments from the stack. 3713 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3714 InVals.push_back( 3715 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3716 } 3717 } 3718 3719 // Assign locations to all of the incoming aggregate by value arguments. 3720 // Aggregates passed by value are stored in the local variable space of the 3721 // caller's stack frame, right above the parameter list area. 3722 SmallVector<CCValAssign, 16> ByValArgLocs; 3723 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3724 ByValArgLocs, *DAG.getContext()); 3725 3726 // Reserve stack space for the allocations in CCInfo. 3727 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3728 3729 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3730 3731 // Area that is at least reserved in the caller of this function. 3732 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3733 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3734 3735 // Set the size that is at least reserved in caller of this function. Tail 3736 // call optimized function's reserved stack space needs to be aligned so that 3737 // taking the difference between two stack areas will result in an aligned 3738 // stack. 3739 MinReservedArea = 3740 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3741 FuncInfo->setMinReservedArea(MinReservedArea); 3742 3743 SmallVector<SDValue, 8> MemOps; 3744 3745 // If the function takes variable number of arguments, make a frame index for 3746 // the start of the first vararg value... for expansion of llvm.va_start. 3747 if (isVarArg) { 3748 static const MCPhysReg GPArgRegs[] = { 3749 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3750 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3751 }; 3752 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3753 3754 static const MCPhysReg FPArgRegs[] = { 3755 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3756 PPC::F8 3757 }; 3758 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3759 3760 if (useSoftFloat() || hasSPE()) 3761 NumFPArgRegs = 0; 3762 3763 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3764 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3765 3766 // Make room for NumGPArgRegs and NumFPArgRegs. 3767 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3768 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3769 3770 FuncInfo->setVarArgsStackOffset( 3771 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3772 CCInfo.getNextStackOffset(), true)); 3773 3774 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3775 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3776 3777 // The fixed integer arguments of a variadic function are stored to the 3778 // VarArgsFrameIndex on the stack so that they may be loaded by 3779 // dereferencing the result of va_next. 3780 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3781 // Get an existing live-in vreg, or add a new one. 3782 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3783 if (!VReg) 3784 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3785 3786 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3787 SDValue Store = 3788 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3789 MemOps.push_back(Store); 3790 // Increment the address by four for the next argument to store 3791 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3792 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3793 } 3794 3795 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3796 // is set. 3797 // The double arguments are stored to the VarArgsFrameIndex 3798 // on the stack. 3799 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3800 // Get an existing live-in vreg, or add a new one. 3801 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3802 if (!VReg) 3803 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3804 3805 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3806 SDValue Store = 3807 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3808 MemOps.push_back(Store); 3809 // Increment the address by eight for the next argument to store 3810 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3811 PtrVT); 3812 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3813 } 3814 } 3815 3816 if (!MemOps.empty()) 3817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3818 3819 return Chain; 3820 } 3821 3822 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3823 // value to MVT::i64 and then truncate to the correct register size. 3824 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3825 EVT ObjectVT, SelectionDAG &DAG, 3826 SDValue ArgVal, 3827 const SDLoc &dl) const { 3828 if (Flags.isSExt()) 3829 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3830 DAG.getValueType(ObjectVT)); 3831 else if (Flags.isZExt()) 3832 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3833 DAG.getValueType(ObjectVT)); 3834 3835 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3836 } 3837 3838 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3839 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3840 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3841 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3842 // TODO: add description of PPC stack frame format, or at least some docs. 3843 // 3844 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3845 bool isLittleEndian = Subtarget.isLittleEndian(); 3846 MachineFunction &MF = DAG.getMachineFunction(); 3847 MachineFrameInfo &MFI = MF.getFrameInfo(); 3848 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3849 3850 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3851 "fastcc not supported on varargs functions"); 3852 3853 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3854 // Potential tail calls could cause overwriting of argument stack slots. 3855 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3856 (CallConv == CallingConv::Fast)); 3857 unsigned PtrByteSize = 8; 3858 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3859 3860 static const MCPhysReg GPR[] = { 3861 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3862 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3863 }; 3864 static const MCPhysReg VR[] = { 3865 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3866 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3867 }; 3868 3869 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3870 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3871 const unsigned Num_VR_Regs = array_lengthof(VR); 3872 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3873 3874 // Do a first pass over the arguments to determine whether the ABI 3875 // guarantees that our caller has allocated the parameter save area 3876 // on its stack frame. In the ELFv1 ABI, this is always the case; 3877 // in the ELFv2 ABI, it is true if this is a vararg function or if 3878 // any parameter is located in a stack slot. 3879 3880 bool HasParameterArea = !isELFv2ABI || isVarArg; 3881 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3882 unsigned NumBytes = LinkageSize; 3883 unsigned AvailableFPRs = Num_FPR_Regs; 3884 unsigned AvailableVRs = Num_VR_Regs; 3885 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3886 if (Ins[i].Flags.isNest()) 3887 continue; 3888 3889 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3890 PtrByteSize, LinkageSize, ParamAreaSize, 3891 NumBytes, AvailableFPRs, AvailableVRs, 3892 Subtarget.hasQPX())) 3893 HasParameterArea = true; 3894 } 3895 3896 // Add DAG nodes to load the arguments or copy them out of registers. On 3897 // entry to a function on PPC, the arguments start after the linkage area, 3898 // although the first ones are often in registers. 3899 3900 unsigned ArgOffset = LinkageSize; 3901 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3902 unsigned &QFPR_idx = FPR_idx; 3903 SmallVector<SDValue, 8> MemOps; 3904 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3905 unsigned CurArgIdx = 0; 3906 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3907 SDValue ArgVal; 3908 bool needsLoad = false; 3909 EVT ObjectVT = Ins[ArgNo].VT; 3910 EVT OrigVT = Ins[ArgNo].ArgVT; 3911 unsigned ObjSize = ObjectVT.getStoreSize(); 3912 unsigned ArgSize = ObjSize; 3913 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3914 if (Ins[ArgNo].isOrigArg()) { 3915 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3916 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3917 } 3918 // We re-align the argument offset for each argument, except when using the 3919 // fast calling convention, when we need to make sure we do that only when 3920 // we'll actually use a stack slot. 3921 unsigned CurArgOffset; 3922 Align Alignment; 3923 auto ComputeArgOffset = [&]() { 3924 /* Respect alignment of argument on the stack. */ 3925 Alignment = 3926 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3927 ArgOffset = alignTo(ArgOffset, Alignment); 3928 CurArgOffset = ArgOffset; 3929 }; 3930 3931 if (CallConv != CallingConv::Fast) { 3932 ComputeArgOffset(); 3933 3934 /* Compute GPR index associated with argument offset. */ 3935 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3936 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3937 } 3938 3939 // FIXME the codegen can be much improved in some cases. 3940 // We do not have to keep everything in memory. 3941 if (Flags.isByVal()) { 3942 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3943 3944 if (CallConv == CallingConv::Fast) 3945 ComputeArgOffset(); 3946 3947 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3948 ObjSize = Flags.getByValSize(); 3949 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3950 // Empty aggregate parameters do not take up registers. Examples: 3951 // struct { } a; 3952 // union { } b; 3953 // int c[0]; 3954 // etc. However, we have to provide a place-holder in InVals, so 3955 // pretend we have an 8-byte item at the current address for that 3956 // purpose. 3957 if (!ObjSize) { 3958 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3959 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3960 InVals.push_back(FIN); 3961 continue; 3962 } 3963 3964 // Create a stack object covering all stack doublewords occupied 3965 // by the argument. If the argument is (fully or partially) on 3966 // the stack, or if the argument is fully in registers but the 3967 // caller has allocated the parameter save anyway, we can refer 3968 // directly to the caller's stack frame. Otherwise, create a 3969 // local copy in our own frame. 3970 int FI; 3971 if (HasParameterArea || 3972 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3973 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3974 else 3975 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3976 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3977 3978 // Handle aggregates smaller than 8 bytes. 3979 if (ObjSize < PtrByteSize) { 3980 // The value of the object is its address, which differs from the 3981 // address of the enclosing doubleword on big-endian systems. 3982 SDValue Arg = FIN; 3983 if (!isLittleEndian) { 3984 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3985 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3986 } 3987 InVals.push_back(Arg); 3988 3989 if (GPR_idx != Num_GPR_Regs) { 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 Store; 3994 3995 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3996 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3997 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3998 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3999 MachinePointerInfo(&*FuncArg), ObjType); 4000 } else { 4001 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4002 // store the whole register as-is to the parameter save area 4003 // slot. 4004 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4005 MachinePointerInfo(&*FuncArg)); 4006 } 4007 4008 MemOps.push_back(Store); 4009 } 4010 // Whether we copied from a register or not, advance the offset 4011 // into the parameter save area by a full doubleword. 4012 ArgOffset += PtrByteSize; 4013 continue; 4014 } 4015 4016 // The value of the object is its address, which is the address of 4017 // its first stack doubleword. 4018 InVals.push_back(FIN); 4019 4020 // Store whatever pieces of the object are in registers to memory. 4021 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4022 if (GPR_idx == Num_GPR_Regs) 4023 break; 4024 4025 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4026 FuncInfo->addLiveInAttr(VReg, Flags); 4027 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4028 SDValue Addr = FIN; 4029 if (j) { 4030 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4031 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4032 } 4033 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4034 MachinePointerInfo(&*FuncArg, j)); 4035 MemOps.push_back(Store); 4036 ++GPR_idx; 4037 } 4038 ArgOffset += ArgSize; 4039 continue; 4040 } 4041 4042 switch (ObjectVT.getSimpleVT().SimpleTy) { 4043 default: llvm_unreachable("Unhandled argument type!"); 4044 case MVT::i1: 4045 case MVT::i32: 4046 case MVT::i64: 4047 if (Flags.isNest()) { 4048 // The 'nest' parameter, if any, is passed in R11. 4049 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4050 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4051 4052 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4053 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4054 4055 break; 4056 } 4057 4058 // These can be scalar arguments or elements of an integer array type 4059 // passed directly. Clang may use those instead of "byval" aggregate 4060 // types to avoid forcing arguments to memory unnecessarily. 4061 if (GPR_idx != Num_GPR_Regs) { 4062 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4063 FuncInfo->addLiveInAttr(VReg, Flags); 4064 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4065 4066 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4067 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4068 // value to MVT::i64 and then truncate to the correct register size. 4069 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4070 } else { 4071 if (CallConv == CallingConv::Fast) 4072 ComputeArgOffset(); 4073 4074 needsLoad = true; 4075 ArgSize = PtrByteSize; 4076 } 4077 if (CallConv != CallingConv::Fast || needsLoad) 4078 ArgOffset += 8; 4079 break; 4080 4081 case MVT::f32: 4082 case MVT::f64: 4083 // These can be scalar arguments or elements of a float array type 4084 // passed directly. The latter are used to implement ELFv2 homogenous 4085 // float aggregates. 4086 if (FPR_idx != Num_FPR_Regs) { 4087 unsigned VReg; 4088 4089 if (ObjectVT == MVT::f32) 4090 VReg = MF.addLiveIn(FPR[FPR_idx], 4091 Subtarget.hasP8Vector() 4092 ? &PPC::VSSRCRegClass 4093 : &PPC::F4RCRegClass); 4094 else 4095 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4096 ? &PPC::VSFRCRegClass 4097 : &PPC::F8RCRegClass); 4098 4099 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4100 ++FPR_idx; 4101 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4102 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4103 // once we support fp <-> gpr moves. 4104 4105 // This can only ever happen in the presence of f32 array types, 4106 // since otherwise we never run out of FPRs before running out 4107 // of GPRs. 4108 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4109 FuncInfo->addLiveInAttr(VReg, Flags); 4110 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4111 4112 if (ObjectVT == MVT::f32) { 4113 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4114 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4115 DAG.getConstant(32, dl, MVT::i32)); 4116 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4117 } 4118 4119 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4120 } else { 4121 if (CallConv == CallingConv::Fast) 4122 ComputeArgOffset(); 4123 4124 needsLoad = true; 4125 } 4126 4127 // When passing an array of floats, the array occupies consecutive 4128 // space in the argument area; only round up to the next doubleword 4129 // at the end of the array. Otherwise, each float takes 8 bytes. 4130 if (CallConv != CallingConv::Fast || needsLoad) { 4131 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4132 ArgOffset += ArgSize; 4133 if (Flags.isInConsecutiveRegsLast()) 4134 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4135 } 4136 break; 4137 case MVT::v4f32: 4138 case MVT::v4i32: 4139 case MVT::v8i16: 4140 case MVT::v16i8: 4141 case MVT::v2f64: 4142 case MVT::v2i64: 4143 case MVT::v1i128: 4144 case MVT::f128: 4145 if (!Subtarget.hasQPX()) { 4146 // These can be scalar arguments or elements of a vector array type 4147 // passed directly. The latter are used to implement ELFv2 homogenous 4148 // vector aggregates. 4149 if (VR_idx != Num_VR_Regs) { 4150 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4151 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4152 ++VR_idx; 4153 } else { 4154 if (CallConv == CallingConv::Fast) 4155 ComputeArgOffset(); 4156 needsLoad = true; 4157 } 4158 if (CallConv != CallingConv::Fast || needsLoad) 4159 ArgOffset += 16; 4160 break; 4161 } // not QPX 4162 4163 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4164 "Invalid QPX parameter type"); 4165 LLVM_FALLTHROUGH; 4166 4167 case MVT::v4f64: 4168 case MVT::v4i1: 4169 // QPX vectors are treated like their scalar floating-point subregisters 4170 // (except that they're larger). 4171 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4172 if (QFPR_idx != Num_QFPR_Regs) { 4173 const TargetRegisterClass *RC; 4174 switch (ObjectVT.getSimpleVT().SimpleTy) { 4175 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4176 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4177 default: RC = &PPC::QBRCRegClass; break; 4178 } 4179 4180 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4181 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4182 ++QFPR_idx; 4183 } else { 4184 if (CallConv == CallingConv::Fast) 4185 ComputeArgOffset(); 4186 needsLoad = true; 4187 } 4188 if (CallConv != CallingConv::Fast || needsLoad) 4189 ArgOffset += Sz; 4190 break; 4191 } 4192 4193 // We need to load the argument to a virtual register if we determined 4194 // above that we ran out of physical registers of the appropriate type. 4195 if (needsLoad) { 4196 if (ObjSize < ArgSize && !isLittleEndian) 4197 CurArgOffset += ArgSize - ObjSize; 4198 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4199 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4200 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4201 } 4202 4203 InVals.push_back(ArgVal); 4204 } 4205 4206 // Area that is at least reserved in the caller of this function. 4207 unsigned MinReservedArea; 4208 if (HasParameterArea) 4209 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4210 else 4211 MinReservedArea = LinkageSize; 4212 4213 // Set the size that is at least reserved in caller of this function. Tail 4214 // call optimized functions' reserved stack space needs to be aligned so that 4215 // taking the difference between two stack areas will result in an aligned 4216 // stack. 4217 MinReservedArea = 4218 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4219 FuncInfo->setMinReservedArea(MinReservedArea); 4220 4221 // If the function takes variable number of arguments, make a frame index for 4222 // the start of the first vararg value... for expansion of llvm.va_start. 4223 if (isVarArg) { 4224 int Depth = ArgOffset; 4225 4226 FuncInfo->setVarArgsFrameIndex( 4227 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4228 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4229 4230 // If this function is vararg, store any remaining integer argument regs 4231 // to their spots on the stack so that they may be loaded by dereferencing 4232 // the result of va_next. 4233 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4234 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4235 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4236 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4237 SDValue Store = 4238 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4239 MemOps.push_back(Store); 4240 // Increment the address by four for the next argument to store 4241 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4242 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4243 } 4244 } 4245 4246 if (!MemOps.empty()) 4247 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4248 4249 return Chain; 4250 } 4251 4252 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4253 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4254 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4255 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4256 // TODO: add description of PPC stack frame format, or at least some docs. 4257 // 4258 MachineFunction &MF = DAG.getMachineFunction(); 4259 MachineFrameInfo &MFI = MF.getFrameInfo(); 4260 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4261 4262 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4263 bool isPPC64 = PtrVT == MVT::i64; 4264 // Potential tail calls could cause overwriting of argument stack slots. 4265 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4266 (CallConv == CallingConv::Fast)); 4267 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4268 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4269 unsigned ArgOffset = LinkageSize; 4270 // Area that is at least reserved in caller of this function. 4271 unsigned MinReservedArea = ArgOffset; 4272 4273 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4274 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4275 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4276 }; 4277 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4278 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4279 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4280 }; 4281 static const MCPhysReg VR[] = { 4282 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4283 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4284 }; 4285 4286 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4287 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4288 const unsigned Num_VR_Regs = array_lengthof( VR); 4289 4290 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4291 4292 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4293 4294 // In 32-bit non-varargs functions, the stack space for vectors is after the 4295 // stack space for non-vectors. We do not use this space unless we have 4296 // too many vectors to fit in registers, something that only occurs in 4297 // constructed examples:), but we have to walk the arglist to figure 4298 // that out...for the pathological case, compute VecArgOffset as the 4299 // start of the vector parameter area. Computing VecArgOffset is the 4300 // entire point of the following loop. 4301 unsigned VecArgOffset = ArgOffset; 4302 if (!isVarArg && !isPPC64) { 4303 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4304 ++ArgNo) { 4305 EVT ObjectVT = Ins[ArgNo].VT; 4306 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4307 4308 if (Flags.isByVal()) { 4309 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4310 unsigned ObjSize = Flags.getByValSize(); 4311 unsigned ArgSize = 4312 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4313 VecArgOffset += ArgSize; 4314 continue; 4315 } 4316 4317 switch(ObjectVT.getSimpleVT().SimpleTy) { 4318 default: llvm_unreachable("Unhandled argument type!"); 4319 case MVT::i1: 4320 case MVT::i32: 4321 case MVT::f32: 4322 VecArgOffset += 4; 4323 break; 4324 case MVT::i64: // PPC64 4325 case MVT::f64: 4326 // FIXME: We are guaranteed to be !isPPC64 at this point. 4327 // Does MVT::i64 apply? 4328 VecArgOffset += 8; 4329 break; 4330 case MVT::v4f32: 4331 case MVT::v4i32: 4332 case MVT::v8i16: 4333 case MVT::v16i8: 4334 // Nothing to do, we're only looking at Nonvector args here. 4335 break; 4336 } 4337 } 4338 } 4339 // We've found where the vector parameter area in memory is. Skip the 4340 // first 12 parameters; these don't use that memory. 4341 VecArgOffset = ((VecArgOffset+15)/16)*16; 4342 VecArgOffset += 12*16; 4343 4344 // Add DAG nodes to load the arguments or copy them out of registers. On 4345 // entry to a function on PPC, the arguments start after the linkage area, 4346 // although the first ones are often in registers. 4347 4348 SmallVector<SDValue, 8> MemOps; 4349 unsigned nAltivecParamsAtEnd = 0; 4350 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4351 unsigned CurArgIdx = 0; 4352 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4353 SDValue ArgVal; 4354 bool needsLoad = false; 4355 EVT ObjectVT = Ins[ArgNo].VT; 4356 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4357 unsigned ArgSize = ObjSize; 4358 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4359 if (Ins[ArgNo].isOrigArg()) { 4360 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4361 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4362 } 4363 unsigned CurArgOffset = ArgOffset; 4364 4365 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4366 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4367 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4368 if (isVarArg || isPPC64) { 4369 MinReservedArea = ((MinReservedArea+15)/16)*16; 4370 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4371 Flags, 4372 PtrByteSize); 4373 } else nAltivecParamsAtEnd++; 4374 } else 4375 // Calculate min reserved area. 4376 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4377 Flags, 4378 PtrByteSize); 4379 4380 // FIXME the codegen can be much improved in some cases. 4381 // We do not have to keep everything in memory. 4382 if (Flags.isByVal()) { 4383 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4384 4385 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4386 ObjSize = Flags.getByValSize(); 4387 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4388 // Objects of size 1 and 2 are right justified, everything else is 4389 // left justified. This means the memory address is adjusted forwards. 4390 if (ObjSize==1 || ObjSize==2) { 4391 CurArgOffset = CurArgOffset + (4 - ObjSize); 4392 } 4393 // The value of the object is its address. 4394 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4395 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4396 InVals.push_back(FIN); 4397 if (ObjSize==1 || ObjSize==2) { 4398 if (GPR_idx != Num_GPR_Regs) { 4399 unsigned VReg; 4400 if (isPPC64) 4401 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4402 else 4403 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4404 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4405 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4406 SDValue Store = 4407 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4408 MachinePointerInfo(&*FuncArg), ObjType); 4409 MemOps.push_back(Store); 4410 ++GPR_idx; 4411 } 4412 4413 ArgOffset += PtrByteSize; 4414 4415 continue; 4416 } 4417 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4418 // Store whatever pieces of the object are in registers 4419 // to memory. ArgOffset will be the address of the beginning 4420 // of the object. 4421 if (GPR_idx != Num_GPR_Regs) { 4422 unsigned VReg; 4423 if (isPPC64) 4424 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4425 else 4426 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4427 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4428 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4429 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4430 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4431 MachinePointerInfo(&*FuncArg, j)); 4432 MemOps.push_back(Store); 4433 ++GPR_idx; 4434 ArgOffset += PtrByteSize; 4435 } else { 4436 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4437 break; 4438 } 4439 } 4440 continue; 4441 } 4442 4443 switch (ObjectVT.getSimpleVT().SimpleTy) { 4444 default: llvm_unreachable("Unhandled argument type!"); 4445 case MVT::i1: 4446 case MVT::i32: 4447 if (!isPPC64) { 4448 if (GPR_idx != Num_GPR_Regs) { 4449 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4450 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4451 4452 if (ObjectVT == MVT::i1) 4453 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4454 4455 ++GPR_idx; 4456 } else { 4457 needsLoad = true; 4458 ArgSize = PtrByteSize; 4459 } 4460 // All int arguments reserve stack space in the Darwin ABI. 4461 ArgOffset += PtrByteSize; 4462 break; 4463 } 4464 LLVM_FALLTHROUGH; 4465 case MVT::i64: // PPC64 4466 if (GPR_idx != Num_GPR_Regs) { 4467 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4468 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4469 4470 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4471 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4472 // value to MVT::i64 and then truncate to the correct register size. 4473 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4474 4475 ++GPR_idx; 4476 } else { 4477 needsLoad = true; 4478 ArgSize = PtrByteSize; 4479 } 4480 // All int arguments reserve stack space in the Darwin ABI. 4481 ArgOffset += 8; 4482 break; 4483 4484 case MVT::f32: 4485 case MVT::f64: 4486 // Every 4 bytes of argument space consumes one of the GPRs available for 4487 // argument passing. 4488 if (GPR_idx != Num_GPR_Regs) { 4489 ++GPR_idx; 4490 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4491 ++GPR_idx; 4492 } 4493 if (FPR_idx != Num_FPR_Regs) { 4494 unsigned VReg; 4495 4496 if (ObjectVT == MVT::f32) 4497 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4498 else 4499 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4500 4501 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4502 ++FPR_idx; 4503 } else { 4504 needsLoad = true; 4505 } 4506 4507 // All FP arguments reserve stack space in the Darwin ABI. 4508 ArgOffset += isPPC64 ? 8 : ObjSize; 4509 break; 4510 case MVT::v4f32: 4511 case MVT::v4i32: 4512 case MVT::v8i16: 4513 case MVT::v16i8: 4514 // Note that vector arguments in registers don't reserve stack space, 4515 // except in varargs functions. 4516 if (VR_idx != Num_VR_Regs) { 4517 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4518 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4519 if (isVarArg) { 4520 while ((ArgOffset % 16) != 0) { 4521 ArgOffset += PtrByteSize; 4522 if (GPR_idx != Num_GPR_Regs) 4523 GPR_idx++; 4524 } 4525 ArgOffset += 16; 4526 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4527 } 4528 ++VR_idx; 4529 } else { 4530 if (!isVarArg && !isPPC64) { 4531 // Vectors go after all the nonvectors. 4532 CurArgOffset = VecArgOffset; 4533 VecArgOffset += 16; 4534 } else { 4535 // Vectors are aligned. 4536 ArgOffset = ((ArgOffset+15)/16)*16; 4537 CurArgOffset = ArgOffset; 4538 ArgOffset += 16; 4539 } 4540 needsLoad = true; 4541 } 4542 break; 4543 } 4544 4545 // We need to load the argument to a virtual register if we determined above 4546 // that we ran out of physical registers of the appropriate type. 4547 if (needsLoad) { 4548 int FI = MFI.CreateFixedObject(ObjSize, 4549 CurArgOffset + (ArgSize - ObjSize), 4550 isImmutable); 4551 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4552 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4553 } 4554 4555 InVals.push_back(ArgVal); 4556 } 4557 4558 // Allow for Altivec parameters at the end, if needed. 4559 if (nAltivecParamsAtEnd) { 4560 MinReservedArea = ((MinReservedArea+15)/16)*16; 4561 MinReservedArea += 16*nAltivecParamsAtEnd; 4562 } 4563 4564 // Area that is at least reserved in the caller of this function. 4565 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4566 4567 // Set the size that is at least reserved in caller of this function. Tail 4568 // call optimized functions' reserved stack space needs to be aligned so that 4569 // taking the difference between two stack areas will result in an aligned 4570 // stack. 4571 MinReservedArea = 4572 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4573 FuncInfo->setMinReservedArea(MinReservedArea); 4574 4575 // If the function takes variable number of arguments, make a frame index for 4576 // the start of the first vararg value... for expansion of llvm.va_start. 4577 if (isVarArg) { 4578 int Depth = ArgOffset; 4579 4580 FuncInfo->setVarArgsFrameIndex( 4581 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4582 Depth, true)); 4583 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4584 4585 // If this function is vararg, store any remaining integer argument regs 4586 // to their spots on the stack so that they may be loaded by dereferencing 4587 // the result of va_next. 4588 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4589 unsigned VReg; 4590 4591 if (isPPC64) 4592 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4593 else 4594 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4595 4596 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4597 SDValue Store = 4598 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4599 MemOps.push_back(Store); 4600 // Increment the address by four for the next argument to store 4601 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4602 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4603 } 4604 } 4605 4606 if (!MemOps.empty()) 4607 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4608 4609 return Chain; 4610 } 4611 4612 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4613 /// adjusted to accommodate the arguments for the tailcall. 4614 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4615 unsigned ParamSize) { 4616 4617 if (!isTailCall) return 0; 4618 4619 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4620 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4621 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4622 // Remember only if the new adjustment is bigger. 4623 if (SPDiff < FI->getTailCallSPDelta()) 4624 FI->setTailCallSPDelta(SPDiff); 4625 4626 return SPDiff; 4627 } 4628 4629 static bool isFunctionGlobalAddress(SDValue Callee); 4630 4631 static bool 4632 callsShareTOCBase(const Function *Caller, SDValue Callee, 4633 const TargetMachine &TM) { 4634 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4635 // don't have enough information to determine if the caller and calle share 4636 // the same TOC base, so we have to pessimistically assume they don't for 4637 // correctness. 4638 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4639 if (!G) 4640 return false; 4641 4642 const GlobalValue *GV = G->getGlobal(); 4643 // The medium and large code models are expected to provide a sufficiently 4644 // large TOC to provide all data addressing needs of a module with a 4645 // single TOC. Since each module will be addressed with a single TOC then we 4646 // only need to check that caller and callee don't cross dso boundaries. 4647 if (CodeModel::Medium == TM.getCodeModel() || 4648 CodeModel::Large == TM.getCodeModel()) 4649 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4650 4651 // Otherwise we need to ensure callee and caller are in the same section, 4652 // since the linker may allocate multiple TOCs, and we don't know which 4653 // sections will belong to the same TOC base. 4654 4655 if (!GV->isStrongDefinitionForLinker()) 4656 return false; 4657 4658 // Any explicitly-specified sections and section prefixes must also match. 4659 // Also, if we're using -ffunction-sections, then each function is always in 4660 // a different section (the same is true for COMDAT functions). 4661 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4662 GV->getSection() != Caller->getSection()) 4663 return false; 4664 if (const auto *F = dyn_cast<Function>(GV)) { 4665 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4666 return false; 4667 } 4668 4669 // If the callee might be interposed, then we can't assume the ultimate call 4670 // target will be in the same section. Even in cases where we can assume that 4671 // interposition won't happen, in any case where the linker might insert a 4672 // stub to allow for interposition, we must generate code as though 4673 // interposition might occur. To understand why this matters, consider a 4674 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4675 // in the same section, but a is in a different module (i.e. has a different 4676 // TOC base pointer). If the linker allows for interposition between b and c, 4677 // then it will generate a stub for the call edge between b and c which will 4678 // save the TOC pointer into the designated stack slot allocated by b. If we 4679 // return true here, and therefore allow a tail call between b and c, that 4680 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4681 // pointer into the stack slot allocated by a (where the a -> b stub saved 4682 // a's TOC base pointer). If we're not considering a tail call, but rather, 4683 // whether a nop is needed after the call instruction in b, because the linker 4684 // will insert a stub, it might complain about a missing nop if we omit it 4685 // (although many don't complain in this case). 4686 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4687 return false; 4688 4689 return true; 4690 } 4691 4692 static bool 4693 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4694 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4695 assert(Subtarget.is64BitELFABI()); 4696 4697 const unsigned PtrByteSize = 8; 4698 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4699 4700 static const MCPhysReg GPR[] = { 4701 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4702 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4703 }; 4704 static const MCPhysReg VR[] = { 4705 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4706 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4707 }; 4708 4709 const unsigned NumGPRs = array_lengthof(GPR); 4710 const unsigned NumFPRs = 13; 4711 const unsigned NumVRs = array_lengthof(VR); 4712 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4713 4714 unsigned NumBytes = LinkageSize; 4715 unsigned AvailableFPRs = NumFPRs; 4716 unsigned AvailableVRs = NumVRs; 4717 4718 for (const ISD::OutputArg& Param : Outs) { 4719 if (Param.Flags.isNest()) continue; 4720 4721 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4722 PtrByteSize, LinkageSize, ParamAreaSize, 4723 NumBytes, AvailableFPRs, AvailableVRs, 4724 Subtarget.hasQPX())) 4725 return true; 4726 } 4727 return false; 4728 } 4729 4730 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4731 if (CB.arg_size() != CallerFn->arg_size()) 4732 return false; 4733 4734 auto CalleeArgIter = CB.arg_begin(); 4735 auto CalleeArgEnd = CB.arg_end(); 4736 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4737 4738 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4739 const Value* CalleeArg = *CalleeArgIter; 4740 const Value* CallerArg = &(*CallerArgIter); 4741 if (CalleeArg == CallerArg) 4742 continue; 4743 4744 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4745 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4746 // } 4747 // 1st argument of callee is undef and has the same type as caller. 4748 if (CalleeArg->getType() == CallerArg->getType() && 4749 isa<UndefValue>(CalleeArg)) 4750 continue; 4751 4752 return false; 4753 } 4754 4755 return true; 4756 } 4757 4758 // Returns true if TCO is possible between the callers and callees 4759 // calling conventions. 4760 static bool 4761 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4762 CallingConv::ID CalleeCC) { 4763 // Tail calls are possible with fastcc and ccc. 4764 auto isTailCallableCC = [] (CallingConv::ID CC){ 4765 return CC == CallingConv::C || CC == CallingConv::Fast; 4766 }; 4767 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4768 return false; 4769 4770 // We can safely tail call both fastcc and ccc callees from a c calling 4771 // convention caller. If the caller is fastcc, we may have less stack space 4772 // than a non-fastcc caller with the same signature so disable tail-calls in 4773 // that case. 4774 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4775 } 4776 4777 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4778 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4779 const SmallVectorImpl<ISD::OutputArg> &Outs, 4780 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4781 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4782 4783 if (DisableSCO && !TailCallOpt) return false; 4784 4785 // Variadic argument functions are not supported. 4786 if (isVarArg) return false; 4787 4788 auto &Caller = DAG.getMachineFunction().getFunction(); 4789 // Check that the calling conventions are compatible for tco. 4790 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4791 return false; 4792 4793 // Caller contains any byval parameter is not supported. 4794 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4795 return false; 4796 4797 // Callee contains any byval parameter is not supported, too. 4798 // Note: This is a quick work around, because in some cases, e.g. 4799 // caller's stack size > callee's stack size, we are still able to apply 4800 // sibling call optimization. For example, gcc is able to do SCO for caller1 4801 // in the following example, but not for caller2. 4802 // struct test { 4803 // long int a; 4804 // char ary[56]; 4805 // } gTest; 4806 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4807 // b->a = v.a; 4808 // return 0; 4809 // } 4810 // void caller1(struct test a, struct test c, struct test *b) { 4811 // callee(gTest, b); } 4812 // void caller2(struct test *b) { callee(gTest, b); } 4813 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4814 return false; 4815 4816 // If callee and caller use different calling conventions, we cannot pass 4817 // parameters on stack since offsets for the parameter area may be different. 4818 if (Caller.getCallingConv() != CalleeCC && 4819 needStackSlotPassParameters(Subtarget, Outs)) 4820 return false; 4821 4822 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4823 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4824 // callee potentially have different TOC bases then we cannot tail call since 4825 // we need to restore the TOC pointer after the call. 4826 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4827 // We cannot guarantee this for indirect calls or calls to external functions. 4828 // When PC-Relative addressing is used, the concept of the TOC is no longer 4829 // applicable so this check is not required. 4830 // Check first for indirect calls. 4831 if (!Subtarget.isUsingPCRelativeCalls() && 4832 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4833 return false; 4834 4835 // Check if we share the TOC base. 4836 if (!Subtarget.isUsingPCRelativeCalls() && 4837 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4838 return false; 4839 4840 // TCO allows altering callee ABI, so we don't have to check further. 4841 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4842 return true; 4843 4844 if (DisableSCO) return false; 4845 4846 // If callee use the same argument list that caller is using, then we can 4847 // apply SCO on this case. If it is not, then we need to check if callee needs 4848 // stack for passing arguments. 4849 // PC Relative tail calls may not have a CallBase. 4850 // If there is no CallBase we cannot verify if we have the same argument 4851 // list so assume that we don't have the same argument list. 4852 if (CB && !hasSameArgumentList(&Caller, *CB) && 4853 needStackSlotPassParameters(Subtarget, Outs)) 4854 return false; 4855 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4856 return false; 4857 4858 return true; 4859 } 4860 4861 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4862 /// for tail call optimization. Targets which want to do tail call 4863 /// optimization should implement this function. 4864 bool 4865 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4866 CallingConv::ID CalleeCC, 4867 bool isVarArg, 4868 const SmallVectorImpl<ISD::InputArg> &Ins, 4869 SelectionDAG& DAG) const { 4870 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4871 return false; 4872 4873 // Variable argument functions are not supported. 4874 if (isVarArg) 4875 return false; 4876 4877 MachineFunction &MF = DAG.getMachineFunction(); 4878 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4879 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4880 // Functions containing by val parameters are not supported. 4881 for (unsigned i = 0; i != Ins.size(); i++) { 4882 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4883 if (Flags.isByVal()) return false; 4884 } 4885 4886 // Non-PIC/GOT tail calls are supported. 4887 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4888 return true; 4889 4890 // At the moment we can only do local tail calls (in same module, hidden 4891 // or protected) if we are generating PIC. 4892 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4893 return G->getGlobal()->hasHiddenVisibility() 4894 || G->getGlobal()->hasProtectedVisibility(); 4895 } 4896 4897 return false; 4898 } 4899 4900 /// isCallCompatibleAddress - Return the immediate to use if the specified 4901 /// 32-bit value is representable in the immediate field of a BxA instruction. 4902 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4903 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4904 if (!C) return nullptr; 4905 4906 int Addr = C->getZExtValue(); 4907 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4908 SignExtend32<26>(Addr) != Addr) 4909 return nullptr; // Top 6 bits have to be sext of immediate. 4910 4911 return DAG 4912 .getConstant( 4913 (int)C->getZExtValue() >> 2, SDLoc(Op), 4914 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4915 .getNode(); 4916 } 4917 4918 namespace { 4919 4920 struct TailCallArgumentInfo { 4921 SDValue Arg; 4922 SDValue FrameIdxOp; 4923 int FrameIdx = 0; 4924 4925 TailCallArgumentInfo() = default; 4926 }; 4927 4928 } // end anonymous namespace 4929 4930 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4931 static void StoreTailCallArgumentsToStackSlot( 4932 SelectionDAG &DAG, SDValue Chain, 4933 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4934 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4935 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4936 SDValue Arg = TailCallArgs[i].Arg; 4937 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4938 int FI = TailCallArgs[i].FrameIdx; 4939 // Store relative to framepointer. 4940 MemOpChains.push_back(DAG.getStore( 4941 Chain, dl, Arg, FIN, 4942 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4943 } 4944 } 4945 4946 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4947 /// the appropriate stack slot for the tail call optimized function call. 4948 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4949 SDValue OldRetAddr, SDValue OldFP, 4950 int SPDiff, const SDLoc &dl) { 4951 if (SPDiff) { 4952 // Calculate the new stack slot for the return address. 4953 MachineFunction &MF = DAG.getMachineFunction(); 4954 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4955 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4956 bool isPPC64 = Subtarget.isPPC64(); 4957 int SlotSize = isPPC64 ? 8 : 4; 4958 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4959 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4960 NewRetAddrLoc, true); 4961 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4962 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4963 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4964 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4965 } 4966 return Chain; 4967 } 4968 4969 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4970 /// the position of the argument. 4971 static void 4972 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4973 SDValue Arg, int SPDiff, unsigned ArgOffset, 4974 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4975 int Offset = ArgOffset + SPDiff; 4976 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4977 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4978 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4979 SDValue FIN = DAG.getFrameIndex(FI, VT); 4980 TailCallArgumentInfo Info; 4981 Info.Arg = Arg; 4982 Info.FrameIdxOp = FIN; 4983 Info.FrameIdx = FI; 4984 TailCallArguments.push_back(Info); 4985 } 4986 4987 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4988 /// stack slot. Returns the chain as result and the loaded frame pointers in 4989 /// LROpOut/FPOpout. Used when tail calling. 4990 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4991 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4992 SDValue &FPOpOut, const SDLoc &dl) const { 4993 if (SPDiff) { 4994 // Load the LR and FP stack slot for later adjusting. 4995 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4996 LROpOut = getReturnAddrFrameIndex(DAG); 4997 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4998 Chain = SDValue(LROpOut.getNode(), 1); 4999 } 5000 return Chain; 5001 } 5002 5003 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5004 /// by "Src" to address "Dst" of size "Size". Alignment information is 5005 /// specified by the specific parameter attribute. The copy will be passed as 5006 /// a byval function parameter. 5007 /// Sometimes what we are copying is the end of a larger object, the part that 5008 /// does not fit in registers. 5009 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5010 SDValue Chain, ISD::ArgFlagsTy Flags, 5011 SelectionDAG &DAG, const SDLoc &dl) { 5012 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5013 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5014 Flags.getNonZeroByValAlign(), false, false, false, 5015 MachinePointerInfo(), MachinePointerInfo()); 5016 } 5017 5018 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5019 /// tail calls. 5020 static void LowerMemOpCallTo( 5021 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5022 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5023 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5024 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5025 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5026 if (!isTailCall) { 5027 if (isVector) { 5028 SDValue StackPtr; 5029 if (isPPC64) 5030 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5031 else 5032 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5033 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5034 DAG.getConstant(ArgOffset, dl, PtrVT)); 5035 } 5036 MemOpChains.push_back( 5037 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5038 // Calculate and remember argument location. 5039 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5040 TailCallArguments); 5041 } 5042 5043 static void 5044 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5045 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5046 SDValue FPOp, 5047 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5048 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5049 // might overwrite each other in case of tail call optimization. 5050 SmallVector<SDValue, 8> MemOpChains2; 5051 // Do not flag preceding copytoreg stuff together with the following stuff. 5052 InFlag = SDValue(); 5053 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5054 MemOpChains2, dl); 5055 if (!MemOpChains2.empty()) 5056 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5057 5058 // Store the return address to the appropriate stack slot. 5059 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5060 5061 // Emit callseq_end just before tailcall node. 5062 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5063 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5064 InFlag = Chain.getValue(1); 5065 } 5066 5067 // Is this global address that of a function that can be called by name? (as 5068 // opposed to something that must hold a descriptor for an indirect call). 5069 static bool isFunctionGlobalAddress(SDValue Callee) { 5070 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5071 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5072 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5073 return false; 5074 5075 return G->getGlobal()->getValueType()->isFunctionTy(); 5076 } 5077 5078 return false; 5079 } 5080 5081 SDValue PPCTargetLowering::LowerCallResult( 5082 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5083 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5084 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5085 SmallVector<CCValAssign, 16> RVLocs; 5086 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5087 *DAG.getContext()); 5088 5089 CCRetInfo.AnalyzeCallResult( 5090 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5091 ? RetCC_PPC_Cold 5092 : RetCC_PPC); 5093 5094 // Copy all of the result registers out of their specified physreg. 5095 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5096 CCValAssign &VA = RVLocs[i]; 5097 assert(VA.isRegLoc() && "Can only return in registers!"); 5098 5099 SDValue Val; 5100 5101 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5102 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5103 InFlag); 5104 Chain = Lo.getValue(1); 5105 InFlag = Lo.getValue(2); 5106 VA = RVLocs[++i]; // skip ahead to next loc 5107 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5108 InFlag); 5109 Chain = Hi.getValue(1); 5110 InFlag = Hi.getValue(2); 5111 if (!Subtarget.isLittleEndian()) 5112 std::swap (Lo, Hi); 5113 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5114 } else { 5115 Val = DAG.getCopyFromReg(Chain, dl, 5116 VA.getLocReg(), VA.getLocVT(), InFlag); 5117 Chain = Val.getValue(1); 5118 InFlag = Val.getValue(2); 5119 } 5120 5121 switch (VA.getLocInfo()) { 5122 default: llvm_unreachable("Unknown loc info!"); 5123 case CCValAssign::Full: break; 5124 case CCValAssign::AExt: 5125 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5126 break; 5127 case CCValAssign::ZExt: 5128 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5129 DAG.getValueType(VA.getValVT())); 5130 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5131 break; 5132 case CCValAssign::SExt: 5133 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5134 DAG.getValueType(VA.getValVT())); 5135 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5136 break; 5137 } 5138 5139 InVals.push_back(Val); 5140 } 5141 5142 return Chain; 5143 } 5144 5145 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5146 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5147 // PatchPoint calls are not indirect. 5148 if (isPatchPoint) 5149 return false; 5150 5151 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5152 return false; 5153 5154 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5155 // becuase the immediate function pointer points to a descriptor instead of 5156 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5157 // pointer immediate points to the global entry point, while the BLA would 5158 // need to jump to the local entry point (see rL211174). 5159 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5160 isBLACompatibleAddress(Callee, DAG)) 5161 return false; 5162 5163 return true; 5164 } 5165 5166 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5167 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5168 return Subtarget.isAIXABI() || 5169 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5170 } 5171 5172 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5173 const Function &Caller, 5174 const SDValue &Callee, 5175 const PPCSubtarget &Subtarget, 5176 const TargetMachine &TM) { 5177 if (CFlags.IsTailCall) 5178 return PPCISD::TC_RETURN; 5179 5180 // This is a call through a function pointer. 5181 if (CFlags.IsIndirect) { 5182 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5183 // indirect calls. The save of the caller's TOC pointer to the stack will be 5184 // inserted into the DAG as part of call lowering. The restore of the TOC 5185 // pointer is modeled by using a pseudo instruction for the call opcode that 5186 // represents the 2 instruction sequence of an indirect branch and link, 5187 // immediately followed by a load of the TOC pointer from the the stack save 5188 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5189 // as it is not saved or used. 5190 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5191 : PPCISD::BCTRL; 5192 } 5193 5194 if (Subtarget.isUsingPCRelativeCalls()) { 5195 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5196 return PPCISD::CALL_NOTOC; 5197 } 5198 5199 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5200 // immediately following the call instruction if the caller and callee may 5201 // have different TOC bases. At link time if the linker determines the calls 5202 // may not share a TOC base, the call is redirected to a trampoline inserted 5203 // by the linker. The trampoline will (among other things) save the callers 5204 // TOC pointer at an ABI designated offset in the linkage area and the linker 5205 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5206 // into gpr2. 5207 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5208 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5209 : PPCISD::CALL_NOP; 5210 5211 return PPCISD::CALL; 5212 } 5213 5214 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5215 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5216 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5217 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5218 return SDValue(Dest, 0); 5219 5220 // Returns true if the callee is local, and false otherwise. 5221 auto isLocalCallee = [&]() { 5222 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5223 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5224 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5225 5226 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5227 !dyn_cast_or_null<GlobalIFunc>(GV); 5228 }; 5229 5230 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5231 // a static relocation model causes some versions of GNU LD (2.17.50, at 5232 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5233 // built with secure-PLT. 5234 bool UsePlt = 5235 Subtarget.is32BitELFABI() && !isLocalCallee() && 5236 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5237 5238 // On AIX, direct function calls reference the symbol for the function's 5239 // entry point, which is named by prepending a "." before the function's 5240 // C-linkage name. 5241 const auto getAIXFuncEntryPointSymbolSDNode = 5242 [&](StringRef FuncName, bool IsDeclaration, 5243 const XCOFF::StorageClass &SC) { 5244 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5245 5246 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5247 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5248 5249 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5250 // On AIX, an undefined symbol needs to be associated with a 5251 // MCSectionXCOFF to get the correct storage mapping class. 5252 // In this case, XCOFF::XMC_PR. 5253 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5254 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5255 SectionKind::getMetadata()); 5256 S->setRepresentedCsect(Sec); 5257 } 5258 5259 MVT PtrVT = 5260 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5261 return DAG.getMCSymbol(S, PtrVT); 5262 }; 5263 5264 if (isFunctionGlobalAddress(Callee)) { 5265 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5266 const GlobalValue *GV = G->getGlobal(); 5267 5268 if (!Subtarget.isAIXABI()) 5269 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5270 UsePlt ? PPCII::MO_PLT : 0); 5271 5272 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5273 const GlobalObject *GO = cast<GlobalObject>(GV); 5274 const XCOFF::StorageClass SC = 5275 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5276 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5277 SC); 5278 } 5279 5280 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5281 const char *SymName = S->getSymbol(); 5282 if (!Subtarget.isAIXABI()) 5283 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5284 UsePlt ? PPCII::MO_PLT : 0); 5285 5286 // If there exists a user-declared function whose name is the same as the 5287 // ExternalSymbol's, then we pick up the user-declared version. 5288 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5289 if (const Function *F = 5290 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5291 const XCOFF::StorageClass SC = 5292 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5293 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5294 SC); 5295 } 5296 5297 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5298 } 5299 5300 // No transformation needed. 5301 assert(Callee.getNode() && "What no callee?"); 5302 return Callee; 5303 } 5304 5305 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5306 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5307 "Expected a CALLSEQ_STARTSDNode."); 5308 5309 // The last operand is the chain, except when the node has glue. If the node 5310 // has glue, then the last operand is the glue, and the chain is the second 5311 // last operand. 5312 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5313 if (LastValue.getValueType() != MVT::Glue) 5314 return LastValue; 5315 5316 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5317 } 5318 5319 // Creates the node that moves a functions address into the count register 5320 // to prepare for an indirect call instruction. 5321 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5322 SDValue &Glue, SDValue &Chain, 5323 const SDLoc &dl) { 5324 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5325 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5326 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5327 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5328 // The glue is the second value produced. 5329 Glue = Chain.getValue(1); 5330 } 5331 5332 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5333 SDValue &Glue, SDValue &Chain, 5334 SDValue CallSeqStart, 5335 const CallBase *CB, const SDLoc &dl, 5336 bool hasNest, 5337 const PPCSubtarget &Subtarget) { 5338 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5339 // entry point, but to the function descriptor (the function entry point 5340 // address is part of the function descriptor though). 5341 // The function descriptor is a three doubleword structure with the 5342 // following fields: function entry point, TOC base address and 5343 // environment pointer. 5344 // Thus for a call through a function pointer, the following actions need 5345 // to be performed: 5346 // 1. Save the TOC of the caller in the TOC save area of its stack 5347 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5348 // 2. Load the address of the function entry point from the function 5349 // descriptor. 5350 // 3. Load the TOC of the callee from the function descriptor into r2. 5351 // 4. Load the environment pointer from the function descriptor into 5352 // r11. 5353 // 5. Branch to the function entry point address. 5354 // 6. On return of the callee, the TOC of the caller needs to be 5355 // restored (this is done in FinishCall()). 5356 // 5357 // The loads are scheduled at the beginning of the call sequence, and the 5358 // register copies are flagged together to ensure that no other 5359 // operations can be scheduled in between. E.g. without flagging the 5360 // copies together, a TOC access in the caller could be scheduled between 5361 // the assignment of the callee TOC and the branch to the callee, which leads 5362 // to incorrect code. 5363 5364 // Start by loading the function address from the descriptor. 5365 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5366 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5367 ? (MachineMemOperand::MODereferenceable | 5368 MachineMemOperand::MOInvariant) 5369 : MachineMemOperand::MONone; 5370 5371 MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr); 5372 5373 // Registers used in building the DAG. 5374 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5375 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5376 5377 // Offsets of descriptor members. 5378 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5379 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5380 5381 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5382 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5383 5384 // One load for the functions entry point address. 5385 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5386 Alignment, MMOFlags); 5387 5388 // One for loading the TOC anchor for the module that contains the called 5389 // function. 5390 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5391 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5392 SDValue TOCPtr = 5393 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5394 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5395 5396 // One for loading the environment pointer. 5397 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5398 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5399 SDValue LoadEnvPtr = 5400 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5401 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5402 5403 5404 // Then copy the newly loaded TOC anchor to the TOC pointer. 5405 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5406 Chain = TOCVal.getValue(0); 5407 Glue = TOCVal.getValue(1); 5408 5409 // If the function call has an explicit 'nest' parameter, it takes the 5410 // place of the environment pointer. 5411 assert((!hasNest || !Subtarget.isAIXABI()) && 5412 "Nest parameter is not supported on AIX."); 5413 if (!hasNest) { 5414 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5415 Chain = EnvVal.getValue(0); 5416 Glue = EnvVal.getValue(1); 5417 } 5418 5419 // The rest of the indirect call sequence is the same as the non-descriptor 5420 // DAG. 5421 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5422 } 5423 5424 static void 5425 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5426 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5427 SelectionDAG &DAG, 5428 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5429 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5430 const PPCSubtarget &Subtarget) { 5431 const bool IsPPC64 = Subtarget.isPPC64(); 5432 // MVT for a general purpose register. 5433 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5434 5435 // First operand is always the chain. 5436 Ops.push_back(Chain); 5437 5438 // If it's a direct call pass the callee as the second operand. 5439 if (!CFlags.IsIndirect) 5440 Ops.push_back(Callee); 5441 else { 5442 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5443 5444 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5445 // on the stack (this would have been done in `LowerCall_64SVR4` or 5446 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5447 // represents both the indirect branch and a load that restores the TOC 5448 // pointer from the linkage area. The operand for the TOC restore is an add 5449 // of the TOC save offset to the stack pointer. This must be the second 5450 // operand: after the chain input but before any other variadic arguments. 5451 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5452 // saved or used. 5453 if (isTOCSaveRestoreRequired(Subtarget)) { 5454 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5455 5456 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5457 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5458 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5459 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5460 Ops.push_back(AddTOC); 5461 } 5462 5463 // Add the register used for the environment pointer. 5464 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5465 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5466 RegVT)); 5467 5468 5469 // Add CTR register as callee so a bctr can be emitted later. 5470 if (CFlags.IsTailCall) 5471 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5472 } 5473 5474 // If this is a tail call add stack pointer delta. 5475 if (CFlags.IsTailCall) 5476 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5477 5478 // Add argument registers to the end of the list so that they are known live 5479 // into the call. 5480 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5481 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5482 RegsToPass[i].second.getValueType())); 5483 5484 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5485 // no way to mark dependencies as implicit here. 5486 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5487 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5488 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5489 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5490 5491 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5492 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5493 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5494 5495 // Add a register mask operand representing the call-preserved registers. 5496 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5497 const uint32_t *Mask = 5498 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5499 assert(Mask && "Missing call preserved mask for calling convention"); 5500 Ops.push_back(DAG.getRegisterMask(Mask)); 5501 5502 // If the glue is valid, it is the last operand. 5503 if (Glue.getNode()) 5504 Ops.push_back(Glue); 5505 } 5506 5507 SDValue PPCTargetLowering::FinishCall( 5508 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5509 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5510 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5511 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5512 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5513 5514 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5515 Subtarget.isAIXABI()) 5516 setUsesTOCBasePtr(DAG); 5517 5518 unsigned CallOpc = 5519 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5520 Subtarget, DAG.getTarget()); 5521 5522 if (!CFlags.IsIndirect) 5523 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5524 else if (Subtarget.usesFunctionDescriptors()) 5525 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5526 dl, CFlags.HasNest, Subtarget); 5527 else 5528 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5529 5530 // Build the operand list for the call instruction. 5531 SmallVector<SDValue, 8> Ops; 5532 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5533 SPDiff, Subtarget); 5534 5535 // Emit tail call. 5536 if (CFlags.IsTailCall) { 5537 // Indirect tail call when using PC Relative calls do not have the same 5538 // constraints. 5539 assert(((Callee.getOpcode() == ISD::Register && 5540 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5541 Callee.getOpcode() == ISD::TargetExternalSymbol || 5542 Callee.getOpcode() == ISD::TargetGlobalAddress || 5543 isa<ConstantSDNode>(Callee) || 5544 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5545 "Expecting a global address, external symbol, absolute value, " 5546 "register or an indirect tail call when PC Relative calls are " 5547 "used."); 5548 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5549 assert(CallOpc == PPCISD::TC_RETURN && 5550 "Unexpected call opcode for a tail call."); 5551 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5552 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5553 } 5554 5555 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5556 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5557 Glue = Chain.getValue(1); 5558 5559 // When performing tail call optimization the callee pops its arguments off 5560 // the stack. Account for this here so these bytes can be pushed back on in 5561 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5562 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5563 getTargetMachine().Options.GuaranteedTailCallOpt) 5564 ? NumBytes 5565 : 0; 5566 5567 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5568 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5569 Glue, dl); 5570 Glue = Chain.getValue(1); 5571 5572 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5573 DAG, InVals); 5574 } 5575 5576 SDValue 5577 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5578 SmallVectorImpl<SDValue> &InVals) const { 5579 SelectionDAG &DAG = CLI.DAG; 5580 SDLoc &dl = CLI.DL; 5581 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5582 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5583 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5584 SDValue Chain = CLI.Chain; 5585 SDValue Callee = CLI.Callee; 5586 bool &isTailCall = CLI.IsTailCall; 5587 CallingConv::ID CallConv = CLI.CallConv; 5588 bool isVarArg = CLI.IsVarArg; 5589 bool isPatchPoint = CLI.IsPatchPoint; 5590 const CallBase *CB = CLI.CB; 5591 5592 if (isTailCall) { 5593 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5594 isTailCall = false; 5595 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5596 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5597 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5598 else 5599 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5600 Ins, DAG); 5601 if (isTailCall) { 5602 ++NumTailCalls; 5603 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5604 ++NumSiblingCalls; 5605 5606 // PC Relative calls no longer guarantee that the callee is a Global 5607 // Address Node. The callee could be an indirect tail call in which 5608 // case the SDValue for the callee could be a load (to load the address 5609 // of a function pointer) or it may be a register copy (to move the 5610 // address of the callee from a function parameter into a virtual 5611 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5612 assert((Subtarget.isUsingPCRelativeCalls() || 5613 isa<GlobalAddressSDNode>(Callee)) && 5614 "Callee should be an llvm::Function object."); 5615 5616 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5617 << "\nTCO callee: "); 5618 LLVM_DEBUG(Callee.dump()); 5619 } 5620 } 5621 5622 if (!isTailCall && CB && CB->isMustTailCall()) 5623 report_fatal_error("failed to perform tail call elimination on a call " 5624 "site marked musttail"); 5625 5626 // When long calls (i.e. indirect calls) are always used, calls are always 5627 // made via function pointer. If we have a function name, first translate it 5628 // into a pointer. 5629 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5630 !isTailCall) 5631 Callee = LowerGlobalAddress(Callee, DAG); 5632 5633 CallFlags CFlags( 5634 CallConv, isTailCall, isVarArg, isPatchPoint, 5635 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5636 // hasNest 5637 Subtarget.is64BitELFABI() && 5638 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5639 5640 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5641 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5642 InVals, CB); 5643 5644 if (Subtarget.isSVR4ABI()) 5645 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5646 InVals, CB); 5647 5648 if (Subtarget.isAIXABI()) 5649 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5650 InVals, CB); 5651 5652 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5653 InVals, CB); 5654 } 5655 5656 SDValue PPCTargetLowering::LowerCall_32SVR4( 5657 SDValue Chain, SDValue Callee, CallFlags CFlags, 5658 const SmallVectorImpl<ISD::OutputArg> &Outs, 5659 const SmallVectorImpl<SDValue> &OutVals, 5660 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5661 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5662 const CallBase *CB) const { 5663 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5664 // of the 32-bit SVR4 ABI stack frame layout. 5665 5666 const CallingConv::ID CallConv = CFlags.CallConv; 5667 const bool IsVarArg = CFlags.IsVarArg; 5668 const bool IsTailCall = CFlags.IsTailCall; 5669 5670 assert((CallConv == CallingConv::C || 5671 CallConv == CallingConv::Cold || 5672 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5673 5674 unsigned PtrByteSize = 4; 5675 5676 MachineFunction &MF = DAG.getMachineFunction(); 5677 5678 // Mark this function as potentially containing a function that contains a 5679 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5680 // and restoring the callers stack pointer in this functions epilog. This is 5681 // done because by tail calling the called function might overwrite the value 5682 // in this function's (MF) stack pointer stack slot 0(SP). 5683 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5684 CallConv == CallingConv::Fast) 5685 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5686 5687 // Count how many bytes are to be pushed on the stack, including the linkage 5688 // area, parameter list area and the part of the local variable space which 5689 // contains copies of aggregates which are passed by value. 5690 5691 // Assign locations to all of the outgoing arguments. 5692 SmallVector<CCValAssign, 16> ArgLocs; 5693 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5694 5695 // Reserve space for the linkage area on the stack. 5696 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5697 PtrByteSize); 5698 if (useSoftFloat()) 5699 CCInfo.PreAnalyzeCallOperands(Outs); 5700 5701 if (IsVarArg) { 5702 // Handle fixed and variable vector arguments differently. 5703 // Fixed vector arguments go into registers as long as registers are 5704 // available. Variable vector arguments always go into memory. 5705 unsigned NumArgs = Outs.size(); 5706 5707 for (unsigned i = 0; i != NumArgs; ++i) { 5708 MVT ArgVT = Outs[i].VT; 5709 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5710 bool Result; 5711 5712 if (Outs[i].IsFixed) { 5713 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5714 CCInfo); 5715 } else { 5716 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5717 ArgFlags, CCInfo); 5718 } 5719 5720 if (Result) { 5721 #ifndef NDEBUG 5722 errs() << "Call operand #" << i << " has unhandled type " 5723 << EVT(ArgVT).getEVTString() << "\n"; 5724 #endif 5725 llvm_unreachable(nullptr); 5726 } 5727 } 5728 } else { 5729 // All arguments are treated the same. 5730 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5731 } 5732 CCInfo.clearWasPPCF128(); 5733 5734 // Assign locations to all of the outgoing aggregate by value arguments. 5735 SmallVector<CCValAssign, 16> ByValArgLocs; 5736 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5737 5738 // Reserve stack space for the allocations in CCInfo. 5739 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5740 5741 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5742 5743 // Size of the linkage area, parameter list area and the part of the local 5744 // space variable where copies of aggregates which are passed by value are 5745 // stored. 5746 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5747 5748 // Calculate by how many bytes the stack has to be adjusted in case of tail 5749 // call optimization. 5750 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5751 5752 // Adjust the stack pointer for the new arguments... 5753 // These operations are automatically eliminated by the prolog/epilog pass 5754 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5755 SDValue CallSeqStart = Chain; 5756 5757 // Load the return address and frame pointer so it can be moved somewhere else 5758 // later. 5759 SDValue LROp, FPOp; 5760 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5761 5762 // Set up a copy of the stack pointer for use loading and storing any 5763 // arguments that may not fit in the registers available for argument 5764 // passing. 5765 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5766 5767 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5768 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5769 SmallVector<SDValue, 8> MemOpChains; 5770 5771 bool seenFloatArg = false; 5772 // Walk the register/memloc assignments, inserting copies/loads. 5773 // i - Tracks the index into the list of registers allocated for the call 5774 // RealArgIdx - Tracks the index into the list of actual function arguments 5775 // j - Tracks the index into the list of byval arguments 5776 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5777 i != e; 5778 ++i, ++RealArgIdx) { 5779 CCValAssign &VA = ArgLocs[i]; 5780 SDValue Arg = OutVals[RealArgIdx]; 5781 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5782 5783 if (Flags.isByVal()) { 5784 // Argument is an aggregate which is passed by value, thus we need to 5785 // create a copy of it in the local variable space of the current stack 5786 // frame (which is the stack frame of the caller) and pass the address of 5787 // this copy to the callee. 5788 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5789 CCValAssign &ByValVA = ByValArgLocs[j++]; 5790 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5791 5792 // Memory reserved in the local variable space of the callers stack frame. 5793 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5794 5795 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5796 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5797 StackPtr, PtrOff); 5798 5799 // Create a copy of the argument in the local area of the current 5800 // stack frame. 5801 SDValue MemcpyCall = 5802 CreateCopyOfByValArgument(Arg, PtrOff, 5803 CallSeqStart.getNode()->getOperand(0), 5804 Flags, DAG, dl); 5805 5806 // This must go outside the CALLSEQ_START..END. 5807 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5808 SDLoc(MemcpyCall)); 5809 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5810 NewCallSeqStart.getNode()); 5811 Chain = CallSeqStart = NewCallSeqStart; 5812 5813 // Pass the address of the aggregate copy on the stack either in a 5814 // physical register or in the parameter list area of the current stack 5815 // frame to the callee. 5816 Arg = PtrOff; 5817 } 5818 5819 // When useCRBits() is true, there can be i1 arguments. 5820 // It is because getRegisterType(MVT::i1) => MVT::i1, 5821 // and for other integer types getRegisterType() => MVT::i32. 5822 // Extend i1 and ensure callee will get i32. 5823 if (Arg.getValueType() == MVT::i1) 5824 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5825 dl, MVT::i32, Arg); 5826 5827 if (VA.isRegLoc()) { 5828 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5829 // Put argument in a physical register. 5830 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5831 bool IsLE = Subtarget.isLittleEndian(); 5832 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5833 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5834 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5835 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5836 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5837 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5838 SVal.getValue(0))); 5839 } else 5840 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5841 } else { 5842 // Put argument in the parameter list area of the current stack frame. 5843 assert(VA.isMemLoc()); 5844 unsigned LocMemOffset = VA.getLocMemOffset(); 5845 5846 if (!IsTailCall) { 5847 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5848 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5849 StackPtr, PtrOff); 5850 5851 MemOpChains.push_back( 5852 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5853 } else { 5854 // Calculate and remember argument location. 5855 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5856 TailCallArguments); 5857 } 5858 } 5859 } 5860 5861 if (!MemOpChains.empty()) 5862 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5863 5864 // Build a sequence of copy-to-reg nodes chained together with token chain 5865 // and flag operands which copy the outgoing args into the appropriate regs. 5866 SDValue InFlag; 5867 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5868 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5869 RegsToPass[i].second, InFlag); 5870 InFlag = Chain.getValue(1); 5871 } 5872 5873 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5874 // registers. 5875 if (IsVarArg) { 5876 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5877 SDValue Ops[] = { Chain, InFlag }; 5878 5879 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5880 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5881 5882 InFlag = Chain.getValue(1); 5883 } 5884 5885 if (IsTailCall) 5886 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5887 TailCallArguments); 5888 5889 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5890 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5891 } 5892 5893 // Copy an argument into memory, being careful to do this outside the 5894 // call sequence for the call to which the argument belongs. 5895 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5896 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5897 SelectionDAG &DAG, const SDLoc &dl) const { 5898 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5899 CallSeqStart.getNode()->getOperand(0), 5900 Flags, DAG, dl); 5901 // The MEMCPY must go outside the CALLSEQ_START..END. 5902 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5903 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5904 SDLoc(MemcpyCall)); 5905 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5906 NewCallSeqStart.getNode()); 5907 return NewCallSeqStart; 5908 } 5909 5910 SDValue PPCTargetLowering::LowerCall_64SVR4( 5911 SDValue Chain, SDValue Callee, CallFlags CFlags, 5912 const SmallVectorImpl<ISD::OutputArg> &Outs, 5913 const SmallVectorImpl<SDValue> &OutVals, 5914 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5915 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5916 const CallBase *CB) const { 5917 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5918 bool isLittleEndian = Subtarget.isLittleEndian(); 5919 unsigned NumOps = Outs.size(); 5920 bool IsSibCall = false; 5921 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5922 5923 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5924 unsigned PtrByteSize = 8; 5925 5926 MachineFunction &MF = DAG.getMachineFunction(); 5927 5928 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5929 IsSibCall = true; 5930 5931 // Mark this function as potentially containing a function that contains a 5932 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5933 // and restoring the callers stack pointer in this functions epilog. This is 5934 // done because by tail calling the called function might overwrite the value 5935 // in this function's (MF) stack pointer stack slot 0(SP). 5936 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5937 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5938 5939 assert(!(IsFastCall && CFlags.IsVarArg) && 5940 "fastcc not supported on varargs functions"); 5941 5942 // Count how many bytes are to be pushed on the stack, including the linkage 5943 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5944 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5945 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5946 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5947 unsigned NumBytes = LinkageSize; 5948 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5949 unsigned &QFPR_idx = FPR_idx; 5950 5951 static const MCPhysReg GPR[] = { 5952 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5953 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5954 }; 5955 static const MCPhysReg VR[] = { 5956 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5957 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5958 }; 5959 5960 const unsigned NumGPRs = array_lengthof(GPR); 5961 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5962 const unsigned NumVRs = array_lengthof(VR); 5963 const unsigned NumQFPRs = NumFPRs; 5964 5965 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5966 // can be passed to the callee in registers. 5967 // For the fast calling convention, there is another check below. 5968 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5969 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5970 if (!HasParameterArea) { 5971 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5972 unsigned AvailableFPRs = NumFPRs; 5973 unsigned AvailableVRs = NumVRs; 5974 unsigned NumBytesTmp = NumBytes; 5975 for (unsigned i = 0; i != NumOps; ++i) { 5976 if (Outs[i].Flags.isNest()) continue; 5977 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5978 PtrByteSize, LinkageSize, ParamAreaSize, 5979 NumBytesTmp, AvailableFPRs, AvailableVRs, 5980 Subtarget.hasQPX())) 5981 HasParameterArea = true; 5982 } 5983 } 5984 5985 // When using the fast calling convention, we don't provide backing for 5986 // arguments that will be in registers. 5987 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5988 5989 // Avoid allocating parameter area for fastcc functions if all the arguments 5990 // can be passed in the registers. 5991 if (IsFastCall) 5992 HasParameterArea = false; 5993 5994 // Add up all the space actually used. 5995 for (unsigned i = 0; i != NumOps; ++i) { 5996 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5997 EVT ArgVT = Outs[i].VT; 5998 EVT OrigVT = Outs[i].ArgVT; 5999 6000 if (Flags.isNest()) 6001 continue; 6002 6003 if (IsFastCall) { 6004 if (Flags.isByVal()) { 6005 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6006 if (NumGPRsUsed > NumGPRs) 6007 HasParameterArea = true; 6008 } else { 6009 switch (ArgVT.getSimpleVT().SimpleTy) { 6010 default: llvm_unreachable("Unexpected ValueType for argument!"); 6011 case MVT::i1: 6012 case MVT::i32: 6013 case MVT::i64: 6014 if (++NumGPRsUsed <= NumGPRs) 6015 continue; 6016 break; 6017 case MVT::v4i32: 6018 case MVT::v8i16: 6019 case MVT::v16i8: 6020 case MVT::v2f64: 6021 case MVT::v2i64: 6022 case MVT::v1i128: 6023 case MVT::f128: 6024 if (++NumVRsUsed <= NumVRs) 6025 continue; 6026 break; 6027 case MVT::v4f32: 6028 // When using QPX, this is handled like a FP register, otherwise, it 6029 // is an Altivec register. 6030 if (Subtarget.hasQPX()) { 6031 if (++NumFPRsUsed <= NumFPRs) 6032 continue; 6033 } else { 6034 if (++NumVRsUsed <= NumVRs) 6035 continue; 6036 } 6037 break; 6038 case MVT::f32: 6039 case MVT::f64: 6040 case MVT::v4f64: // QPX 6041 case MVT::v4i1: // QPX 6042 if (++NumFPRsUsed <= NumFPRs) 6043 continue; 6044 break; 6045 } 6046 HasParameterArea = true; 6047 } 6048 } 6049 6050 /* Respect alignment of argument on the stack. */ 6051 auto Alignement = 6052 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6053 NumBytes = alignTo(NumBytes, Alignement); 6054 6055 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6056 if (Flags.isInConsecutiveRegsLast()) 6057 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6058 } 6059 6060 unsigned NumBytesActuallyUsed = NumBytes; 6061 6062 // In the old ELFv1 ABI, 6063 // the prolog code of the callee may store up to 8 GPR argument registers to 6064 // the stack, allowing va_start to index over them in memory if its varargs. 6065 // Because we cannot tell if this is needed on the caller side, we have to 6066 // conservatively assume that it is needed. As such, make sure we have at 6067 // least enough stack space for the caller to store the 8 GPRs. 6068 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6069 // really requires memory operands, e.g. a vararg function. 6070 if (HasParameterArea) 6071 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6072 else 6073 NumBytes = LinkageSize; 6074 6075 // Tail call needs the stack to be aligned. 6076 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6077 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6078 6079 int SPDiff = 0; 6080 6081 // Calculate by how many bytes the stack has to be adjusted in case of tail 6082 // call optimization. 6083 if (!IsSibCall) 6084 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6085 6086 // To protect arguments on the stack from being clobbered in a tail call, 6087 // force all the loads to happen before doing any other lowering. 6088 if (CFlags.IsTailCall) 6089 Chain = DAG.getStackArgumentTokenFactor(Chain); 6090 6091 // Adjust the stack pointer for the new arguments... 6092 // These operations are automatically eliminated by the prolog/epilog pass 6093 if (!IsSibCall) 6094 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6095 SDValue CallSeqStart = Chain; 6096 6097 // Load the return address and frame pointer so it can be move somewhere else 6098 // later. 6099 SDValue LROp, FPOp; 6100 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6101 6102 // Set up a copy of the stack pointer for use loading and storing any 6103 // arguments that may not fit in the registers available for argument 6104 // passing. 6105 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6106 6107 // Figure out which arguments are going to go in registers, and which in 6108 // memory. Also, if this is a vararg function, floating point operations 6109 // must be stored to our stack, and loaded into integer regs as well, if 6110 // any integer regs are available for argument passing. 6111 unsigned ArgOffset = LinkageSize; 6112 6113 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6114 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6115 6116 SmallVector<SDValue, 8> MemOpChains; 6117 for (unsigned i = 0; i != NumOps; ++i) { 6118 SDValue Arg = OutVals[i]; 6119 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6120 EVT ArgVT = Outs[i].VT; 6121 EVT OrigVT = Outs[i].ArgVT; 6122 6123 // PtrOff will be used to store the current argument to the stack if a 6124 // register cannot be found for it. 6125 SDValue PtrOff; 6126 6127 // We re-align the argument offset for each argument, except when using the 6128 // fast calling convention, when we need to make sure we do that only when 6129 // we'll actually use a stack slot. 6130 auto ComputePtrOff = [&]() { 6131 /* Respect alignment of argument on the stack. */ 6132 auto Alignment = 6133 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6134 ArgOffset = alignTo(ArgOffset, Alignment); 6135 6136 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6137 6138 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6139 }; 6140 6141 if (!IsFastCall) { 6142 ComputePtrOff(); 6143 6144 /* Compute GPR index associated with argument offset. */ 6145 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6146 GPR_idx = std::min(GPR_idx, NumGPRs); 6147 } 6148 6149 // Promote integers to 64-bit values. 6150 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6151 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6152 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6153 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6154 } 6155 6156 // FIXME memcpy is used way more than necessary. Correctness first. 6157 // Note: "by value" is code for passing a structure by value, not 6158 // basic types. 6159 if (Flags.isByVal()) { 6160 // Note: Size includes alignment padding, so 6161 // struct x { short a; char b; } 6162 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6163 // These are the proper values we need for right-justifying the 6164 // aggregate in a parameter register. 6165 unsigned Size = Flags.getByValSize(); 6166 6167 // An empty aggregate parameter takes up no storage and no 6168 // registers. 6169 if (Size == 0) 6170 continue; 6171 6172 if (IsFastCall) 6173 ComputePtrOff(); 6174 6175 // All aggregates smaller than 8 bytes must be passed right-justified. 6176 if (Size==1 || Size==2 || Size==4) { 6177 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6178 if (GPR_idx != NumGPRs) { 6179 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6180 MachinePointerInfo(), VT); 6181 MemOpChains.push_back(Load.getValue(1)); 6182 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6183 6184 ArgOffset += PtrByteSize; 6185 continue; 6186 } 6187 } 6188 6189 if (GPR_idx == NumGPRs && Size < 8) { 6190 SDValue AddPtr = PtrOff; 6191 if (!isLittleEndian) { 6192 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6193 PtrOff.getValueType()); 6194 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6195 } 6196 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6197 CallSeqStart, 6198 Flags, DAG, dl); 6199 ArgOffset += PtrByteSize; 6200 continue; 6201 } 6202 // Copy entire object into memory. There are cases where gcc-generated 6203 // code assumes it is there, even if it could be put entirely into 6204 // registers. (This is not what the doc says.) 6205 6206 // FIXME: The above statement is likely due to a misunderstanding of the 6207 // documents. All arguments must be copied into the parameter area BY 6208 // THE CALLEE in the event that the callee takes the address of any 6209 // formal argument. That has not yet been implemented. However, it is 6210 // reasonable to use the stack area as a staging area for the register 6211 // load. 6212 6213 // Skip this for small aggregates, as we will use the same slot for a 6214 // right-justified copy, below. 6215 if (Size >= 8) 6216 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6217 CallSeqStart, 6218 Flags, DAG, dl); 6219 6220 // When a register is available, pass a small aggregate right-justified. 6221 if (Size < 8 && GPR_idx != NumGPRs) { 6222 // The easiest way to get this right-justified in a register 6223 // is to copy the structure into the rightmost portion of a 6224 // local variable slot, then load the whole slot into the 6225 // register. 6226 // FIXME: The memcpy seems to produce pretty awful code for 6227 // small aggregates, particularly for packed ones. 6228 // FIXME: It would be preferable to use the slot in the 6229 // parameter save area instead of a new local variable. 6230 SDValue AddPtr = PtrOff; 6231 if (!isLittleEndian) { 6232 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6233 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6234 } 6235 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6236 CallSeqStart, 6237 Flags, DAG, dl); 6238 6239 // Load the slot into the register. 6240 SDValue Load = 6241 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6242 MemOpChains.push_back(Load.getValue(1)); 6243 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6244 6245 // Done with this argument. 6246 ArgOffset += PtrByteSize; 6247 continue; 6248 } 6249 6250 // For aggregates larger than PtrByteSize, copy the pieces of the 6251 // object that fit into registers from the parameter save area. 6252 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6253 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6254 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6255 if (GPR_idx != NumGPRs) { 6256 SDValue Load = 6257 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6258 MemOpChains.push_back(Load.getValue(1)); 6259 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6260 ArgOffset += PtrByteSize; 6261 } else { 6262 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6263 break; 6264 } 6265 } 6266 continue; 6267 } 6268 6269 switch (Arg.getSimpleValueType().SimpleTy) { 6270 default: llvm_unreachable("Unexpected ValueType for argument!"); 6271 case MVT::i1: 6272 case MVT::i32: 6273 case MVT::i64: 6274 if (Flags.isNest()) { 6275 // The 'nest' parameter, if any, is passed in R11. 6276 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6277 break; 6278 } 6279 6280 // These can be scalar arguments or elements of an integer array type 6281 // passed directly. Clang may use those instead of "byval" aggregate 6282 // types to avoid forcing arguments to memory unnecessarily. 6283 if (GPR_idx != NumGPRs) { 6284 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6285 } else { 6286 if (IsFastCall) 6287 ComputePtrOff(); 6288 6289 assert(HasParameterArea && 6290 "Parameter area must exist to pass an argument in memory."); 6291 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6292 true, CFlags.IsTailCall, false, MemOpChains, 6293 TailCallArguments, dl); 6294 if (IsFastCall) 6295 ArgOffset += PtrByteSize; 6296 } 6297 if (!IsFastCall) 6298 ArgOffset += PtrByteSize; 6299 break; 6300 case MVT::f32: 6301 case MVT::f64: { 6302 // These can be scalar arguments or elements of a float array type 6303 // passed directly. The latter are used to implement ELFv2 homogenous 6304 // float aggregates. 6305 6306 // Named arguments go into FPRs first, and once they overflow, the 6307 // remaining arguments go into GPRs and then the parameter save area. 6308 // Unnamed arguments for vararg functions always go to GPRs and 6309 // then the parameter save area. For now, put all arguments to vararg 6310 // routines always in both locations (FPR *and* GPR or stack slot). 6311 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6312 bool NeededLoad = false; 6313 6314 // First load the argument into the next available FPR. 6315 if (FPR_idx != NumFPRs) 6316 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6317 6318 // Next, load the argument into GPR or stack slot if needed. 6319 if (!NeedGPROrStack) 6320 ; 6321 else if (GPR_idx != NumGPRs && !IsFastCall) { 6322 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6323 // once we support fp <-> gpr moves. 6324 6325 // In the non-vararg case, this can only ever happen in the 6326 // presence of f32 array types, since otherwise we never run 6327 // out of FPRs before running out of GPRs. 6328 SDValue ArgVal; 6329 6330 // Double values are always passed in a single GPR. 6331 if (Arg.getValueType() != MVT::f32) { 6332 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6333 6334 // Non-array float values are extended and passed in a GPR. 6335 } else if (!Flags.isInConsecutiveRegs()) { 6336 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6337 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6338 6339 // If we have an array of floats, we collect every odd element 6340 // together with its predecessor into one GPR. 6341 } else if (ArgOffset % PtrByteSize != 0) { 6342 SDValue Lo, Hi; 6343 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6344 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6345 if (!isLittleEndian) 6346 std::swap(Lo, Hi); 6347 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6348 6349 // The final element, if even, goes into the first half of a GPR. 6350 } else if (Flags.isInConsecutiveRegsLast()) { 6351 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6352 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6353 if (!isLittleEndian) 6354 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6355 DAG.getConstant(32, dl, MVT::i32)); 6356 6357 // Non-final even elements are skipped; they will be handled 6358 // together the with subsequent argument on the next go-around. 6359 } else 6360 ArgVal = SDValue(); 6361 6362 if (ArgVal.getNode()) 6363 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6364 } else { 6365 if (IsFastCall) 6366 ComputePtrOff(); 6367 6368 // Single-precision floating-point values are mapped to the 6369 // second (rightmost) word of the stack doubleword. 6370 if (Arg.getValueType() == MVT::f32 && 6371 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6372 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6373 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6374 } 6375 6376 assert(HasParameterArea && 6377 "Parameter area must exist to pass an argument in memory."); 6378 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6379 true, CFlags.IsTailCall, false, MemOpChains, 6380 TailCallArguments, dl); 6381 6382 NeededLoad = true; 6383 } 6384 // When passing an array of floats, the array occupies consecutive 6385 // space in the argument area; only round up to the next doubleword 6386 // at the end of the array. Otherwise, each float takes 8 bytes. 6387 if (!IsFastCall || NeededLoad) { 6388 ArgOffset += (Arg.getValueType() == MVT::f32 && 6389 Flags.isInConsecutiveRegs()) ? 4 : 8; 6390 if (Flags.isInConsecutiveRegsLast()) 6391 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6392 } 6393 break; 6394 } 6395 case MVT::v4f32: 6396 case MVT::v4i32: 6397 case MVT::v8i16: 6398 case MVT::v16i8: 6399 case MVT::v2f64: 6400 case MVT::v2i64: 6401 case MVT::v1i128: 6402 case MVT::f128: 6403 if (!Subtarget.hasQPX()) { 6404 // These can be scalar arguments or elements of a vector array type 6405 // passed directly. The latter are used to implement ELFv2 homogenous 6406 // vector aggregates. 6407 6408 // For a varargs call, named arguments go into VRs or on the stack as 6409 // usual; unnamed arguments always go to the stack or the corresponding 6410 // GPRs when within range. For now, we always put the value in both 6411 // locations (or even all three). 6412 if (CFlags.IsVarArg) { 6413 assert(HasParameterArea && 6414 "Parameter area must exist if we have a varargs call."); 6415 // We could elide this store in the case where the object fits 6416 // entirely in R registers. Maybe later. 6417 SDValue Store = 6418 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6419 MemOpChains.push_back(Store); 6420 if (VR_idx != NumVRs) { 6421 SDValue Load = 6422 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6423 MemOpChains.push_back(Load.getValue(1)); 6424 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6425 } 6426 ArgOffset += 16; 6427 for (unsigned i=0; i<16; i+=PtrByteSize) { 6428 if (GPR_idx == NumGPRs) 6429 break; 6430 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6431 DAG.getConstant(i, dl, PtrVT)); 6432 SDValue Load = 6433 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6434 MemOpChains.push_back(Load.getValue(1)); 6435 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6436 } 6437 break; 6438 } 6439 6440 // Non-varargs Altivec params go into VRs or on the stack. 6441 if (VR_idx != NumVRs) { 6442 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6443 } else { 6444 if (IsFastCall) 6445 ComputePtrOff(); 6446 6447 assert(HasParameterArea && 6448 "Parameter area must exist to pass an argument in memory."); 6449 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6450 true, CFlags.IsTailCall, true, MemOpChains, 6451 TailCallArguments, dl); 6452 if (IsFastCall) 6453 ArgOffset += 16; 6454 } 6455 6456 if (!IsFastCall) 6457 ArgOffset += 16; 6458 break; 6459 } // not QPX 6460 6461 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6462 "Invalid QPX parameter type"); 6463 6464 LLVM_FALLTHROUGH; 6465 case MVT::v4f64: 6466 case MVT::v4i1: { 6467 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6468 if (CFlags.IsVarArg) { 6469 assert(HasParameterArea && 6470 "Parameter area must exist if we have a varargs call."); 6471 // We could elide this store in the case where the object fits 6472 // entirely in R registers. Maybe later. 6473 SDValue Store = 6474 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6475 MemOpChains.push_back(Store); 6476 if (QFPR_idx != NumQFPRs) { 6477 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6478 PtrOff, MachinePointerInfo()); 6479 MemOpChains.push_back(Load.getValue(1)); 6480 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6481 } 6482 ArgOffset += (IsF32 ? 16 : 32); 6483 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6484 if (GPR_idx == NumGPRs) 6485 break; 6486 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6487 DAG.getConstant(i, dl, PtrVT)); 6488 SDValue Load = 6489 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6490 MemOpChains.push_back(Load.getValue(1)); 6491 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6492 } 6493 break; 6494 } 6495 6496 // Non-varargs QPX params go into registers or on the stack. 6497 if (QFPR_idx != NumQFPRs) { 6498 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6499 } else { 6500 if (IsFastCall) 6501 ComputePtrOff(); 6502 6503 assert(HasParameterArea && 6504 "Parameter area must exist to pass an argument in memory."); 6505 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6506 true, CFlags.IsTailCall, true, MemOpChains, 6507 TailCallArguments, dl); 6508 if (IsFastCall) 6509 ArgOffset += (IsF32 ? 16 : 32); 6510 } 6511 6512 if (!IsFastCall) 6513 ArgOffset += (IsF32 ? 16 : 32); 6514 break; 6515 } 6516 } 6517 } 6518 6519 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6520 "mismatch in size of parameter area"); 6521 (void)NumBytesActuallyUsed; 6522 6523 if (!MemOpChains.empty()) 6524 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6525 6526 // Check if this is an indirect call (MTCTR/BCTRL). 6527 // See prepareDescriptorIndirectCall and buildCallOperands for more 6528 // information about calls through function pointers in the 64-bit SVR4 ABI. 6529 if (CFlags.IsIndirect) { 6530 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6531 // caller in the TOC save area. 6532 if (isTOCSaveRestoreRequired(Subtarget)) { 6533 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6534 // Load r2 into a virtual register and store it to the TOC save area. 6535 setUsesTOCBasePtr(DAG); 6536 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6537 // TOC save area offset. 6538 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6539 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6540 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6541 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6542 MachinePointerInfo::getStack( 6543 DAG.getMachineFunction(), TOCSaveOffset)); 6544 } 6545 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6546 // This does not mean the MTCTR instruction must use R12; it's easier 6547 // to model this as an extra parameter, so do that. 6548 if (isELFv2ABI && !CFlags.IsPatchPoint) 6549 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6550 } 6551 6552 // Build a sequence of copy-to-reg nodes chained together with token chain 6553 // and flag operands which copy the outgoing args into the appropriate regs. 6554 SDValue InFlag; 6555 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6556 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6557 RegsToPass[i].second, InFlag); 6558 InFlag = Chain.getValue(1); 6559 } 6560 6561 if (CFlags.IsTailCall && !IsSibCall) 6562 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6563 TailCallArguments); 6564 6565 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6566 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6567 } 6568 6569 SDValue PPCTargetLowering::LowerCall_Darwin( 6570 SDValue Chain, SDValue Callee, CallFlags CFlags, 6571 const SmallVectorImpl<ISD::OutputArg> &Outs, 6572 const SmallVectorImpl<SDValue> &OutVals, 6573 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6574 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6575 const CallBase *CB) const { 6576 unsigned NumOps = Outs.size(); 6577 6578 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6579 bool isPPC64 = PtrVT == MVT::i64; 6580 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6581 6582 MachineFunction &MF = DAG.getMachineFunction(); 6583 6584 // Mark this function as potentially containing a function that contains a 6585 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6586 // and restoring the callers stack pointer in this functions epilog. This is 6587 // done because by tail calling the called function might overwrite the value 6588 // in this function's (MF) stack pointer stack slot 0(SP). 6589 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6590 CFlags.CallConv == CallingConv::Fast) 6591 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6592 6593 // Count how many bytes are to be pushed on the stack, including the linkage 6594 // area, and parameter passing area. We start with 24/48 bytes, which is 6595 // prereserved space for [SP][CR][LR][3 x unused]. 6596 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6597 unsigned NumBytes = LinkageSize; 6598 6599 // Add up all the space actually used. 6600 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6601 // they all go in registers, but we must reserve stack space for them for 6602 // possible use by the caller. In varargs or 64-bit calls, parameters are 6603 // assigned stack space in order, with padding so Altivec parameters are 6604 // 16-byte aligned. 6605 unsigned nAltivecParamsAtEnd = 0; 6606 for (unsigned i = 0; i != NumOps; ++i) { 6607 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6608 EVT ArgVT = Outs[i].VT; 6609 // Varargs Altivec parameters are padded to a 16 byte boundary. 6610 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6611 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6612 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6613 if (!CFlags.IsVarArg && !isPPC64) { 6614 // Non-varargs Altivec parameters go after all the non-Altivec 6615 // parameters; handle those later so we know how much padding we need. 6616 nAltivecParamsAtEnd++; 6617 continue; 6618 } 6619 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6620 NumBytes = ((NumBytes+15)/16)*16; 6621 } 6622 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6623 } 6624 6625 // Allow for Altivec parameters at the end, if needed. 6626 if (nAltivecParamsAtEnd) { 6627 NumBytes = ((NumBytes+15)/16)*16; 6628 NumBytes += 16*nAltivecParamsAtEnd; 6629 } 6630 6631 // The prolog code of the callee may store up to 8 GPR argument registers to 6632 // the stack, allowing va_start to index over them in memory if its varargs. 6633 // Because we cannot tell if this is needed on the caller side, we have to 6634 // conservatively assume that it is needed. As such, make sure we have at 6635 // least enough stack space for the caller to store the 8 GPRs. 6636 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6637 6638 // Tail call needs the stack to be aligned. 6639 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6640 CFlags.CallConv == CallingConv::Fast) 6641 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6642 6643 // Calculate by how many bytes the stack has to be adjusted in case of tail 6644 // call optimization. 6645 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6646 6647 // To protect arguments on the stack from being clobbered in a tail call, 6648 // force all the loads to happen before doing any other lowering. 6649 if (CFlags.IsTailCall) 6650 Chain = DAG.getStackArgumentTokenFactor(Chain); 6651 6652 // Adjust the stack pointer for the new arguments... 6653 // These operations are automatically eliminated by the prolog/epilog pass 6654 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6655 SDValue CallSeqStart = Chain; 6656 6657 // Load the return address and frame pointer so it can be move somewhere else 6658 // later. 6659 SDValue LROp, FPOp; 6660 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6661 6662 // Set up a copy of the stack pointer for use loading and storing any 6663 // arguments that may not fit in the registers available for argument 6664 // passing. 6665 SDValue StackPtr; 6666 if (isPPC64) 6667 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6668 else 6669 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6670 6671 // Figure out which arguments are going to go in registers, and which in 6672 // memory. Also, if this is a vararg function, floating point operations 6673 // must be stored to our stack, and loaded into integer regs as well, if 6674 // any integer regs are available for argument passing. 6675 unsigned ArgOffset = LinkageSize; 6676 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6677 6678 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6679 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6680 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6681 }; 6682 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6683 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6684 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6685 }; 6686 static const MCPhysReg VR[] = { 6687 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6688 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6689 }; 6690 const unsigned NumGPRs = array_lengthof(GPR_32); 6691 const unsigned NumFPRs = 13; 6692 const unsigned NumVRs = array_lengthof(VR); 6693 6694 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6695 6696 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6697 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6698 6699 SmallVector<SDValue, 8> MemOpChains; 6700 for (unsigned i = 0; i != NumOps; ++i) { 6701 SDValue Arg = OutVals[i]; 6702 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6703 6704 // PtrOff will be used to store the current argument to the stack if a 6705 // register cannot be found for it. 6706 SDValue PtrOff; 6707 6708 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6709 6710 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6711 6712 // On PPC64, promote integers to 64-bit values. 6713 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6714 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6715 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6716 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6717 } 6718 6719 // FIXME memcpy is used way more than necessary. Correctness first. 6720 // Note: "by value" is code for passing a structure by value, not 6721 // basic types. 6722 if (Flags.isByVal()) { 6723 unsigned Size = Flags.getByValSize(); 6724 // Very small objects are passed right-justified. Everything else is 6725 // passed left-justified. 6726 if (Size==1 || Size==2) { 6727 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6728 if (GPR_idx != NumGPRs) { 6729 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6730 MachinePointerInfo(), VT); 6731 MemOpChains.push_back(Load.getValue(1)); 6732 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6733 6734 ArgOffset += PtrByteSize; 6735 } else { 6736 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6737 PtrOff.getValueType()); 6738 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6739 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6740 CallSeqStart, 6741 Flags, DAG, dl); 6742 ArgOffset += PtrByteSize; 6743 } 6744 continue; 6745 } 6746 // Copy entire object into memory. There are cases where gcc-generated 6747 // code assumes it is there, even if it could be put entirely into 6748 // registers. (This is not what the doc says.) 6749 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6750 CallSeqStart, 6751 Flags, DAG, dl); 6752 6753 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6754 // copy the pieces of the object that fit into registers from the 6755 // parameter save area. 6756 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6757 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6758 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6759 if (GPR_idx != NumGPRs) { 6760 SDValue Load = 6761 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6762 MemOpChains.push_back(Load.getValue(1)); 6763 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6764 ArgOffset += PtrByteSize; 6765 } else { 6766 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6767 break; 6768 } 6769 } 6770 continue; 6771 } 6772 6773 switch (Arg.getSimpleValueType().SimpleTy) { 6774 default: llvm_unreachable("Unexpected ValueType for argument!"); 6775 case MVT::i1: 6776 case MVT::i32: 6777 case MVT::i64: 6778 if (GPR_idx != NumGPRs) { 6779 if (Arg.getValueType() == MVT::i1) 6780 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6781 6782 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6783 } else { 6784 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6785 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6786 TailCallArguments, dl); 6787 } 6788 ArgOffset += PtrByteSize; 6789 break; 6790 case MVT::f32: 6791 case MVT::f64: 6792 if (FPR_idx != NumFPRs) { 6793 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6794 6795 if (CFlags.IsVarArg) { 6796 SDValue Store = 6797 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6798 MemOpChains.push_back(Store); 6799 6800 // Float varargs are always shadowed in available integer registers 6801 if (GPR_idx != NumGPRs) { 6802 SDValue Load = 6803 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6804 MemOpChains.push_back(Load.getValue(1)); 6805 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6806 } 6807 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6808 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6809 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6810 SDValue Load = 6811 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6812 MemOpChains.push_back(Load.getValue(1)); 6813 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6814 } 6815 } else { 6816 // If we have any FPRs remaining, we may also have GPRs remaining. 6817 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6818 // GPRs. 6819 if (GPR_idx != NumGPRs) 6820 ++GPR_idx; 6821 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6822 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6823 ++GPR_idx; 6824 } 6825 } else 6826 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6827 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6828 TailCallArguments, dl); 6829 if (isPPC64) 6830 ArgOffset += 8; 6831 else 6832 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6833 break; 6834 case MVT::v4f32: 6835 case MVT::v4i32: 6836 case MVT::v8i16: 6837 case MVT::v16i8: 6838 if (CFlags.IsVarArg) { 6839 // These go aligned on the stack, or in the corresponding R registers 6840 // when within range. The Darwin PPC ABI doc claims they also go in 6841 // V registers; in fact gcc does this only for arguments that are 6842 // prototyped, not for those that match the ... We do it for all 6843 // arguments, seems to work. 6844 while (ArgOffset % 16 !=0) { 6845 ArgOffset += PtrByteSize; 6846 if (GPR_idx != NumGPRs) 6847 GPR_idx++; 6848 } 6849 // We could elide this store in the case where the object fits 6850 // entirely in R registers. Maybe later. 6851 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6852 DAG.getConstant(ArgOffset, dl, PtrVT)); 6853 SDValue Store = 6854 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6855 MemOpChains.push_back(Store); 6856 if (VR_idx != NumVRs) { 6857 SDValue Load = 6858 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6859 MemOpChains.push_back(Load.getValue(1)); 6860 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6861 } 6862 ArgOffset += 16; 6863 for (unsigned i=0; i<16; i+=PtrByteSize) { 6864 if (GPR_idx == NumGPRs) 6865 break; 6866 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6867 DAG.getConstant(i, dl, PtrVT)); 6868 SDValue Load = 6869 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6870 MemOpChains.push_back(Load.getValue(1)); 6871 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6872 } 6873 break; 6874 } 6875 6876 // Non-varargs Altivec params generally go in registers, but have 6877 // stack space allocated at the end. 6878 if (VR_idx != NumVRs) { 6879 // Doesn't have GPR space allocated. 6880 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6881 } else if (nAltivecParamsAtEnd==0) { 6882 // We are emitting Altivec params in order. 6883 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6884 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6885 TailCallArguments, dl); 6886 ArgOffset += 16; 6887 } 6888 break; 6889 } 6890 } 6891 // If all Altivec parameters fit in registers, as they usually do, 6892 // they get stack space following the non-Altivec parameters. We 6893 // don't track this here because nobody below needs it. 6894 // If there are more Altivec parameters than fit in registers emit 6895 // the stores here. 6896 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6897 unsigned j = 0; 6898 // Offset is aligned; skip 1st 12 params which go in V registers. 6899 ArgOffset = ((ArgOffset+15)/16)*16; 6900 ArgOffset += 12*16; 6901 for (unsigned i = 0; i != NumOps; ++i) { 6902 SDValue Arg = OutVals[i]; 6903 EVT ArgType = Outs[i].VT; 6904 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6905 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6906 if (++j > NumVRs) { 6907 SDValue PtrOff; 6908 // We are emitting Altivec params in order. 6909 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6910 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6911 TailCallArguments, dl); 6912 ArgOffset += 16; 6913 } 6914 } 6915 } 6916 } 6917 6918 if (!MemOpChains.empty()) 6919 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6920 6921 // On Darwin, R12 must contain the address of an indirect callee. This does 6922 // not mean the MTCTR instruction must use R12; it's easier to model this as 6923 // an extra parameter, so do that. 6924 if (CFlags.IsIndirect) { 6925 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6926 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6927 PPC::R12), Callee)); 6928 } 6929 6930 // Build a sequence of copy-to-reg nodes chained together with token chain 6931 // and flag operands which copy the outgoing args into the appropriate regs. 6932 SDValue InFlag; 6933 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6934 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6935 RegsToPass[i].second, InFlag); 6936 InFlag = Chain.getValue(1); 6937 } 6938 6939 if (CFlags.IsTailCall) 6940 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6941 TailCallArguments); 6942 6943 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6944 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6945 } 6946 6947 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6948 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6949 CCState &State) { 6950 6951 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6952 State.getMachineFunction().getSubtarget()); 6953 const bool IsPPC64 = Subtarget.isPPC64(); 6954 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6955 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6956 6957 assert((!ValVT.isInteger() || 6958 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6959 "Integer argument exceeds register size: should have been legalized"); 6960 6961 if (ValVT == MVT::f128) 6962 report_fatal_error("f128 is unimplemented on AIX."); 6963 6964 if (ArgFlags.isNest()) 6965 report_fatal_error("Nest arguments are unimplemented."); 6966 6967 if (ValVT.isVector() || LocVT.isVector()) 6968 report_fatal_error("Vector arguments are unimplemented on AIX."); 6969 6970 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6971 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6972 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6973 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6974 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6975 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6976 6977 if (ArgFlags.isByVal()) { 6978 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 6979 report_fatal_error("Pass-by-value arguments with alignment greater than " 6980 "register width are not supported."); 6981 6982 const unsigned ByValSize = ArgFlags.getByValSize(); 6983 6984 // An empty aggregate parameter takes up no storage and no registers, 6985 // but needs a MemLoc for a stack slot for the formal arguments side. 6986 if (ByValSize == 0) { 6987 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6988 State.getNextStackOffset(), RegVT, 6989 LocInfo)); 6990 return false; 6991 } 6992 6993 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 6994 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 6995 for (const unsigned E = Offset + StackSize; Offset < E; 6996 Offset += PtrByteSize) { 6997 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6998 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6999 else { 7000 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7001 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7002 LocInfo)); 7003 break; 7004 } 7005 } 7006 return false; 7007 } 7008 7009 // Arguments always reserve parameter save area. 7010 switch (ValVT.SimpleTy) { 7011 default: 7012 report_fatal_error("Unhandled value type for argument."); 7013 case MVT::i64: 7014 // i64 arguments should have been split to i32 for PPC32. 7015 assert(IsPPC64 && "PPC32 should have split i64 values."); 7016 LLVM_FALLTHROUGH; 7017 case MVT::i1: 7018 case MVT::i32: { 7019 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7020 // AIX integer arguments are always passed in register width. 7021 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7022 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7023 : CCValAssign::LocInfo::ZExt; 7024 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7025 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7026 else 7027 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7028 7029 return false; 7030 } 7031 case MVT::f32: 7032 case MVT::f64: { 7033 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7034 const unsigned StoreSize = LocVT.getStoreSize(); 7035 // Floats are always 4-byte aligned in the PSA on AIX. 7036 // This includes f64 in 64-bit mode for ABI compatibility. 7037 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7038 unsigned FReg = State.AllocateReg(FPR); 7039 if (FReg) 7040 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7041 7042 // Reserve and initialize GPRs or initialize the PSA as required. 7043 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7044 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7045 assert(FReg && "An FPR should be available when a GPR is reserved."); 7046 if (State.isVarArg()) { 7047 // Successfully reserved GPRs are only initialized for vararg calls. 7048 // Custom handling is required for: 7049 // f64 in PPC32 needs to be split into 2 GPRs. 7050 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7051 State.addLoc( 7052 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7053 } 7054 } else { 7055 // If there are insufficient GPRs, the PSA needs to be initialized. 7056 // Initialization occurs even if an FPR was initialized for 7057 // compatibility with the AIX XL compiler. The full memory for the 7058 // argument will be initialized even if a prior word is saved in GPR. 7059 // A custom memLoc is used when the argument also passes in FPR so 7060 // that the callee handling can skip over it easily. 7061 State.addLoc( 7062 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7063 LocInfo) 7064 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7065 break; 7066 } 7067 } 7068 7069 return false; 7070 } 7071 } 7072 return true; 7073 } 7074 7075 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7076 bool IsPPC64) { 7077 assert((IsPPC64 || SVT != MVT::i64) && 7078 "i64 should have been split for 32-bit codegen."); 7079 7080 switch (SVT) { 7081 default: 7082 report_fatal_error("Unexpected value type for formal argument"); 7083 case MVT::i1: 7084 case MVT::i32: 7085 case MVT::i64: 7086 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7087 case MVT::f32: 7088 return &PPC::F4RCRegClass; 7089 case MVT::f64: 7090 return &PPC::F8RCRegClass; 7091 } 7092 } 7093 7094 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7095 SelectionDAG &DAG, SDValue ArgValue, 7096 MVT LocVT, const SDLoc &dl) { 7097 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7098 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7099 7100 if (Flags.isSExt()) 7101 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7102 DAG.getValueType(ValVT)); 7103 else if (Flags.isZExt()) 7104 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7105 DAG.getValueType(ValVT)); 7106 7107 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7108 } 7109 7110 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7111 const unsigned LASize = FL->getLinkageSize(); 7112 7113 if (PPC::GPRCRegClass.contains(Reg)) { 7114 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7115 "Reg must be a valid argument register!"); 7116 return LASize + 4 * (Reg - PPC::R3); 7117 } 7118 7119 if (PPC::G8RCRegClass.contains(Reg)) { 7120 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7121 "Reg must be a valid argument register!"); 7122 return LASize + 8 * (Reg - PPC::X3); 7123 } 7124 7125 llvm_unreachable("Only general purpose registers expected."); 7126 } 7127 7128 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7129 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7130 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7131 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7132 7133 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7134 CallConv == CallingConv::Fast) && 7135 "Unexpected calling convention!"); 7136 7137 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7138 report_fatal_error("Tail call support is unimplemented on AIX."); 7139 7140 if (useSoftFloat()) 7141 report_fatal_error("Soft float support is unimplemented on AIX."); 7142 7143 const PPCSubtarget &Subtarget = 7144 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7145 if (Subtarget.hasQPX()) 7146 report_fatal_error("QPX support is not supported on AIX."); 7147 7148 const bool IsPPC64 = Subtarget.isPPC64(); 7149 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7150 7151 // Assign locations to all of the incoming arguments. 7152 SmallVector<CCValAssign, 16> ArgLocs; 7153 MachineFunction &MF = DAG.getMachineFunction(); 7154 MachineFrameInfo &MFI = MF.getFrameInfo(); 7155 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7156 7157 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7158 // Reserve space for the linkage area on the stack. 7159 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7160 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7161 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7162 7163 SmallVector<SDValue, 8> MemOps; 7164 7165 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7166 CCValAssign &VA = ArgLocs[I++]; 7167 MVT LocVT = VA.getLocVT(); 7168 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7169 7170 // For compatibility with the AIX XL compiler, the float args in the 7171 // parameter save area are initialized even if the argument is available 7172 // in register. The caller is required to initialize both the register 7173 // and memory, however, the callee can choose to expect it in either. 7174 // The memloc is dismissed here because the argument is retrieved from 7175 // the register. 7176 if (VA.isMemLoc() && VA.needsCustom()) 7177 continue; 7178 7179 if (Flags.isByVal() && VA.isMemLoc()) { 7180 const unsigned Size = 7181 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7182 PtrByteSize); 7183 const int FI = MF.getFrameInfo().CreateFixedObject( 7184 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7185 /* IsAliased */ true); 7186 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7187 InVals.push_back(FIN); 7188 7189 continue; 7190 } 7191 7192 if (Flags.isByVal()) { 7193 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7194 7195 const MCPhysReg ArgReg = VA.getLocReg(); 7196 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7197 7198 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7199 report_fatal_error("Over aligned byvals not supported yet."); 7200 7201 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7202 const int FI = MF.getFrameInfo().CreateFixedObject( 7203 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7204 /* IsAliased */ true); 7205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7206 InVals.push_back(FIN); 7207 7208 // Add live ins for all the RegLocs for the same ByVal. 7209 const TargetRegisterClass *RegClass = 7210 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7211 7212 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7213 unsigned Offset) { 7214 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7215 // Since the callers side has left justified the aggregate in the 7216 // register, we can simply store the entire register into the stack 7217 // slot. 7218 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7219 // The store to the fixedstack object is needed becuase accessing a 7220 // field of the ByVal will use a gep and load. Ideally we will optimize 7221 // to extracting the value from the register directly, and elide the 7222 // stores when the arguments address is not taken, but that will need to 7223 // be future work. 7224 SDValue Store = 7225 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7226 DAG.getObjectPtrOffset(dl, FIN, Offset), 7227 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7228 7229 MemOps.push_back(Store); 7230 }; 7231 7232 unsigned Offset = 0; 7233 HandleRegLoc(VA.getLocReg(), Offset); 7234 Offset += PtrByteSize; 7235 for (; Offset != StackSize; Offset += PtrByteSize) { 7236 assert(I != End && 7237 "Expecting enough RegLocs to copy entire ByVal arg."); 7238 7239 if (!ArgLocs[I].isRegLoc()) 7240 report_fatal_error("Passing ByVals split between registers and stack " 7241 "not yet implemented."); 7242 7243 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7244 "Expecting more RegLocs for ByVal argument."); 7245 7246 const CCValAssign RL = ArgLocs[I++]; 7247 HandleRegLoc(RL.getLocReg(), Offset); 7248 } 7249 continue; 7250 } 7251 7252 EVT ValVT = VA.getValVT(); 7253 if (VA.isRegLoc() && !VA.needsCustom()) { 7254 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7255 unsigned VReg = 7256 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7257 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7258 if (ValVT.isScalarInteger() && 7259 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7260 ArgValue = 7261 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7262 } 7263 InVals.push_back(ArgValue); 7264 continue; 7265 } 7266 if (VA.isMemLoc()) { 7267 const unsigned LocSize = LocVT.getStoreSize(); 7268 const unsigned ValSize = ValVT.getStoreSize(); 7269 assert((ValSize <= LocSize) && 7270 "Object size is larger than size of MemLoc"); 7271 int CurArgOffset = VA.getLocMemOffset(); 7272 // Objects are right-justified because AIX is big-endian. 7273 if (LocSize > ValSize) 7274 CurArgOffset += LocSize - ValSize; 7275 // Potential tail calls could cause overwriting of argument stack slots. 7276 const bool IsImmutable = 7277 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7278 (CallConv == CallingConv::Fast)); 7279 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7280 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7281 SDValue ArgValue = 7282 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7283 InVals.push_back(ArgValue); 7284 continue; 7285 } 7286 } 7287 7288 // On AIX a minimum of 8 words is saved to the parameter save area. 7289 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7290 // Area that is at least reserved in the caller of this function. 7291 unsigned CallerReservedArea = 7292 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7293 7294 // Set the size that is at least reserved in caller of this function. Tail 7295 // call optimized function's reserved stack space needs to be aligned so 7296 // that taking the difference between two stack areas will result in an 7297 // aligned stack. 7298 CallerReservedArea = 7299 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7300 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7301 FuncInfo->setMinReservedArea(CallerReservedArea); 7302 7303 if (isVarArg) { 7304 FuncInfo->setVarArgsFrameIndex( 7305 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7306 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7307 7308 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7309 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7310 7311 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7312 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7313 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7314 7315 // The fixed integer arguments of a variadic function are stored to the 7316 // VarArgsFrameIndex on the stack so that they may be loaded by 7317 // dereferencing the result of va_next. 7318 for (unsigned GPRIndex = 7319 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7320 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7321 7322 const unsigned VReg = 7323 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7324 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7325 7326 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7327 SDValue Store = 7328 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7329 MemOps.push_back(Store); 7330 // Increment the address for the next argument to store. 7331 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7332 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7333 } 7334 } 7335 7336 if (!MemOps.empty()) 7337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7338 7339 return Chain; 7340 } 7341 7342 SDValue PPCTargetLowering::LowerCall_AIX( 7343 SDValue Chain, SDValue Callee, CallFlags CFlags, 7344 const SmallVectorImpl<ISD::OutputArg> &Outs, 7345 const SmallVectorImpl<SDValue> &OutVals, 7346 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7347 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7348 const CallBase *CB) const { 7349 7350 assert((CFlags.CallConv == CallingConv::C || 7351 CFlags.CallConv == CallingConv::Cold || 7352 CFlags.CallConv == CallingConv::Fast) && 7353 "Unexpected calling convention!"); 7354 7355 if (CFlags.IsPatchPoint) 7356 report_fatal_error("This call type is unimplemented on AIX."); 7357 7358 const PPCSubtarget& Subtarget = 7359 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7360 if (Subtarget.hasQPX()) 7361 report_fatal_error("QPX is not supported on AIX."); 7362 if (Subtarget.hasAltivec()) 7363 report_fatal_error("Altivec support is unimplemented on AIX."); 7364 7365 MachineFunction &MF = DAG.getMachineFunction(); 7366 SmallVector<CCValAssign, 16> ArgLocs; 7367 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7368 *DAG.getContext()); 7369 7370 // Reserve space for the linkage save area (LSA) on the stack. 7371 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7372 // [SP][CR][LR][2 x reserved][TOC]. 7373 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7374 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7375 const bool IsPPC64 = Subtarget.isPPC64(); 7376 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7377 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7378 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7379 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7380 7381 // The prolog code of the callee may store up to 8 GPR argument registers to 7382 // the stack, allowing va_start to index over them in memory if the callee 7383 // is variadic. 7384 // Because we cannot tell if this is needed on the caller side, we have to 7385 // conservatively assume that it is needed. As such, make sure we have at 7386 // least enough stack space for the caller to store the 8 GPRs. 7387 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7388 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7389 CCInfo.getNextStackOffset()); 7390 7391 // Adjust the stack pointer for the new arguments... 7392 // These operations are automatically eliminated by the prolog/epilog pass. 7393 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7394 SDValue CallSeqStart = Chain; 7395 7396 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7397 SmallVector<SDValue, 8> MemOpChains; 7398 7399 // Set up a copy of the stack pointer for loading and storing any 7400 // arguments that may not fit in the registers available for argument 7401 // passing. 7402 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7403 : DAG.getRegister(PPC::R1, MVT::i32); 7404 7405 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7406 const unsigned ValNo = ArgLocs[I].getValNo(); 7407 SDValue Arg = OutVals[ValNo]; 7408 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7409 7410 if (Flags.isByVal()) { 7411 const unsigned ByValSize = Flags.getByValSize(); 7412 7413 // Nothing to do for zero-sized ByVals on the caller side. 7414 if (!ByValSize) { 7415 ++I; 7416 continue; 7417 } 7418 7419 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7420 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7421 (LoadOffset != 0) 7422 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7423 : Arg, 7424 MachinePointerInfo(), VT); 7425 }; 7426 7427 unsigned LoadOffset = 0; 7428 7429 // Initialize registers, which are fully occupied by the by-val argument. 7430 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7431 SDValue Load = GetLoad(PtrVT, LoadOffset); 7432 MemOpChains.push_back(Load.getValue(1)); 7433 LoadOffset += PtrByteSize; 7434 const CCValAssign &ByValVA = ArgLocs[I++]; 7435 assert(ByValVA.getValNo() == ValNo && 7436 "Unexpected location for pass-by-value argument."); 7437 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7438 } 7439 7440 if (LoadOffset == ByValSize) 7441 continue; 7442 7443 // There must be one more loc to handle the remainder. 7444 assert(ArgLocs[I].getValNo() == ValNo && 7445 "Expected additional location for by-value argument."); 7446 7447 if (ArgLocs[I].isMemLoc()) { 7448 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7449 const CCValAssign &ByValVA = ArgLocs[I++]; 7450 ISD::ArgFlagsTy MemcpyFlags = Flags; 7451 // Only memcpy the bytes that don't pass in register. 7452 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7453 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7454 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7455 : Arg, 7456 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7457 CallSeqStart, MemcpyFlags, DAG, dl); 7458 continue; 7459 } 7460 7461 // Initialize the final register residue. 7462 // Any residue that occupies the final by-val arg register must be 7463 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7464 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7465 // 2 and 1 byte loads. 7466 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7467 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7468 "Unexpected register residue for by-value argument."); 7469 SDValue ResidueVal; 7470 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7471 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7472 const MVT VT = 7473 N == 1 ? MVT::i8 7474 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7475 SDValue Load = GetLoad(VT, LoadOffset); 7476 MemOpChains.push_back(Load.getValue(1)); 7477 LoadOffset += N; 7478 Bytes += N; 7479 7480 // By-val arguments are passed left-justfied in register. 7481 // Every load here needs to be shifted, otherwise a full register load 7482 // should have been used. 7483 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7484 "Unexpected load emitted during handling of pass-by-value " 7485 "argument."); 7486 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7487 EVT ShiftAmountTy = 7488 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7489 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7490 SDValue ShiftedLoad = 7491 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7492 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7493 ShiftedLoad) 7494 : ShiftedLoad; 7495 } 7496 7497 const CCValAssign &ByValVA = ArgLocs[I++]; 7498 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7499 continue; 7500 } 7501 7502 CCValAssign &VA = ArgLocs[I++]; 7503 const MVT LocVT = VA.getLocVT(); 7504 const MVT ValVT = VA.getValVT(); 7505 7506 switch (VA.getLocInfo()) { 7507 default: 7508 report_fatal_error("Unexpected argument extension type."); 7509 case CCValAssign::Full: 7510 break; 7511 case CCValAssign::ZExt: 7512 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7513 break; 7514 case CCValAssign::SExt: 7515 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7516 break; 7517 } 7518 7519 if (VA.isRegLoc() && !VA.needsCustom()) { 7520 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7521 continue; 7522 } 7523 7524 if (VA.isMemLoc()) { 7525 SDValue PtrOff = 7526 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7527 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7528 MemOpChains.push_back( 7529 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7530 7531 continue; 7532 } 7533 7534 // Custom handling is used for GPR initializations for vararg float 7535 // arguments. 7536 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7537 ValVT.isFloatingPoint() && LocVT.isInteger() && 7538 "Unexpected register handling for calling convention."); 7539 7540 SDValue ArgAsInt = 7541 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7542 7543 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7544 // f32 in 32-bit GPR 7545 // f64 in 64-bit GPR 7546 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7547 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7548 // f32 in 64-bit GPR. 7549 RegsToPass.push_back(std::make_pair( 7550 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7551 else { 7552 // f64 in two 32-bit GPRs 7553 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7554 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7555 "Unexpected custom register for argument!"); 7556 CCValAssign &GPR1 = VA; 7557 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7558 DAG.getConstant(32, dl, MVT::i8)); 7559 RegsToPass.push_back(std::make_pair( 7560 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7561 7562 if (I != E) { 7563 // If only 1 GPR was available, there will only be one custom GPR and 7564 // the argument will also pass in memory. 7565 CCValAssign &PeekArg = ArgLocs[I]; 7566 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7567 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7568 CCValAssign &GPR2 = ArgLocs[I++]; 7569 RegsToPass.push_back(std::make_pair( 7570 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7571 } 7572 } 7573 } 7574 } 7575 7576 if (!MemOpChains.empty()) 7577 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7578 7579 // For indirect calls, we need to save the TOC base to the stack for 7580 // restoration after the call. 7581 if (CFlags.IsIndirect) { 7582 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7583 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7584 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7585 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7586 const unsigned TOCSaveOffset = 7587 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7588 7589 setUsesTOCBasePtr(DAG); 7590 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7591 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7592 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7593 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7594 Chain = DAG.getStore( 7595 Val.getValue(1), dl, Val, AddPtr, 7596 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7597 } 7598 7599 // Build a sequence of copy-to-reg nodes chained together with token chain 7600 // and flag operands which copy the outgoing args into the appropriate regs. 7601 SDValue InFlag; 7602 for (auto Reg : RegsToPass) { 7603 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7604 InFlag = Chain.getValue(1); 7605 } 7606 7607 const int SPDiff = 0; 7608 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7609 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7610 } 7611 7612 bool 7613 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7614 MachineFunction &MF, bool isVarArg, 7615 const SmallVectorImpl<ISD::OutputArg> &Outs, 7616 LLVMContext &Context) const { 7617 SmallVector<CCValAssign, 16> RVLocs; 7618 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7619 return CCInfo.CheckReturn( 7620 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7621 ? RetCC_PPC_Cold 7622 : RetCC_PPC); 7623 } 7624 7625 SDValue 7626 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7627 bool isVarArg, 7628 const SmallVectorImpl<ISD::OutputArg> &Outs, 7629 const SmallVectorImpl<SDValue> &OutVals, 7630 const SDLoc &dl, SelectionDAG &DAG) const { 7631 SmallVector<CCValAssign, 16> RVLocs; 7632 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7633 *DAG.getContext()); 7634 CCInfo.AnalyzeReturn(Outs, 7635 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7636 ? RetCC_PPC_Cold 7637 : RetCC_PPC); 7638 7639 SDValue Flag; 7640 SmallVector<SDValue, 4> RetOps(1, Chain); 7641 7642 // Copy the result values into the output registers. 7643 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7644 CCValAssign &VA = RVLocs[i]; 7645 assert(VA.isRegLoc() && "Can only return in registers!"); 7646 7647 SDValue Arg = OutVals[RealResIdx]; 7648 7649 switch (VA.getLocInfo()) { 7650 default: llvm_unreachable("Unknown loc info!"); 7651 case CCValAssign::Full: break; 7652 case CCValAssign::AExt: 7653 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7654 break; 7655 case CCValAssign::ZExt: 7656 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7657 break; 7658 case CCValAssign::SExt: 7659 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7660 break; 7661 } 7662 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7663 bool isLittleEndian = Subtarget.isLittleEndian(); 7664 // Legalize ret f64 -> ret 2 x i32. 7665 SDValue SVal = 7666 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7667 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7668 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7669 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7670 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7671 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7672 Flag = Chain.getValue(1); 7673 VA = RVLocs[++i]; // skip ahead to next loc 7674 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7675 } else 7676 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7677 Flag = Chain.getValue(1); 7678 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7679 } 7680 7681 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7682 const MCPhysReg *I = 7683 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7684 if (I) { 7685 for (; *I; ++I) { 7686 7687 if (PPC::G8RCRegClass.contains(*I)) 7688 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7689 else if (PPC::F8RCRegClass.contains(*I)) 7690 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7691 else if (PPC::CRRCRegClass.contains(*I)) 7692 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7693 else if (PPC::VRRCRegClass.contains(*I)) 7694 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7695 else 7696 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7697 } 7698 } 7699 7700 RetOps[0] = Chain; // Update chain. 7701 7702 // Add the flag if we have it. 7703 if (Flag.getNode()) 7704 RetOps.push_back(Flag); 7705 7706 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7707 } 7708 7709 SDValue 7710 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7711 SelectionDAG &DAG) const { 7712 SDLoc dl(Op); 7713 7714 // Get the correct type for integers. 7715 EVT IntVT = Op.getValueType(); 7716 7717 // Get the inputs. 7718 SDValue Chain = Op.getOperand(0); 7719 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7720 // Build a DYNAREAOFFSET node. 7721 SDValue Ops[2] = {Chain, FPSIdx}; 7722 SDVTList VTs = DAG.getVTList(IntVT); 7723 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7724 } 7725 7726 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7727 SelectionDAG &DAG) const { 7728 // When we pop the dynamic allocation we need to restore the SP link. 7729 SDLoc dl(Op); 7730 7731 // Get the correct type for pointers. 7732 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7733 7734 // Construct the stack pointer operand. 7735 bool isPPC64 = Subtarget.isPPC64(); 7736 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7737 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7738 7739 // Get the operands for the STACKRESTORE. 7740 SDValue Chain = Op.getOperand(0); 7741 SDValue SaveSP = Op.getOperand(1); 7742 7743 // Load the old link SP. 7744 SDValue LoadLinkSP = 7745 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7746 7747 // Restore the stack pointer. 7748 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7749 7750 // Store the old link SP. 7751 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7752 } 7753 7754 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7755 MachineFunction &MF = DAG.getMachineFunction(); 7756 bool isPPC64 = Subtarget.isPPC64(); 7757 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7758 7759 // Get current frame pointer save index. The users of this index will be 7760 // primarily DYNALLOC instructions. 7761 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7762 int RASI = FI->getReturnAddrSaveIndex(); 7763 7764 // If the frame pointer save index hasn't been defined yet. 7765 if (!RASI) { 7766 // Find out what the fix offset of the frame pointer save area. 7767 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7768 // Allocate the frame index for frame pointer save area. 7769 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7770 // Save the result. 7771 FI->setReturnAddrSaveIndex(RASI); 7772 } 7773 return DAG.getFrameIndex(RASI, PtrVT); 7774 } 7775 7776 SDValue 7777 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7778 MachineFunction &MF = DAG.getMachineFunction(); 7779 bool isPPC64 = Subtarget.isPPC64(); 7780 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7781 7782 // Get current frame pointer save index. The users of this index will be 7783 // primarily DYNALLOC instructions. 7784 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7785 int FPSI = FI->getFramePointerSaveIndex(); 7786 7787 // If the frame pointer save index hasn't been defined yet. 7788 if (!FPSI) { 7789 // Find out what the fix offset of the frame pointer save area. 7790 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7791 // Allocate the frame index for frame pointer save area. 7792 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7793 // Save the result. 7794 FI->setFramePointerSaveIndex(FPSI); 7795 } 7796 return DAG.getFrameIndex(FPSI, PtrVT); 7797 } 7798 7799 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7800 SelectionDAG &DAG) const { 7801 // Get the inputs. 7802 SDValue Chain = Op.getOperand(0); 7803 SDValue Size = Op.getOperand(1); 7804 SDLoc dl(Op); 7805 7806 // Get the correct type for pointers. 7807 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7808 // Negate the size. 7809 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7810 DAG.getConstant(0, dl, PtrVT), Size); 7811 // Construct a node for the frame pointer save index. 7812 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7813 // Build a DYNALLOC node. 7814 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7815 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7816 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7817 } 7818 7819 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7820 SelectionDAG &DAG) const { 7821 MachineFunction &MF = DAG.getMachineFunction(); 7822 7823 bool isPPC64 = Subtarget.isPPC64(); 7824 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7825 7826 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7827 return DAG.getFrameIndex(FI, PtrVT); 7828 } 7829 7830 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7831 SelectionDAG &DAG) const { 7832 SDLoc DL(Op); 7833 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7834 DAG.getVTList(MVT::i32, MVT::Other), 7835 Op.getOperand(0), Op.getOperand(1)); 7836 } 7837 7838 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7839 SelectionDAG &DAG) const { 7840 SDLoc DL(Op); 7841 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7842 Op.getOperand(0), Op.getOperand(1)); 7843 } 7844 7845 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7846 if (Op.getValueType().isVector()) 7847 return LowerVectorLoad(Op, DAG); 7848 7849 assert(Op.getValueType() == MVT::i1 && 7850 "Custom lowering only for i1 loads"); 7851 7852 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7853 7854 SDLoc dl(Op); 7855 LoadSDNode *LD = cast<LoadSDNode>(Op); 7856 7857 SDValue Chain = LD->getChain(); 7858 SDValue BasePtr = LD->getBasePtr(); 7859 MachineMemOperand *MMO = LD->getMemOperand(); 7860 7861 SDValue NewLD = 7862 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7863 BasePtr, MVT::i8, MMO); 7864 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7865 7866 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7867 return DAG.getMergeValues(Ops, dl); 7868 } 7869 7870 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7871 if (Op.getOperand(1).getValueType().isVector()) 7872 return LowerVectorStore(Op, DAG); 7873 7874 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7875 "Custom lowering only for i1 stores"); 7876 7877 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7878 7879 SDLoc dl(Op); 7880 StoreSDNode *ST = cast<StoreSDNode>(Op); 7881 7882 SDValue Chain = ST->getChain(); 7883 SDValue BasePtr = ST->getBasePtr(); 7884 SDValue Value = ST->getValue(); 7885 MachineMemOperand *MMO = ST->getMemOperand(); 7886 7887 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7888 Value); 7889 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7890 } 7891 7892 // FIXME: Remove this once the ANDI glue bug is fixed: 7893 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7894 assert(Op.getValueType() == MVT::i1 && 7895 "Custom lowering only for i1 results"); 7896 7897 SDLoc DL(Op); 7898 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7899 } 7900 7901 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7902 SelectionDAG &DAG) const { 7903 7904 // Implements a vector truncate that fits in a vector register as a shuffle. 7905 // We want to legalize vector truncates down to where the source fits in 7906 // a vector register (and target is therefore smaller than vector register 7907 // size). At that point legalization will try to custom lower the sub-legal 7908 // result and get here - where we can contain the truncate as a single target 7909 // operation. 7910 7911 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7912 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7913 // 7914 // We will implement it for big-endian ordering as this (where x denotes 7915 // undefined): 7916 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7917 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7918 // 7919 // The same operation in little-endian ordering will be: 7920 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7921 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7922 7923 assert(Op.getValueType().isVector() && "Vector type expected."); 7924 7925 SDLoc DL(Op); 7926 SDValue N1 = Op.getOperand(0); 7927 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7928 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7929 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7930 7931 EVT TrgVT = Op.getValueType(); 7932 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7933 EVT EltVT = TrgVT.getVectorElementType(); 7934 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7935 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7936 7937 // First list the elements we want to keep. 7938 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7939 SmallVector<int, 16> ShuffV; 7940 if (Subtarget.isLittleEndian()) 7941 for (unsigned i = 0; i < TrgNumElts; ++i) 7942 ShuffV.push_back(i * SizeMult); 7943 else 7944 for (unsigned i = 1; i <= TrgNumElts; ++i) 7945 ShuffV.push_back(i * SizeMult - 1); 7946 7947 // Populate the remaining elements with undefs. 7948 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7949 // ShuffV.push_back(i + WideNumElts); 7950 ShuffV.push_back(WideNumElts + 1); 7951 7952 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7953 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7954 } 7955 7956 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7957 /// possible. 7958 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7959 // Not FP? Not a fsel. 7960 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7961 !Op.getOperand(2).getValueType().isFloatingPoint()) 7962 return Op; 7963 7964 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7965 7966 EVT ResVT = Op.getValueType(); 7967 EVT CmpVT = Op.getOperand(0).getValueType(); 7968 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7969 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7970 SDLoc dl(Op); 7971 7972 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7973 // presence of infinities. 7974 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7975 switch (CC) { 7976 default: 7977 break; 7978 case ISD::SETOGT: 7979 case ISD::SETGT: 7980 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7981 case ISD::SETOLT: 7982 case ISD::SETLT: 7983 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7984 } 7985 } 7986 7987 // We might be able to do better than this under some circumstances, but in 7988 // general, fsel-based lowering of select is a finite-math-only optimization. 7989 // For more information, see section F.3 of the 2.06 ISA specification. 7990 // With ISA 3.0 7991 if (!DAG.getTarget().Options.NoInfsFPMath || 7992 !DAG.getTarget().Options.NoNaNsFPMath) 7993 return Op; 7994 7995 // TODO: Propagate flags from the select rather than global settings. 7996 SDNodeFlags Flags; 7997 Flags.setNoInfs(true); 7998 Flags.setNoNaNs(true); 7999 8000 // If the RHS of the comparison is a 0.0, we don't need to do the 8001 // subtraction at all. 8002 SDValue Sel1; 8003 if (isFloatingPointZero(RHS)) 8004 switch (CC) { 8005 default: break; // SETUO etc aren't handled by fsel. 8006 case ISD::SETNE: 8007 std::swap(TV, FV); 8008 LLVM_FALLTHROUGH; 8009 case ISD::SETEQ: 8010 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8011 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8012 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8013 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8014 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8015 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8016 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8017 case ISD::SETULT: 8018 case ISD::SETLT: 8019 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8020 LLVM_FALLTHROUGH; 8021 case ISD::SETOGE: 8022 case ISD::SETGE: 8023 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8024 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8025 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8026 case ISD::SETUGT: 8027 case ISD::SETGT: 8028 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8029 LLVM_FALLTHROUGH; 8030 case ISD::SETOLE: 8031 case ISD::SETLE: 8032 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8033 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8035 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8036 } 8037 8038 SDValue Cmp; 8039 switch (CC) { 8040 default: break; // SETUO etc aren't handled by fsel. 8041 case ISD::SETNE: 8042 std::swap(TV, FV); 8043 LLVM_FALLTHROUGH; 8044 case ISD::SETEQ: 8045 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8046 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8047 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8048 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8049 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8050 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8051 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8052 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8053 case ISD::SETULT: 8054 case ISD::SETLT: 8055 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8056 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8057 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8058 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8059 case ISD::SETOGE: 8060 case ISD::SETGE: 8061 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8062 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8063 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8064 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8065 case ISD::SETUGT: 8066 case ISD::SETGT: 8067 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8068 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8069 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8070 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8071 case ISD::SETOLE: 8072 case ISD::SETLE: 8073 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8074 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8075 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8076 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8077 } 8078 return Op; 8079 } 8080 8081 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8082 SelectionDAG &DAG, 8083 const SDLoc &dl) const { 8084 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8085 SDValue Src = Op.getOperand(0); 8086 if (Src.getValueType() == MVT::f32) 8087 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8088 8089 SDValue Tmp; 8090 switch (Op.getSimpleValueType().SimpleTy) { 8091 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8092 case MVT::i32: 8093 Tmp = DAG.getNode( 8094 Op.getOpcode() == ISD::FP_TO_SINT 8095 ? PPCISD::FCTIWZ 8096 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8097 dl, MVT::f64, Src); 8098 break; 8099 case MVT::i64: 8100 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8101 "i64 FP_TO_UINT is supported only with FPCVT"); 8102 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8103 PPCISD::FCTIDUZ, 8104 dl, MVT::f64, Src); 8105 break; 8106 } 8107 8108 // Convert the FP value to an int value through memory. 8109 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8110 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8111 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8112 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8113 MachinePointerInfo MPI = 8114 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8115 8116 // Emit a store to the stack slot. 8117 SDValue Chain; 8118 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8119 if (i32Stack) { 8120 MachineFunction &MF = DAG.getMachineFunction(); 8121 Alignment = Align(4); 8122 MachineMemOperand *MMO = 8123 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8124 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8125 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8126 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8127 } else 8128 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8129 8130 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8131 // add in a bias on big endian. 8132 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8133 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8134 DAG.getConstant(4, dl, FIPtr.getValueType())); 8135 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8136 } 8137 8138 RLI.Chain = Chain; 8139 RLI.Ptr = FIPtr; 8140 RLI.MPI = MPI; 8141 RLI.Alignment = Alignment; 8142 } 8143 8144 /// Custom lowers floating point to integer conversions to use 8145 /// the direct move instructions available in ISA 2.07 to avoid the 8146 /// need for load/store combinations. 8147 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8148 SelectionDAG &DAG, 8149 const SDLoc &dl) const { 8150 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8151 SDValue Src = Op.getOperand(0); 8152 8153 if (Src.getValueType() == MVT::f32) 8154 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8155 8156 SDValue Tmp; 8157 switch (Op.getSimpleValueType().SimpleTy) { 8158 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8159 case MVT::i32: 8160 Tmp = DAG.getNode( 8161 Op.getOpcode() == ISD::FP_TO_SINT 8162 ? PPCISD::FCTIWZ 8163 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8164 dl, MVT::f64, Src); 8165 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8166 break; 8167 case MVT::i64: 8168 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8169 "i64 FP_TO_UINT is supported only with FPCVT"); 8170 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8171 PPCISD::FCTIDUZ, 8172 dl, MVT::f64, Src); 8173 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8174 break; 8175 } 8176 return Tmp; 8177 } 8178 8179 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8180 const SDLoc &dl) const { 8181 8182 // FP to INT conversions are legal for f128. 8183 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8184 return Op; 8185 8186 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8187 // PPC (the libcall is not available). 8188 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8189 if (Op.getValueType() == MVT::i32) { 8190 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8191 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8192 MVT::f64, Op.getOperand(0), 8193 DAG.getIntPtrConstant(0, dl)); 8194 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8195 MVT::f64, Op.getOperand(0), 8196 DAG.getIntPtrConstant(1, dl)); 8197 8198 // Add the two halves of the long double in round-to-zero mode. 8199 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8200 8201 // Now use a smaller FP_TO_SINT. 8202 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8203 } 8204 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8205 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8206 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8207 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8208 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8209 // FIXME: generated code sucks. 8210 // TODO: Are there fast-math-flags to propagate to this FSUB? 8211 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8212 Op.getOperand(0), Tmp); 8213 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8214 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8215 DAG.getConstant(0x80000000, dl, MVT::i32)); 8216 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8217 Op.getOperand(0)); 8218 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8219 ISD::SETGE); 8220 } 8221 } 8222 8223 return SDValue(); 8224 } 8225 8226 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8227 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8228 8229 ReuseLoadInfo RLI; 8230 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8231 8232 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8233 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8234 } 8235 8236 // We're trying to insert a regular store, S, and then a load, L. If the 8237 // incoming value, O, is a load, we might just be able to have our load use the 8238 // address used by O. However, we don't know if anything else will store to 8239 // that address before we can load from it. To prevent this situation, we need 8240 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8241 // the same chain operand as O, we create a token factor from the chain results 8242 // of O and L, and we replace all uses of O's chain result with that token 8243 // factor (see spliceIntoChain below for this last part). 8244 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8245 ReuseLoadInfo &RLI, 8246 SelectionDAG &DAG, 8247 ISD::LoadExtType ET) const { 8248 SDLoc dl(Op); 8249 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8250 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8251 if (ET == ISD::NON_EXTLOAD && 8252 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8253 isOperationLegalOrCustom(Op.getOpcode(), 8254 Op.getOperand(0).getValueType())) { 8255 8256 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8257 return true; 8258 } 8259 8260 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8261 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8262 LD->isNonTemporal()) 8263 return false; 8264 if (LD->getMemoryVT() != MemVT) 8265 return false; 8266 8267 RLI.Ptr = LD->getBasePtr(); 8268 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8269 assert(LD->getAddressingMode() == ISD::PRE_INC && 8270 "Non-pre-inc AM on PPC?"); 8271 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8272 LD->getOffset()); 8273 } 8274 8275 RLI.Chain = LD->getChain(); 8276 RLI.MPI = LD->getPointerInfo(); 8277 RLI.IsDereferenceable = LD->isDereferenceable(); 8278 RLI.IsInvariant = LD->isInvariant(); 8279 RLI.Alignment = LD->getAlign(); 8280 RLI.AAInfo = LD->getAAInfo(); 8281 RLI.Ranges = LD->getRanges(); 8282 8283 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8284 return true; 8285 } 8286 8287 // Given the head of the old chain, ResChain, insert a token factor containing 8288 // it and NewResChain, and make users of ResChain now be users of that token 8289 // factor. 8290 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8291 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8292 SDValue NewResChain, 8293 SelectionDAG &DAG) const { 8294 if (!ResChain) 8295 return; 8296 8297 SDLoc dl(NewResChain); 8298 8299 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8300 NewResChain, DAG.getUNDEF(MVT::Other)); 8301 assert(TF.getNode() != NewResChain.getNode() && 8302 "A new TF really is required here"); 8303 8304 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8305 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8306 } 8307 8308 /// Analyze profitability of direct move 8309 /// prefer float load to int load plus direct move 8310 /// when there is no integer use of int load 8311 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8312 SDNode *Origin = Op.getOperand(0).getNode(); 8313 if (Origin->getOpcode() != ISD::LOAD) 8314 return true; 8315 8316 // If there is no LXSIBZX/LXSIHZX, like Power8, 8317 // prefer direct move if the memory size is 1 or 2 bytes. 8318 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8319 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8320 return true; 8321 8322 for (SDNode::use_iterator UI = Origin->use_begin(), 8323 UE = Origin->use_end(); 8324 UI != UE; ++UI) { 8325 8326 // Only look at the users of the loaded value. 8327 if (UI.getUse().get().getResNo() != 0) 8328 continue; 8329 8330 if (UI->getOpcode() != ISD::SINT_TO_FP && 8331 UI->getOpcode() != ISD::UINT_TO_FP) 8332 return true; 8333 } 8334 8335 return false; 8336 } 8337 8338 /// Custom lowers integer to floating point conversions to use 8339 /// the direct move instructions available in ISA 2.07 to avoid the 8340 /// need for load/store combinations. 8341 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8342 SelectionDAG &DAG, 8343 const SDLoc &dl) const { 8344 assert((Op.getValueType() == MVT::f32 || 8345 Op.getValueType() == MVT::f64) && 8346 "Invalid floating point type as target of conversion"); 8347 assert(Subtarget.hasFPCVT() && 8348 "Int to FP conversions with direct moves require FPCVT"); 8349 SDValue FP; 8350 SDValue Src = Op.getOperand(0); 8351 bool SinglePrec = Op.getValueType() == MVT::f32; 8352 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8353 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8354 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8355 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8356 8357 if (WordInt) { 8358 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8359 dl, MVT::f64, Src); 8360 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8361 } 8362 else { 8363 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8364 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8365 } 8366 8367 return FP; 8368 } 8369 8370 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8371 8372 EVT VecVT = Vec.getValueType(); 8373 assert(VecVT.isVector() && "Expected a vector type."); 8374 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8375 8376 EVT EltVT = VecVT.getVectorElementType(); 8377 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8378 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8379 8380 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8381 SmallVector<SDValue, 16> Ops(NumConcat); 8382 Ops[0] = Vec; 8383 SDValue UndefVec = DAG.getUNDEF(VecVT); 8384 for (unsigned i = 1; i < NumConcat; ++i) 8385 Ops[i] = UndefVec; 8386 8387 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8388 } 8389 8390 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8391 const SDLoc &dl) const { 8392 8393 unsigned Opc = Op.getOpcode(); 8394 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8395 "Unexpected conversion type"); 8396 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8397 "Supports conversions to v2f64/v4f32 only."); 8398 8399 bool SignedConv = Opc == ISD::SINT_TO_FP; 8400 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8401 8402 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8403 EVT WideVT = Wide.getValueType(); 8404 unsigned WideNumElts = WideVT.getVectorNumElements(); 8405 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8406 8407 SmallVector<int, 16> ShuffV; 8408 for (unsigned i = 0; i < WideNumElts; ++i) 8409 ShuffV.push_back(i + WideNumElts); 8410 8411 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8412 int SaveElts = FourEltRes ? 4 : 2; 8413 if (Subtarget.isLittleEndian()) 8414 for (int i = 0; i < SaveElts; i++) 8415 ShuffV[i * Stride] = i; 8416 else 8417 for (int i = 1; i <= SaveElts; i++) 8418 ShuffV[i * Stride - 1] = i - 1; 8419 8420 SDValue ShuffleSrc2 = 8421 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8422 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8423 8424 SDValue Extend; 8425 if (SignedConv) { 8426 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8427 EVT ExtVT = Op.getOperand(0).getValueType(); 8428 if (Subtarget.hasP9Altivec()) 8429 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8430 IntermediateVT.getVectorNumElements()); 8431 8432 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8433 DAG.getValueType(ExtVT)); 8434 } else 8435 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8436 8437 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8438 } 8439 8440 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8441 SelectionDAG &DAG) const { 8442 SDLoc dl(Op); 8443 8444 EVT InVT = Op.getOperand(0).getValueType(); 8445 EVT OutVT = Op.getValueType(); 8446 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8447 isOperationCustom(Op.getOpcode(), InVT)) 8448 return LowerINT_TO_FPVector(Op, DAG, dl); 8449 8450 // Conversions to f128 are legal. 8451 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8452 return Op; 8453 8454 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8455 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8456 return SDValue(); 8457 8458 SDValue Value = Op.getOperand(0); 8459 // The values are now known to be -1 (false) or 1 (true). To convert this 8460 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8461 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8462 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8463 8464 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8465 8466 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8467 8468 if (Op.getValueType() != MVT::v4f64) 8469 Value = DAG.getNode(ISD::FP_ROUND, dl, 8470 Op.getValueType(), Value, 8471 DAG.getIntPtrConstant(1, dl)); 8472 return Value; 8473 } 8474 8475 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8476 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8477 return SDValue(); 8478 8479 if (Op.getOperand(0).getValueType() == MVT::i1) 8480 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8481 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8482 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8483 8484 // If we have direct moves, we can do all the conversion, skip the store/load 8485 // however, without FPCVT we can't do most conversions. 8486 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8487 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8488 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8489 8490 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8491 "UINT_TO_FP is supported only with FPCVT"); 8492 8493 // If we have FCFIDS, then use it when converting to single-precision. 8494 // Otherwise, convert to double-precision and then round. 8495 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8496 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8497 : PPCISD::FCFIDS) 8498 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8499 : PPCISD::FCFID); 8500 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8501 ? MVT::f32 8502 : MVT::f64; 8503 8504 if (Op.getOperand(0).getValueType() == MVT::i64) { 8505 SDValue SINT = Op.getOperand(0); 8506 // When converting to single-precision, we actually need to convert 8507 // to double-precision first and then round to single-precision. 8508 // To avoid double-rounding effects during that operation, we have 8509 // to prepare the input operand. Bits that might be truncated when 8510 // converting to double-precision are replaced by a bit that won't 8511 // be lost at this stage, but is below the single-precision rounding 8512 // position. 8513 // 8514 // However, if -enable-unsafe-fp-math is in effect, accept double 8515 // rounding to avoid the extra overhead. 8516 if (Op.getValueType() == MVT::f32 && 8517 !Subtarget.hasFPCVT() && 8518 !DAG.getTarget().Options.UnsafeFPMath) { 8519 8520 // Twiddle input to make sure the low 11 bits are zero. (If this 8521 // is the case, we are guaranteed the value will fit into the 53 bit 8522 // mantissa of an IEEE double-precision value without rounding.) 8523 // If any of those low 11 bits were not zero originally, make sure 8524 // bit 12 (value 2048) is set instead, so that the final rounding 8525 // to single-precision gets the correct result. 8526 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8527 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8528 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8529 Round, DAG.getConstant(2047, dl, MVT::i64)); 8530 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8531 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8532 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8533 8534 // However, we cannot use that value unconditionally: if the magnitude 8535 // of the input value is small, the bit-twiddling we did above might 8536 // end up visibly changing the output. Fortunately, in that case, we 8537 // don't need to twiddle bits since the original input will convert 8538 // exactly to double-precision floating-point already. Therefore, 8539 // construct a conditional to use the original value if the top 11 8540 // bits are all sign-bit copies, and use the rounded value computed 8541 // above otherwise. 8542 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8543 SINT, DAG.getConstant(53, dl, MVT::i32)); 8544 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8545 Cond, DAG.getConstant(1, dl, MVT::i64)); 8546 Cond = DAG.getSetCC( 8547 dl, 8548 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8549 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8550 8551 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8552 } 8553 8554 ReuseLoadInfo RLI; 8555 SDValue Bits; 8556 8557 MachineFunction &MF = DAG.getMachineFunction(); 8558 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8559 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8560 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8561 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8562 } else if (Subtarget.hasLFIWAX() && 8563 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8564 MachineMemOperand *MMO = 8565 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8566 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8567 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8568 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8569 DAG.getVTList(MVT::f64, MVT::Other), 8570 Ops, MVT::i32, MMO); 8571 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8572 } else if (Subtarget.hasFPCVT() && 8573 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8574 MachineMemOperand *MMO = 8575 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8576 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8577 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8578 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8579 DAG.getVTList(MVT::f64, MVT::Other), 8580 Ops, MVT::i32, MMO); 8581 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8582 } else if (((Subtarget.hasLFIWAX() && 8583 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8584 (Subtarget.hasFPCVT() && 8585 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8586 SINT.getOperand(0).getValueType() == MVT::i32) { 8587 MachineFrameInfo &MFI = MF.getFrameInfo(); 8588 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8589 8590 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8591 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8592 8593 SDValue Store = 8594 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8595 MachinePointerInfo::getFixedStack( 8596 DAG.getMachineFunction(), FrameIdx)); 8597 8598 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8599 "Expected an i32 store"); 8600 8601 RLI.Ptr = FIdx; 8602 RLI.Chain = Store; 8603 RLI.MPI = 8604 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8605 RLI.Alignment = Align(4); 8606 8607 MachineMemOperand *MMO = 8608 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8609 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8610 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8611 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8612 PPCISD::LFIWZX : PPCISD::LFIWAX, 8613 dl, DAG.getVTList(MVT::f64, MVT::Other), 8614 Ops, MVT::i32, MMO); 8615 } else 8616 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8617 8618 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8619 8620 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8621 FP = DAG.getNode(ISD::FP_ROUND, dl, 8622 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8623 return FP; 8624 } 8625 8626 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8627 "Unhandled INT_TO_FP type in custom expander!"); 8628 // Since we only generate this in 64-bit mode, we can take advantage of 8629 // 64-bit registers. In particular, sign extend the input value into the 8630 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8631 // then lfd it and fcfid it. 8632 MachineFunction &MF = DAG.getMachineFunction(); 8633 MachineFrameInfo &MFI = MF.getFrameInfo(); 8634 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8635 8636 SDValue Ld; 8637 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8638 ReuseLoadInfo RLI; 8639 bool ReusingLoad; 8640 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8641 DAG))) { 8642 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8643 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8644 8645 SDValue Store = 8646 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8647 MachinePointerInfo::getFixedStack( 8648 DAG.getMachineFunction(), FrameIdx)); 8649 8650 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8651 "Expected an i32 store"); 8652 8653 RLI.Ptr = FIdx; 8654 RLI.Chain = Store; 8655 RLI.MPI = 8656 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8657 RLI.Alignment = Align(4); 8658 } 8659 8660 MachineMemOperand *MMO = 8661 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8662 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8663 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8664 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8665 PPCISD::LFIWZX : PPCISD::LFIWAX, 8666 dl, DAG.getVTList(MVT::f64, MVT::Other), 8667 Ops, MVT::i32, MMO); 8668 if (ReusingLoad) 8669 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8670 } else { 8671 assert(Subtarget.isPPC64() && 8672 "i32->FP without LFIWAX supported only on PPC64"); 8673 8674 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8675 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8676 8677 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8678 Op.getOperand(0)); 8679 8680 // STD the extended value into the stack slot. 8681 SDValue Store = DAG.getStore( 8682 DAG.getEntryNode(), dl, Ext64, FIdx, 8683 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8684 8685 // Load the value as a double. 8686 Ld = DAG.getLoad( 8687 MVT::f64, dl, Store, FIdx, 8688 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8689 } 8690 8691 // FCFID it and return it. 8692 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8693 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8694 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8695 DAG.getIntPtrConstant(0, dl)); 8696 return FP; 8697 } 8698 8699 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8700 SelectionDAG &DAG) const { 8701 SDLoc dl(Op); 8702 /* 8703 The rounding mode is in bits 30:31 of FPSR, and has the following 8704 settings: 8705 00 Round to nearest 8706 01 Round to 0 8707 10 Round to +inf 8708 11 Round to -inf 8709 8710 FLT_ROUNDS, on the other hand, expects the following: 8711 -1 Undefined 8712 0 Round to 0 8713 1 Round to nearest 8714 2 Round to +inf 8715 3 Round to -inf 8716 8717 To perform the conversion, we do: 8718 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8719 */ 8720 8721 MachineFunction &MF = DAG.getMachineFunction(); 8722 EVT VT = Op.getValueType(); 8723 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8724 8725 // Save FP Control Word to register 8726 SDValue Chain = Op.getOperand(0); 8727 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8728 Chain = MFFS.getValue(1); 8729 8730 // Save FP register to stack slot 8731 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8732 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8733 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8734 8735 // Load FP Control Word from low 32 bits of stack slot. 8736 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8737 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8738 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8739 Chain = CWD.getValue(1); 8740 8741 // Transform as necessary 8742 SDValue CWD1 = 8743 DAG.getNode(ISD::AND, dl, MVT::i32, 8744 CWD, DAG.getConstant(3, dl, MVT::i32)); 8745 SDValue CWD2 = 8746 DAG.getNode(ISD::SRL, dl, MVT::i32, 8747 DAG.getNode(ISD::AND, dl, MVT::i32, 8748 DAG.getNode(ISD::XOR, dl, MVT::i32, 8749 CWD, DAG.getConstant(3, dl, MVT::i32)), 8750 DAG.getConstant(3, dl, MVT::i32)), 8751 DAG.getConstant(1, dl, MVT::i32)); 8752 8753 SDValue RetVal = 8754 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8755 8756 RetVal = 8757 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8758 dl, VT, RetVal); 8759 8760 return DAG.getMergeValues({RetVal, Chain}, dl); 8761 } 8762 8763 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8764 EVT VT = Op.getValueType(); 8765 unsigned BitWidth = VT.getSizeInBits(); 8766 SDLoc dl(Op); 8767 assert(Op.getNumOperands() == 3 && 8768 VT == Op.getOperand(1).getValueType() && 8769 "Unexpected SHL!"); 8770 8771 // Expand into a bunch of logical ops. Note that these ops 8772 // depend on the PPC behavior for oversized shift amounts. 8773 SDValue Lo = Op.getOperand(0); 8774 SDValue Hi = Op.getOperand(1); 8775 SDValue Amt = Op.getOperand(2); 8776 EVT AmtVT = Amt.getValueType(); 8777 8778 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8779 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8780 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8781 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8782 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8783 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8784 DAG.getConstant(-BitWidth, dl, AmtVT)); 8785 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8786 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8787 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8788 SDValue OutOps[] = { OutLo, OutHi }; 8789 return DAG.getMergeValues(OutOps, dl); 8790 } 8791 8792 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8793 EVT VT = Op.getValueType(); 8794 SDLoc dl(Op); 8795 unsigned BitWidth = VT.getSizeInBits(); 8796 assert(Op.getNumOperands() == 3 && 8797 VT == Op.getOperand(1).getValueType() && 8798 "Unexpected SRL!"); 8799 8800 // Expand into a bunch of logical ops. Note that these ops 8801 // depend on the PPC behavior for oversized shift amounts. 8802 SDValue Lo = Op.getOperand(0); 8803 SDValue Hi = Op.getOperand(1); 8804 SDValue Amt = Op.getOperand(2); 8805 EVT AmtVT = Amt.getValueType(); 8806 8807 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8808 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8809 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8810 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8811 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8812 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8813 DAG.getConstant(-BitWidth, dl, AmtVT)); 8814 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8815 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8816 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8817 SDValue OutOps[] = { OutLo, OutHi }; 8818 return DAG.getMergeValues(OutOps, dl); 8819 } 8820 8821 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8822 SDLoc dl(Op); 8823 EVT VT = Op.getValueType(); 8824 unsigned BitWidth = VT.getSizeInBits(); 8825 assert(Op.getNumOperands() == 3 && 8826 VT == Op.getOperand(1).getValueType() && 8827 "Unexpected SRA!"); 8828 8829 // Expand into a bunch of logical ops, followed by a select_cc. 8830 SDValue Lo = Op.getOperand(0); 8831 SDValue Hi = Op.getOperand(1); 8832 SDValue Amt = Op.getOperand(2); 8833 EVT AmtVT = Amt.getValueType(); 8834 8835 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8836 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8837 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8838 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8839 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8840 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8841 DAG.getConstant(-BitWidth, dl, AmtVT)); 8842 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8843 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8844 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8845 Tmp4, Tmp6, ISD::SETLE); 8846 SDValue OutOps[] = { OutLo, OutHi }; 8847 return DAG.getMergeValues(OutOps, dl); 8848 } 8849 8850 //===----------------------------------------------------------------------===// 8851 // Vector related lowering. 8852 // 8853 8854 /// BuildSplatI - Build a canonical splati of Val with an element size of 8855 /// SplatSize. Cast the result to VT. 8856 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8857 SelectionDAG &DAG, const SDLoc &dl) { 8858 static const MVT VTys[] = { // canonical VT to use for each size. 8859 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8860 }; 8861 8862 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8863 8864 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8865 if (Val == -1) 8866 SplatSize = 1; 8867 8868 EVT CanonicalVT = VTys[SplatSize-1]; 8869 8870 // Build a canonical splat for this value. 8871 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8872 } 8873 8874 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8875 /// specified intrinsic ID. 8876 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8877 const SDLoc &dl, EVT DestVT = MVT::Other) { 8878 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8879 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8880 DAG.getConstant(IID, dl, MVT::i32), Op); 8881 } 8882 8883 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8884 /// specified intrinsic ID. 8885 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8886 SelectionDAG &DAG, const SDLoc &dl, 8887 EVT DestVT = MVT::Other) { 8888 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8889 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8890 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8891 } 8892 8893 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8894 /// specified intrinsic ID. 8895 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8896 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8897 EVT DestVT = MVT::Other) { 8898 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8899 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8900 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8901 } 8902 8903 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8904 /// amount. The result has the specified value type. 8905 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8906 SelectionDAG &DAG, const SDLoc &dl) { 8907 // Force LHS/RHS to be the right type. 8908 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8909 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8910 8911 int Ops[16]; 8912 for (unsigned i = 0; i != 16; ++i) 8913 Ops[i] = i + Amt; 8914 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8915 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8916 } 8917 8918 /// Do we have an efficient pattern in a .td file for this node? 8919 /// 8920 /// \param V - pointer to the BuildVectorSDNode being matched 8921 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8922 /// 8923 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8924 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8925 /// the opposite is true (expansion is beneficial) are: 8926 /// - The node builds a vector out of integers that are not 32 or 64-bits 8927 /// - The node builds a vector out of constants 8928 /// - The node is a "load-and-splat" 8929 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8930 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8931 bool HasDirectMove, 8932 bool HasP8Vector) { 8933 EVT VecVT = V->getValueType(0); 8934 bool RightType = VecVT == MVT::v2f64 || 8935 (HasP8Vector && VecVT == MVT::v4f32) || 8936 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8937 if (!RightType) 8938 return false; 8939 8940 bool IsSplat = true; 8941 bool IsLoad = false; 8942 SDValue Op0 = V->getOperand(0); 8943 8944 // This function is called in a block that confirms the node is not a constant 8945 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8946 // different constants. 8947 if (V->isConstant()) 8948 return false; 8949 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8950 if (V->getOperand(i).isUndef()) 8951 return false; 8952 // We want to expand nodes that represent load-and-splat even if the 8953 // loaded value is a floating point truncation or conversion to int. 8954 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8955 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8956 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8957 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8958 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8959 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8960 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8961 IsLoad = true; 8962 // If the operands are different or the input is not a load and has more 8963 // uses than just this BV node, then it isn't a splat. 8964 if (V->getOperand(i) != Op0 || 8965 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8966 IsSplat = false; 8967 } 8968 return !(IsSplat && IsLoad); 8969 } 8970 8971 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8972 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8973 8974 SDLoc dl(Op); 8975 SDValue Op0 = Op->getOperand(0); 8976 8977 if (!EnableQuadPrecision || 8978 (Op.getValueType() != MVT::f128 ) || 8979 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8980 (Op0.getOperand(0).getValueType() != MVT::i64) || 8981 (Op0.getOperand(1).getValueType() != MVT::i64)) 8982 return SDValue(); 8983 8984 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8985 Op0.getOperand(1)); 8986 } 8987 8988 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8989 const SDValue *InputLoad = &Op; 8990 if (InputLoad->getOpcode() == ISD::BITCAST) 8991 InputLoad = &InputLoad->getOperand(0); 8992 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8993 InputLoad = &InputLoad->getOperand(0); 8994 if (InputLoad->getOpcode() != ISD::LOAD) 8995 return nullptr; 8996 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8997 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8998 } 8999 9000 // If this is a case we can't handle, return null and let the default 9001 // expansion code take care of it. If we CAN select this case, and if it 9002 // selects to a single instruction, return Op. Otherwise, if we can codegen 9003 // this case more efficiently than a constant pool load, lower it to the 9004 // sequence of ops that should be used. 9005 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9006 SelectionDAG &DAG) const { 9007 SDLoc dl(Op); 9008 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9009 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9010 9011 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9012 // We first build an i32 vector, load it into a QPX register, 9013 // then convert it to a floating-point vector and compare it 9014 // to a zero vector to get the boolean result. 9015 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9016 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9017 MachinePointerInfo PtrInfo = 9018 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9019 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9020 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9021 9022 assert(BVN->getNumOperands() == 4 && 9023 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9024 9025 bool IsConst = true; 9026 for (unsigned i = 0; i < 4; ++i) { 9027 if (BVN->getOperand(i).isUndef()) continue; 9028 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9029 IsConst = false; 9030 break; 9031 } 9032 } 9033 9034 if (IsConst) { 9035 Constant *One = 9036 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9037 Constant *NegOne = 9038 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9039 9040 Constant *CV[4]; 9041 for (unsigned i = 0; i < 4; ++i) { 9042 if (BVN->getOperand(i).isUndef()) 9043 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9044 else if (isNullConstant(BVN->getOperand(i))) 9045 CV[i] = NegOne; 9046 else 9047 CV[i] = One; 9048 } 9049 9050 Constant *CP = ConstantVector::get(CV); 9051 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 9052 16 /* alignment */); 9053 9054 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9055 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9056 return DAG.getMemIntrinsicNode( 9057 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9058 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9059 } 9060 9061 SmallVector<SDValue, 4> Stores; 9062 for (unsigned i = 0; i < 4; ++i) { 9063 if (BVN->getOperand(i).isUndef()) continue; 9064 9065 unsigned Offset = 4*i; 9066 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9067 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9068 9069 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9070 if (StoreSize > 4) { 9071 Stores.push_back( 9072 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9073 PtrInfo.getWithOffset(Offset), MVT::i32)); 9074 } else { 9075 SDValue StoreValue = BVN->getOperand(i); 9076 if (StoreSize < 4) 9077 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9078 9079 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9080 PtrInfo.getWithOffset(Offset))); 9081 } 9082 } 9083 9084 SDValue StoreChain; 9085 if (!Stores.empty()) 9086 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9087 else 9088 StoreChain = DAG.getEntryNode(); 9089 9090 // Now load from v4i32 into the QPX register; this will extend it to 9091 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9092 // is typed as v4f64 because the QPX register integer states are not 9093 // explicitly represented. 9094 9095 SDValue Ops[] = {StoreChain, 9096 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9097 FIdx}; 9098 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9099 9100 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9101 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9102 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9103 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9104 LoadedVect); 9105 9106 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9107 9108 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9109 } 9110 9111 // All other QPX vectors are handled by generic code. 9112 if (Subtarget.hasQPX()) 9113 return SDValue(); 9114 9115 // Check if this is a splat of a constant value. 9116 APInt APSplatBits, APSplatUndef; 9117 unsigned SplatBitSize; 9118 bool HasAnyUndefs; 9119 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9120 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9121 SplatBitSize > 32) { 9122 9123 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9124 // Handle load-and-splat patterns as we have instructions that will do this 9125 // in one go. 9126 if (InputLoad && DAG.isSplatValue(Op, true)) { 9127 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9128 9129 // We have handling for 4 and 8 byte elements. 9130 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9131 9132 // Checking for a single use of this load, we have to check for vector 9133 // width (128 bits) / ElementSize uses (since each operand of the 9134 // BUILD_VECTOR is a separate use of the value. 9135 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9136 ((Subtarget.hasVSX() && ElementSize == 64) || 9137 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9138 SDValue Ops[] = { 9139 LD->getChain(), // Chain 9140 LD->getBasePtr(), // Ptr 9141 DAG.getValueType(Op.getValueType()) // VT 9142 }; 9143 return 9144 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9145 DAG.getVTList(Op.getValueType(), MVT::Other), 9146 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9147 } 9148 } 9149 9150 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9151 // lowered to VSX instructions under certain conditions. 9152 // Without VSX, there is no pattern more efficient than expanding the node. 9153 if (Subtarget.hasVSX() && 9154 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9155 Subtarget.hasP8Vector())) 9156 return Op; 9157 return SDValue(); 9158 } 9159 9160 unsigned SplatBits = APSplatBits.getZExtValue(); 9161 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9162 unsigned SplatSize = SplatBitSize / 8; 9163 9164 // First, handle single instruction cases. 9165 9166 // All zeros? 9167 if (SplatBits == 0) { 9168 // Canonicalize all zero vectors to be v4i32. 9169 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9170 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9171 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9172 } 9173 return Op; 9174 } 9175 9176 // We have XXSPLTIB for constant splats one byte wide 9177 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9178 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9179 if (Subtarget.hasP9Vector() && SplatSize == 1) 9180 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9181 9182 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9183 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9184 (32-SplatBitSize)); 9185 if (SextVal >= -16 && SextVal <= 15) 9186 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9187 9188 // Two instruction sequences. 9189 9190 // If this value is in the range [-32,30] and is even, use: 9191 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9192 // If this value is in the range [17,31] and is odd, use: 9193 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9194 // If this value is in the range [-31,-17] and is odd, use: 9195 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9196 // Note the last two are three-instruction sequences. 9197 if (SextVal >= -32 && SextVal <= 31) { 9198 // To avoid having these optimizations undone by constant folding, 9199 // we convert to a pseudo that will be expanded later into one of 9200 // the above forms. 9201 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9202 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9203 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9204 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9205 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9206 if (VT == Op.getValueType()) 9207 return RetVal; 9208 else 9209 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9210 } 9211 9212 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9213 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9214 // for fneg/fabs. 9215 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9216 // Make -1 and vspltisw -1: 9217 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9218 9219 // Make the VSLW intrinsic, computing 0x8000_0000. 9220 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9221 OnesV, DAG, dl); 9222 9223 // xor by OnesV to invert it. 9224 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9225 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9226 } 9227 9228 // Check to see if this is a wide variety of vsplti*, binop self cases. 9229 static const signed char SplatCsts[] = { 9230 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9231 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9232 }; 9233 9234 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9235 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9236 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9237 int i = SplatCsts[idx]; 9238 9239 // Figure out what shift amount will be used by altivec if shifted by i in 9240 // this splat size. 9241 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9242 9243 // vsplti + shl self. 9244 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9245 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9246 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9247 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9248 Intrinsic::ppc_altivec_vslw 9249 }; 9250 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9251 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9252 } 9253 9254 // vsplti + srl self. 9255 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9256 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9257 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9258 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9259 Intrinsic::ppc_altivec_vsrw 9260 }; 9261 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9262 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9263 } 9264 9265 // vsplti + sra self. 9266 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9267 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9268 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9269 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9270 Intrinsic::ppc_altivec_vsraw 9271 }; 9272 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9273 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9274 } 9275 9276 // vsplti + rol self. 9277 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9278 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9279 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9280 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9281 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9282 Intrinsic::ppc_altivec_vrlw 9283 }; 9284 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9285 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9286 } 9287 9288 // t = vsplti c, result = vsldoi t, t, 1 9289 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9290 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9291 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9292 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9293 } 9294 // t = vsplti c, result = vsldoi t, t, 2 9295 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9296 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9297 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9298 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9299 } 9300 // t = vsplti c, result = vsldoi t, t, 3 9301 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9302 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9303 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9304 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9305 } 9306 } 9307 9308 return SDValue(); 9309 } 9310 9311 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9312 /// the specified operations to build the shuffle. 9313 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9314 SDValue RHS, SelectionDAG &DAG, 9315 const SDLoc &dl) { 9316 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9317 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9318 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9319 9320 enum { 9321 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9322 OP_VMRGHW, 9323 OP_VMRGLW, 9324 OP_VSPLTISW0, 9325 OP_VSPLTISW1, 9326 OP_VSPLTISW2, 9327 OP_VSPLTISW3, 9328 OP_VSLDOI4, 9329 OP_VSLDOI8, 9330 OP_VSLDOI12 9331 }; 9332 9333 if (OpNum == OP_COPY) { 9334 if (LHSID == (1*9+2)*9+3) return LHS; 9335 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9336 return RHS; 9337 } 9338 9339 SDValue OpLHS, OpRHS; 9340 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9341 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9342 9343 int ShufIdxs[16]; 9344 switch (OpNum) { 9345 default: llvm_unreachable("Unknown i32 permute!"); 9346 case OP_VMRGHW: 9347 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9348 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9349 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9350 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9351 break; 9352 case OP_VMRGLW: 9353 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9354 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9355 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9356 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9357 break; 9358 case OP_VSPLTISW0: 9359 for (unsigned i = 0; i != 16; ++i) 9360 ShufIdxs[i] = (i&3)+0; 9361 break; 9362 case OP_VSPLTISW1: 9363 for (unsigned i = 0; i != 16; ++i) 9364 ShufIdxs[i] = (i&3)+4; 9365 break; 9366 case OP_VSPLTISW2: 9367 for (unsigned i = 0; i != 16; ++i) 9368 ShufIdxs[i] = (i&3)+8; 9369 break; 9370 case OP_VSPLTISW3: 9371 for (unsigned i = 0; i != 16; ++i) 9372 ShufIdxs[i] = (i&3)+12; 9373 break; 9374 case OP_VSLDOI4: 9375 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9376 case OP_VSLDOI8: 9377 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9378 case OP_VSLDOI12: 9379 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9380 } 9381 EVT VT = OpLHS.getValueType(); 9382 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9383 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9384 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9385 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9386 } 9387 9388 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9389 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9390 /// SDValue. 9391 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9392 SelectionDAG &DAG) const { 9393 const unsigned BytesInVector = 16; 9394 bool IsLE = Subtarget.isLittleEndian(); 9395 SDLoc dl(N); 9396 SDValue V1 = N->getOperand(0); 9397 SDValue V2 = N->getOperand(1); 9398 unsigned ShiftElts = 0, InsertAtByte = 0; 9399 bool Swap = false; 9400 9401 // Shifts required to get the byte we want at element 7. 9402 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9403 0, 15, 14, 13, 12, 11, 10, 9}; 9404 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9405 1, 2, 3, 4, 5, 6, 7, 8}; 9406 9407 ArrayRef<int> Mask = N->getMask(); 9408 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9409 9410 // For each mask element, find out if we're just inserting something 9411 // from V2 into V1 or vice versa. 9412 // Possible permutations inserting an element from V2 into V1: 9413 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9414 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9415 // ... 9416 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9417 // Inserting from V1 into V2 will be similar, except mask range will be 9418 // [16,31]. 9419 9420 bool FoundCandidate = false; 9421 // If both vector operands for the shuffle are the same vector, the mask 9422 // will contain only elements from the first one and the second one will be 9423 // undef. 9424 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9425 // Go through the mask of half-words to find an element that's being moved 9426 // from one vector to the other. 9427 for (unsigned i = 0; i < BytesInVector; ++i) { 9428 unsigned CurrentElement = Mask[i]; 9429 // If 2nd operand is undefined, we should only look for element 7 in the 9430 // Mask. 9431 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9432 continue; 9433 9434 bool OtherElementsInOrder = true; 9435 // Examine the other elements in the Mask to see if they're in original 9436 // order. 9437 for (unsigned j = 0; j < BytesInVector; ++j) { 9438 if (j == i) 9439 continue; 9440 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9441 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9442 // in which we always assume we're always picking from the 1st operand. 9443 int MaskOffset = 9444 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9445 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9446 OtherElementsInOrder = false; 9447 break; 9448 } 9449 } 9450 // If other elements are in original order, we record the number of shifts 9451 // we need to get the element we want into element 7. Also record which byte 9452 // in the vector we should insert into. 9453 if (OtherElementsInOrder) { 9454 // If 2nd operand is undefined, we assume no shifts and no swapping. 9455 if (V2.isUndef()) { 9456 ShiftElts = 0; 9457 Swap = false; 9458 } else { 9459 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9460 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9461 : BigEndianShifts[CurrentElement & 0xF]; 9462 Swap = CurrentElement < BytesInVector; 9463 } 9464 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9465 FoundCandidate = true; 9466 break; 9467 } 9468 } 9469 9470 if (!FoundCandidate) 9471 return SDValue(); 9472 9473 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9474 // optionally with VECSHL if shift is required. 9475 if (Swap) 9476 std::swap(V1, V2); 9477 if (V2.isUndef()) 9478 V2 = V1; 9479 if (ShiftElts) { 9480 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9481 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9482 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9483 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9484 } 9485 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9486 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9487 } 9488 9489 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9490 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9491 /// SDValue. 9492 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9493 SelectionDAG &DAG) const { 9494 const unsigned NumHalfWords = 8; 9495 const unsigned BytesInVector = NumHalfWords * 2; 9496 // Check that the shuffle is on half-words. 9497 if (!isNByteElemShuffleMask(N, 2, 1)) 9498 return SDValue(); 9499 9500 bool IsLE = Subtarget.isLittleEndian(); 9501 SDLoc dl(N); 9502 SDValue V1 = N->getOperand(0); 9503 SDValue V2 = N->getOperand(1); 9504 unsigned ShiftElts = 0, InsertAtByte = 0; 9505 bool Swap = false; 9506 9507 // Shifts required to get the half-word we want at element 3. 9508 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9509 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9510 9511 uint32_t Mask = 0; 9512 uint32_t OriginalOrderLow = 0x1234567; 9513 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9514 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9515 // 32-bit space, only need 4-bit nibbles per element. 9516 for (unsigned i = 0; i < NumHalfWords; ++i) { 9517 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9518 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9519 } 9520 9521 // For each mask element, find out if we're just inserting something 9522 // from V2 into V1 or vice versa. Possible permutations inserting an element 9523 // from V2 into V1: 9524 // X, 1, 2, 3, 4, 5, 6, 7 9525 // 0, X, 2, 3, 4, 5, 6, 7 9526 // 0, 1, X, 3, 4, 5, 6, 7 9527 // 0, 1, 2, X, 4, 5, 6, 7 9528 // 0, 1, 2, 3, X, 5, 6, 7 9529 // 0, 1, 2, 3, 4, X, 6, 7 9530 // 0, 1, 2, 3, 4, 5, X, 7 9531 // 0, 1, 2, 3, 4, 5, 6, X 9532 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9533 9534 bool FoundCandidate = false; 9535 // Go through the mask of half-words to find an element that's being moved 9536 // from one vector to the other. 9537 for (unsigned i = 0; i < NumHalfWords; ++i) { 9538 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9539 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9540 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9541 uint32_t TargetOrder = 0x0; 9542 9543 // If both vector operands for the shuffle are the same vector, the mask 9544 // will contain only elements from the first one and the second one will be 9545 // undef. 9546 if (V2.isUndef()) { 9547 ShiftElts = 0; 9548 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9549 TargetOrder = OriginalOrderLow; 9550 Swap = false; 9551 // Skip if not the correct element or mask of other elements don't equal 9552 // to our expected order. 9553 if (MaskOneElt == VINSERTHSrcElem && 9554 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9555 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9556 FoundCandidate = true; 9557 break; 9558 } 9559 } else { // If both operands are defined. 9560 // Target order is [8,15] if the current mask is between [0,7]. 9561 TargetOrder = 9562 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9563 // Skip if mask of other elements don't equal our expected order. 9564 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9565 // We only need the last 3 bits for the number of shifts. 9566 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9567 : BigEndianShifts[MaskOneElt & 0x7]; 9568 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9569 Swap = MaskOneElt < NumHalfWords; 9570 FoundCandidate = true; 9571 break; 9572 } 9573 } 9574 } 9575 9576 if (!FoundCandidate) 9577 return SDValue(); 9578 9579 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9580 // optionally with VECSHL if shift is required. 9581 if (Swap) 9582 std::swap(V1, V2); 9583 if (V2.isUndef()) 9584 V2 = V1; 9585 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9586 if (ShiftElts) { 9587 // Double ShiftElts because we're left shifting on v16i8 type. 9588 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9589 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9590 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9591 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9592 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9593 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9594 } 9595 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9596 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9597 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9598 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9599 } 9600 9601 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9602 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9603 /// return the code it can be lowered into. Worst case, it can always be 9604 /// lowered into a vperm. 9605 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9606 SelectionDAG &DAG) const { 9607 SDLoc dl(Op); 9608 SDValue V1 = Op.getOperand(0); 9609 SDValue V2 = Op.getOperand(1); 9610 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9611 EVT VT = Op.getValueType(); 9612 bool isLittleEndian = Subtarget.isLittleEndian(); 9613 9614 unsigned ShiftElts, InsertAtByte; 9615 bool Swap = false; 9616 9617 // If this is a load-and-splat, we can do that with a single instruction 9618 // in some cases. However if the load has multiple uses, we don't want to 9619 // combine it because that will just produce multiple loads. 9620 const SDValue *InputLoad = getNormalLoadInput(V1); 9621 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9622 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9623 InputLoad->hasOneUse()) { 9624 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9625 int SplatIdx = 9626 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9627 9628 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9629 // For 4-byte load-and-splat, we need Power9. 9630 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9631 uint64_t Offset = 0; 9632 if (IsFourByte) 9633 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9634 else 9635 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9636 SDValue BasePtr = LD->getBasePtr(); 9637 if (Offset != 0) 9638 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9639 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9640 SDValue Ops[] = { 9641 LD->getChain(), // Chain 9642 BasePtr, // BasePtr 9643 DAG.getValueType(Op.getValueType()) // VT 9644 }; 9645 SDVTList VTL = 9646 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9647 SDValue LdSplt = 9648 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9649 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9650 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9651 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9652 return LdSplt; 9653 } 9654 } 9655 if (Subtarget.hasP9Vector() && 9656 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9657 isLittleEndian)) { 9658 if (Swap) 9659 std::swap(V1, V2); 9660 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9661 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9662 if (ShiftElts) { 9663 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9664 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9665 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9666 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9667 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9668 } 9669 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9670 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9671 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9672 } 9673 9674 if (Subtarget.hasP9Altivec()) { 9675 SDValue NewISDNode; 9676 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9677 return NewISDNode; 9678 9679 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9680 return NewISDNode; 9681 } 9682 9683 if (Subtarget.hasVSX() && 9684 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9685 if (Swap) 9686 std::swap(V1, V2); 9687 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9688 SDValue Conv2 = 9689 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9690 9691 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9692 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9693 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9694 } 9695 9696 if (Subtarget.hasVSX() && 9697 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9698 if (Swap) 9699 std::swap(V1, V2); 9700 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9701 SDValue Conv2 = 9702 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9703 9704 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9705 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9706 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9707 } 9708 9709 if (Subtarget.hasP9Vector()) { 9710 if (PPC::isXXBRHShuffleMask(SVOp)) { 9711 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9712 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9713 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9714 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9715 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9716 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9717 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9718 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9719 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9720 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9721 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9722 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9723 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9724 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9725 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9726 } 9727 } 9728 9729 if (Subtarget.hasVSX()) { 9730 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9731 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9732 9733 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9734 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9735 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9736 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9737 } 9738 9739 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9740 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9741 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9742 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9743 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9744 } 9745 } 9746 9747 if (Subtarget.hasQPX()) { 9748 if (VT.getVectorNumElements() != 4) 9749 return SDValue(); 9750 9751 if (V2.isUndef()) V2 = V1; 9752 9753 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9754 if (AlignIdx != -1) { 9755 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9756 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9757 } else if (SVOp->isSplat()) { 9758 int SplatIdx = SVOp->getSplatIndex(); 9759 if (SplatIdx >= 4) { 9760 std::swap(V1, V2); 9761 SplatIdx -= 4; 9762 } 9763 9764 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9765 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9766 } 9767 9768 // Lower this into a qvgpci/qvfperm pair. 9769 9770 // Compute the qvgpci literal 9771 unsigned idx = 0; 9772 for (unsigned i = 0; i < 4; ++i) { 9773 int m = SVOp->getMaskElt(i); 9774 unsigned mm = m >= 0 ? (unsigned) m : i; 9775 idx |= mm << (3-i)*3; 9776 } 9777 9778 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9779 DAG.getConstant(idx, dl, MVT::i32)); 9780 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9781 } 9782 9783 // Cases that are handled by instructions that take permute immediates 9784 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9785 // selected by the instruction selector. 9786 if (V2.isUndef()) { 9787 if (PPC::isSplatShuffleMask(SVOp, 1) || 9788 PPC::isSplatShuffleMask(SVOp, 2) || 9789 PPC::isSplatShuffleMask(SVOp, 4) || 9790 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9791 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9792 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9793 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9794 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9795 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9796 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9797 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9798 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9799 (Subtarget.hasP8Altivec() && ( 9800 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9801 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9802 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9803 return Op; 9804 } 9805 } 9806 9807 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9808 // and produce a fixed permutation. If any of these match, do not lower to 9809 // VPERM. 9810 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9811 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9812 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9813 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9814 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9815 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9816 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9817 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9818 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9819 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9820 (Subtarget.hasP8Altivec() && ( 9821 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9822 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9823 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9824 return Op; 9825 9826 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9827 // perfect shuffle table to emit an optimal matching sequence. 9828 ArrayRef<int> PermMask = SVOp->getMask(); 9829 9830 unsigned PFIndexes[4]; 9831 bool isFourElementShuffle = true; 9832 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9833 unsigned EltNo = 8; // Start out undef. 9834 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9835 if (PermMask[i*4+j] < 0) 9836 continue; // Undef, ignore it. 9837 9838 unsigned ByteSource = PermMask[i*4+j]; 9839 if ((ByteSource & 3) != j) { 9840 isFourElementShuffle = false; 9841 break; 9842 } 9843 9844 if (EltNo == 8) { 9845 EltNo = ByteSource/4; 9846 } else if (EltNo != ByteSource/4) { 9847 isFourElementShuffle = false; 9848 break; 9849 } 9850 } 9851 PFIndexes[i] = EltNo; 9852 } 9853 9854 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9855 // perfect shuffle vector to determine if it is cost effective to do this as 9856 // discrete instructions, or whether we should use a vperm. 9857 // For now, we skip this for little endian until such time as we have a 9858 // little-endian perfect shuffle table. 9859 if (isFourElementShuffle && !isLittleEndian) { 9860 // Compute the index in the perfect shuffle table. 9861 unsigned PFTableIndex = 9862 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9863 9864 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9865 unsigned Cost = (PFEntry >> 30); 9866 9867 // Determining when to avoid vperm is tricky. Many things affect the cost 9868 // of vperm, particularly how many times the perm mask needs to be computed. 9869 // For example, if the perm mask can be hoisted out of a loop or is already 9870 // used (perhaps because there are multiple permutes with the same shuffle 9871 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9872 // the loop requires an extra register. 9873 // 9874 // As a compromise, we only emit discrete instructions if the shuffle can be 9875 // generated in 3 or fewer operations. When we have loop information 9876 // available, if this block is within a loop, we should avoid using vperm 9877 // for 3-operation perms and use a constant pool load instead. 9878 if (Cost < 3) 9879 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9880 } 9881 9882 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9883 // vector that will get spilled to the constant pool. 9884 if (V2.isUndef()) V2 = V1; 9885 9886 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9887 // that it is in input element units, not in bytes. Convert now. 9888 9889 // For little endian, the order of the input vectors is reversed, and 9890 // the permutation mask is complemented with respect to 31. This is 9891 // necessary to produce proper semantics with the big-endian-biased vperm 9892 // instruction. 9893 EVT EltVT = V1.getValueType().getVectorElementType(); 9894 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9895 9896 SmallVector<SDValue, 16> ResultMask; 9897 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9898 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9899 9900 for (unsigned j = 0; j != BytesPerElement; ++j) 9901 if (isLittleEndian) 9902 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9903 dl, MVT::i32)); 9904 else 9905 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9906 MVT::i32)); 9907 } 9908 9909 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9910 if (isLittleEndian) 9911 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9912 V2, V1, VPermMask); 9913 else 9914 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9915 V1, V2, VPermMask); 9916 } 9917 9918 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9919 /// vector comparison. If it is, return true and fill in Opc/isDot with 9920 /// information about the intrinsic. 9921 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9922 bool &isDot, const PPCSubtarget &Subtarget) { 9923 unsigned IntrinsicID = 9924 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9925 CompareOpc = -1; 9926 isDot = false; 9927 switch (IntrinsicID) { 9928 default: 9929 return false; 9930 // Comparison predicates. 9931 case Intrinsic::ppc_altivec_vcmpbfp_p: 9932 CompareOpc = 966; 9933 isDot = true; 9934 break; 9935 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9936 CompareOpc = 198; 9937 isDot = true; 9938 break; 9939 case Intrinsic::ppc_altivec_vcmpequb_p: 9940 CompareOpc = 6; 9941 isDot = true; 9942 break; 9943 case Intrinsic::ppc_altivec_vcmpequh_p: 9944 CompareOpc = 70; 9945 isDot = true; 9946 break; 9947 case Intrinsic::ppc_altivec_vcmpequw_p: 9948 CompareOpc = 134; 9949 isDot = true; 9950 break; 9951 case Intrinsic::ppc_altivec_vcmpequd_p: 9952 if (Subtarget.hasP8Altivec()) { 9953 CompareOpc = 199; 9954 isDot = true; 9955 } else 9956 return false; 9957 break; 9958 case Intrinsic::ppc_altivec_vcmpneb_p: 9959 case Intrinsic::ppc_altivec_vcmpneh_p: 9960 case Intrinsic::ppc_altivec_vcmpnew_p: 9961 case Intrinsic::ppc_altivec_vcmpnezb_p: 9962 case Intrinsic::ppc_altivec_vcmpnezh_p: 9963 case Intrinsic::ppc_altivec_vcmpnezw_p: 9964 if (Subtarget.hasP9Altivec()) { 9965 switch (IntrinsicID) { 9966 default: 9967 llvm_unreachable("Unknown comparison intrinsic."); 9968 case Intrinsic::ppc_altivec_vcmpneb_p: 9969 CompareOpc = 7; 9970 break; 9971 case Intrinsic::ppc_altivec_vcmpneh_p: 9972 CompareOpc = 71; 9973 break; 9974 case Intrinsic::ppc_altivec_vcmpnew_p: 9975 CompareOpc = 135; 9976 break; 9977 case Intrinsic::ppc_altivec_vcmpnezb_p: 9978 CompareOpc = 263; 9979 break; 9980 case Intrinsic::ppc_altivec_vcmpnezh_p: 9981 CompareOpc = 327; 9982 break; 9983 case Intrinsic::ppc_altivec_vcmpnezw_p: 9984 CompareOpc = 391; 9985 break; 9986 } 9987 isDot = true; 9988 } else 9989 return false; 9990 break; 9991 case Intrinsic::ppc_altivec_vcmpgefp_p: 9992 CompareOpc = 454; 9993 isDot = true; 9994 break; 9995 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9996 CompareOpc = 710; 9997 isDot = true; 9998 break; 9999 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10000 CompareOpc = 774; 10001 isDot = true; 10002 break; 10003 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10004 CompareOpc = 838; 10005 isDot = true; 10006 break; 10007 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10008 CompareOpc = 902; 10009 isDot = true; 10010 break; 10011 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10012 if (Subtarget.hasP8Altivec()) { 10013 CompareOpc = 967; 10014 isDot = true; 10015 } else 10016 return false; 10017 break; 10018 case Intrinsic::ppc_altivec_vcmpgtub_p: 10019 CompareOpc = 518; 10020 isDot = true; 10021 break; 10022 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10023 CompareOpc = 582; 10024 isDot = true; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10027 CompareOpc = 646; 10028 isDot = true; 10029 break; 10030 case Intrinsic::ppc_altivec_vcmpgtud_p: 10031 if (Subtarget.hasP8Altivec()) { 10032 CompareOpc = 711; 10033 isDot = true; 10034 } else 10035 return false; 10036 break; 10037 10038 // VSX predicate comparisons use the same infrastructure 10039 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10040 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10041 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10042 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10043 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10044 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10045 if (Subtarget.hasVSX()) { 10046 switch (IntrinsicID) { 10047 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10048 CompareOpc = 99; 10049 break; 10050 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10051 CompareOpc = 115; 10052 break; 10053 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10054 CompareOpc = 107; 10055 break; 10056 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10057 CompareOpc = 67; 10058 break; 10059 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10060 CompareOpc = 83; 10061 break; 10062 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10063 CompareOpc = 75; 10064 break; 10065 } 10066 isDot = true; 10067 } else 10068 return false; 10069 break; 10070 10071 // Normal Comparisons. 10072 case Intrinsic::ppc_altivec_vcmpbfp: 10073 CompareOpc = 966; 10074 break; 10075 case Intrinsic::ppc_altivec_vcmpeqfp: 10076 CompareOpc = 198; 10077 break; 10078 case Intrinsic::ppc_altivec_vcmpequb: 10079 CompareOpc = 6; 10080 break; 10081 case Intrinsic::ppc_altivec_vcmpequh: 10082 CompareOpc = 70; 10083 break; 10084 case Intrinsic::ppc_altivec_vcmpequw: 10085 CompareOpc = 134; 10086 break; 10087 case Intrinsic::ppc_altivec_vcmpequd: 10088 if (Subtarget.hasP8Altivec()) 10089 CompareOpc = 199; 10090 else 10091 return false; 10092 break; 10093 case Intrinsic::ppc_altivec_vcmpneb: 10094 case Intrinsic::ppc_altivec_vcmpneh: 10095 case Intrinsic::ppc_altivec_vcmpnew: 10096 case Intrinsic::ppc_altivec_vcmpnezb: 10097 case Intrinsic::ppc_altivec_vcmpnezh: 10098 case Intrinsic::ppc_altivec_vcmpnezw: 10099 if (Subtarget.hasP9Altivec()) 10100 switch (IntrinsicID) { 10101 default: 10102 llvm_unreachable("Unknown comparison intrinsic."); 10103 case Intrinsic::ppc_altivec_vcmpneb: 10104 CompareOpc = 7; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpneh: 10107 CompareOpc = 71; 10108 break; 10109 case Intrinsic::ppc_altivec_vcmpnew: 10110 CompareOpc = 135; 10111 break; 10112 case Intrinsic::ppc_altivec_vcmpnezb: 10113 CompareOpc = 263; 10114 break; 10115 case Intrinsic::ppc_altivec_vcmpnezh: 10116 CompareOpc = 327; 10117 break; 10118 case Intrinsic::ppc_altivec_vcmpnezw: 10119 CompareOpc = 391; 10120 break; 10121 } 10122 else 10123 return false; 10124 break; 10125 case Intrinsic::ppc_altivec_vcmpgefp: 10126 CompareOpc = 454; 10127 break; 10128 case Intrinsic::ppc_altivec_vcmpgtfp: 10129 CompareOpc = 710; 10130 break; 10131 case Intrinsic::ppc_altivec_vcmpgtsb: 10132 CompareOpc = 774; 10133 break; 10134 case Intrinsic::ppc_altivec_vcmpgtsh: 10135 CompareOpc = 838; 10136 break; 10137 case Intrinsic::ppc_altivec_vcmpgtsw: 10138 CompareOpc = 902; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpgtsd: 10141 if (Subtarget.hasP8Altivec()) 10142 CompareOpc = 967; 10143 else 10144 return false; 10145 break; 10146 case Intrinsic::ppc_altivec_vcmpgtub: 10147 CompareOpc = 518; 10148 break; 10149 case Intrinsic::ppc_altivec_vcmpgtuh: 10150 CompareOpc = 582; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpgtuw: 10153 CompareOpc = 646; 10154 break; 10155 case Intrinsic::ppc_altivec_vcmpgtud: 10156 if (Subtarget.hasP8Altivec()) 10157 CompareOpc = 711; 10158 else 10159 return false; 10160 break; 10161 } 10162 return true; 10163 } 10164 10165 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10166 /// lower, do it, otherwise return null. 10167 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10168 SelectionDAG &DAG) const { 10169 unsigned IntrinsicID = 10170 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10171 10172 SDLoc dl(Op); 10173 10174 if (IntrinsicID == Intrinsic::thread_pointer) { 10175 // Reads the thread pointer register, used for __builtin_thread_pointer. 10176 if (Subtarget.isPPC64()) 10177 return DAG.getRegister(PPC::X13, MVT::i64); 10178 return DAG.getRegister(PPC::R2, MVT::i32); 10179 } 10180 10181 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10182 // opcode number of the comparison. 10183 int CompareOpc; 10184 bool isDot; 10185 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10186 return SDValue(); // Don't custom lower most intrinsics. 10187 10188 // If this is a non-dot comparison, make the VCMP node and we are done. 10189 if (!isDot) { 10190 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10191 Op.getOperand(1), Op.getOperand(2), 10192 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10193 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10194 } 10195 10196 // Create the PPCISD altivec 'dot' comparison node. 10197 SDValue Ops[] = { 10198 Op.getOperand(2), // LHS 10199 Op.getOperand(3), // RHS 10200 DAG.getConstant(CompareOpc, dl, MVT::i32) 10201 }; 10202 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10203 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10204 10205 // Now that we have the comparison, emit a copy from the CR to a GPR. 10206 // This is flagged to the above dot comparison. 10207 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10208 DAG.getRegister(PPC::CR6, MVT::i32), 10209 CompNode.getValue(1)); 10210 10211 // Unpack the result based on how the target uses it. 10212 unsigned BitNo; // Bit # of CR6. 10213 bool InvertBit; // Invert result? 10214 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10215 default: // Can't happen, don't crash on invalid number though. 10216 case 0: // Return the value of the EQ bit of CR6. 10217 BitNo = 0; InvertBit = false; 10218 break; 10219 case 1: // Return the inverted value of the EQ bit of CR6. 10220 BitNo = 0; InvertBit = true; 10221 break; 10222 case 2: // Return the value of the LT bit of CR6. 10223 BitNo = 2; InvertBit = false; 10224 break; 10225 case 3: // Return the inverted value of the LT bit of CR6. 10226 BitNo = 2; InvertBit = true; 10227 break; 10228 } 10229 10230 // Shift the bit into the low position. 10231 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10232 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10233 // Isolate the bit. 10234 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10235 DAG.getConstant(1, dl, MVT::i32)); 10236 10237 // If we are supposed to, toggle the bit. 10238 if (InvertBit) 10239 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10240 DAG.getConstant(1, dl, MVT::i32)); 10241 return Flags; 10242 } 10243 10244 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10245 SelectionDAG &DAG) const { 10246 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10247 // the beginning of the argument list. 10248 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10249 SDLoc DL(Op); 10250 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10251 case Intrinsic::ppc_cfence: { 10252 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10253 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10254 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10255 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10256 Op.getOperand(ArgStart + 1)), 10257 Op.getOperand(0)), 10258 0); 10259 } 10260 default: 10261 break; 10262 } 10263 return SDValue(); 10264 } 10265 10266 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10267 // Check for a DIV with the same operands as this REM. 10268 for (auto UI : Op.getOperand(1)->uses()) { 10269 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10270 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10271 if (UI->getOperand(0) == Op.getOperand(0) && 10272 UI->getOperand(1) == Op.getOperand(1)) 10273 return SDValue(); 10274 } 10275 return Op; 10276 } 10277 10278 // Lower scalar BSWAP64 to xxbrd. 10279 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10280 SDLoc dl(Op); 10281 // MTVSRDD 10282 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10283 Op.getOperand(0)); 10284 // XXBRD 10285 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10286 // MFVSRD 10287 int VectorIndex = 0; 10288 if (Subtarget.isLittleEndian()) 10289 VectorIndex = 1; 10290 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10291 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10292 return Op; 10293 } 10294 10295 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10296 // compared to a value that is atomically loaded (atomic loads zero-extend). 10297 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10298 SelectionDAG &DAG) const { 10299 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10300 "Expecting an atomic compare-and-swap here."); 10301 SDLoc dl(Op); 10302 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10303 EVT MemVT = AtomicNode->getMemoryVT(); 10304 if (MemVT.getSizeInBits() >= 32) 10305 return Op; 10306 10307 SDValue CmpOp = Op.getOperand(2); 10308 // If this is already correctly zero-extended, leave it alone. 10309 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10310 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10311 return Op; 10312 10313 // Clear the high bits of the compare operand. 10314 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10315 SDValue NewCmpOp = 10316 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10317 DAG.getConstant(MaskVal, dl, MVT::i32)); 10318 10319 // Replace the existing compare operand with the properly zero-extended one. 10320 SmallVector<SDValue, 4> Ops; 10321 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10322 Ops.push_back(AtomicNode->getOperand(i)); 10323 Ops[2] = NewCmpOp; 10324 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10325 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10326 auto NodeTy = 10327 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10328 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10329 } 10330 10331 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10332 SelectionDAG &DAG) const { 10333 SDLoc dl(Op); 10334 // Create a stack slot that is 16-byte aligned. 10335 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10336 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10337 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10338 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10339 10340 // Store the input value into Value#0 of the stack slot. 10341 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10342 MachinePointerInfo()); 10343 // Load it out. 10344 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10345 } 10346 10347 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10348 SelectionDAG &DAG) const { 10349 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10350 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10351 10352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10353 // We have legal lowering for constant indices but not for variable ones. 10354 if (!C) 10355 return SDValue(); 10356 10357 EVT VT = Op.getValueType(); 10358 SDLoc dl(Op); 10359 SDValue V1 = Op.getOperand(0); 10360 SDValue V2 = Op.getOperand(1); 10361 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10362 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10363 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10364 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10365 unsigned InsertAtElement = C->getZExtValue(); 10366 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10367 if (Subtarget.isLittleEndian()) { 10368 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10369 } 10370 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10371 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10372 } 10373 return Op; 10374 } 10375 10376 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10377 SelectionDAG &DAG) const { 10378 SDLoc dl(Op); 10379 SDNode *N = Op.getNode(); 10380 10381 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10382 "Unknown extract_vector_elt type"); 10383 10384 SDValue Value = N->getOperand(0); 10385 10386 // The first part of this is like the store lowering except that we don't 10387 // need to track the chain. 10388 10389 // The values are now known to be -1 (false) or 1 (true). To convert this 10390 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10391 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10392 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10393 10394 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10395 // understand how to form the extending load. 10396 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10397 10398 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10399 10400 // Now convert to an integer and store. 10401 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10402 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10403 Value); 10404 10405 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10406 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10407 MachinePointerInfo PtrInfo = 10408 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10409 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10410 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10411 10412 SDValue StoreChain = DAG.getEntryNode(); 10413 SDValue Ops[] = {StoreChain, 10414 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10415 Value, FIdx}; 10416 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10417 10418 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10419 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10420 10421 // Extract the value requested. 10422 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10423 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10424 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10425 10426 SDValue IntVal = 10427 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10428 10429 if (!Subtarget.useCRBits()) 10430 return IntVal; 10431 10432 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10433 } 10434 10435 /// Lowering for QPX v4i1 loads 10436 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10437 SelectionDAG &DAG) const { 10438 SDLoc dl(Op); 10439 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10440 SDValue LoadChain = LN->getChain(); 10441 SDValue BasePtr = LN->getBasePtr(); 10442 10443 if (Op.getValueType() == MVT::v4f64 || 10444 Op.getValueType() == MVT::v4f32) { 10445 EVT MemVT = LN->getMemoryVT(); 10446 unsigned Alignment = LN->getAlignment(); 10447 10448 // If this load is properly aligned, then it is legal. 10449 if (Alignment >= MemVT.getStoreSize()) 10450 return Op; 10451 10452 EVT ScalarVT = Op.getValueType().getScalarType(), 10453 ScalarMemVT = MemVT.getScalarType(); 10454 unsigned Stride = ScalarMemVT.getStoreSize(); 10455 10456 SDValue Vals[4], LoadChains[4]; 10457 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10458 SDValue Load; 10459 if (ScalarVT != ScalarMemVT) 10460 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10461 BasePtr, 10462 LN->getPointerInfo().getWithOffset(Idx * Stride), 10463 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10464 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10465 else 10466 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10467 LN->getPointerInfo().getWithOffset(Idx * Stride), 10468 MinAlign(Alignment, Idx * Stride), 10469 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10470 10471 if (Idx == 0 && LN->isIndexed()) { 10472 assert(LN->getAddressingMode() == ISD::PRE_INC && 10473 "Unknown addressing mode on vector load"); 10474 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10475 LN->getAddressingMode()); 10476 } 10477 10478 Vals[Idx] = Load; 10479 LoadChains[Idx] = Load.getValue(1); 10480 10481 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10482 DAG.getConstant(Stride, dl, 10483 BasePtr.getValueType())); 10484 } 10485 10486 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10487 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10488 10489 if (LN->isIndexed()) { 10490 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10491 return DAG.getMergeValues(RetOps, dl); 10492 } 10493 10494 SDValue RetOps[] = { Value, TF }; 10495 return DAG.getMergeValues(RetOps, dl); 10496 } 10497 10498 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10499 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10500 10501 // To lower v4i1 from a byte array, we load the byte elements of the 10502 // vector and then reuse the BUILD_VECTOR logic. 10503 10504 SDValue VectElmts[4], VectElmtChains[4]; 10505 for (unsigned i = 0; i < 4; ++i) { 10506 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10507 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10508 10509 VectElmts[i] = DAG.getExtLoad( 10510 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10511 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10512 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10513 VectElmtChains[i] = VectElmts[i].getValue(1); 10514 } 10515 10516 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10517 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10518 10519 SDValue RVals[] = { Value, LoadChain }; 10520 return DAG.getMergeValues(RVals, dl); 10521 } 10522 10523 /// Lowering for QPX v4i1 stores 10524 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10525 SelectionDAG &DAG) const { 10526 SDLoc dl(Op); 10527 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10528 SDValue StoreChain = SN->getChain(); 10529 SDValue BasePtr = SN->getBasePtr(); 10530 SDValue Value = SN->getValue(); 10531 10532 if (Value.getValueType() == MVT::v4f64 || 10533 Value.getValueType() == MVT::v4f32) { 10534 EVT MemVT = SN->getMemoryVT(); 10535 unsigned Alignment = SN->getAlignment(); 10536 10537 // If this store is properly aligned, then it is legal. 10538 if (Alignment >= MemVT.getStoreSize()) 10539 return Op; 10540 10541 EVT ScalarVT = Value.getValueType().getScalarType(), 10542 ScalarMemVT = MemVT.getScalarType(); 10543 unsigned Stride = ScalarMemVT.getStoreSize(); 10544 10545 SDValue Stores[4]; 10546 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10547 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10548 DAG.getVectorIdxConstant(Idx, dl)); 10549 SDValue Store; 10550 if (ScalarVT != ScalarMemVT) 10551 Store = 10552 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10553 SN->getPointerInfo().getWithOffset(Idx * Stride), 10554 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10555 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10556 else 10557 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10558 SN->getPointerInfo().getWithOffset(Idx * Stride), 10559 MinAlign(Alignment, Idx * Stride), 10560 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10561 10562 if (Idx == 0 && SN->isIndexed()) { 10563 assert(SN->getAddressingMode() == ISD::PRE_INC && 10564 "Unknown addressing mode on vector store"); 10565 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10566 SN->getAddressingMode()); 10567 } 10568 10569 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10570 DAG.getConstant(Stride, dl, 10571 BasePtr.getValueType())); 10572 Stores[Idx] = Store; 10573 } 10574 10575 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10576 10577 if (SN->isIndexed()) { 10578 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10579 return DAG.getMergeValues(RetOps, dl); 10580 } 10581 10582 return TF; 10583 } 10584 10585 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10586 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10587 10588 // The values are now known to be -1 (false) or 1 (true). To convert this 10589 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10590 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10591 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10592 10593 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10594 // understand how to form the extending load. 10595 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10596 10597 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10598 10599 // Now convert to an integer and store. 10600 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10601 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10602 Value); 10603 10604 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10605 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10606 MachinePointerInfo PtrInfo = 10607 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10608 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10609 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10610 10611 SDValue Ops[] = {StoreChain, 10612 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10613 Value, FIdx}; 10614 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10615 10616 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10617 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10618 10619 // Move data into the byte array. 10620 SDValue Loads[4], LoadChains[4]; 10621 for (unsigned i = 0; i < 4; ++i) { 10622 unsigned Offset = 4*i; 10623 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10624 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10625 10626 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10627 PtrInfo.getWithOffset(Offset)); 10628 LoadChains[i] = Loads[i].getValue(1); 10629 } 10630 10631 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10632 10633 SDValue Stores[4]; 10634 for (unsigned i = 0; i < 4; ++i) { 10635 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10636 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10637 10638 Stores[i] = DAG.getTruncStore( 10639 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10640 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10641 SN->getAAInfo()); 10642 } 10643 10644 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10645 10646 return StoreChain; 10647 } 10648 10649 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10650 SDLoc dl(Op); 10651 if (Op.getValueType() == MVT::v4i32) { 10652 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10653 10654 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10655 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10656 10657 SDValue RHSSwap = // = vrlw RHS, 16 10658 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10659 10660 // Shrinkify inputs to v8i16. 10661 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10662 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10663 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10664 10665 // Low parts multiplied together, generating 32-bit results (we ignore the 10666 // top parts). 10667 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10668 LHS, RHS, DAG, dl, MVT::v4i32); 10669 10670 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10671 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10672 // Shift the high parts up 16 bits. 10673 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10674 Neg16, DAG, dl); 10675 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10676 } else if (Op.getValueType() == MVT::v16i8) { 10677 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10678 bool isLittleEndian = Subtarget.isLittleEndian(); 10679 10680 // Multiply the even 8-bit parts, producing 16-bit sums. 10681 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10682 LHS, RHS, DAG, dl, MVT::v8i16); 10683 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10684 10685 // Multiply the odd 8-bit parts, producing 16-bit sums. 10686 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10687 LHS, RHS, DAG, dl, MVT::v8i16); 10688 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10689 10690 // Merge the results together. Because vmuleub and vmuloub are 10691 // instructions with a big-endian bias, we must reverse the 10692 // element numbering and reverse the meaning of "odd" and "even" 10693 // when generating little endian code. 10694 int Ops[16]; 10695 for (unsigned i = 0; i != 8; ++i) { 10696 if (isLittleEndian) { 10697 Ops[i*2 ] = 2*i; 10698 Ops[i*2+1] = 2*i+16; 10699 } else { 10700 Ops[i*2 ] = 2*i+1; 10701 Ops[i*2+1] = 2*i+1+16; 10702 } 10703 } 10704 if (isLittleEndian) 10705 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10706 else 10707 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10708 } else { 10709 llvm_unreachable("Unknown mul to lower!"); 10710 } 10711 } 10712 10713 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10714 10715 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10716 10717 EVT VT = Op.getValueType(); 10718 assert(VT.isVector() && 10719 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10720 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10721 VT == MVT::v16i8) && 10722 "Unexpected vector element type!"); 10723 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10724 "Current subtarget doesn't support smax v2i64!"); 10725 10726 // For vector abs, it can be lowered to: 10727 // abs x 10728 // ==> 10729 // y = -x 10730 // smax(x, y) 10731 10732 SDLoc dl(Op); 10733 SDValue X = Op.getOperand(0); 10734 SDValue Zero = DAG.getConstant(0, dl, VT); 10735 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10736 10737 // SMAX patch https://reviews.llvm.org/D47332 10738 // hasn't landed yet, so use intrinsic first here. 10739 // TODO: Should use SMAX directly once SMAX patch landed 10740 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10741 if (VT == MVT::v2i64) 10742 BifID = Intrinsic::ppc_altivec_vmaxsd; 10743 else if (VT == MVT::v8i16) 10744 BifID = Intrinsic::ppc_altivec_vmaxsh; 10745 else if (VT == MVT::v16i8) 10746 BifID = Intrinsic::ppc_altivec_vmaxsb; 10747 10748 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10749 } 10750 10751 // Custom lowering for fpext vf32 to v2f64 10752 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10753 10754 assert(Op.getOpcode() == ISD::FP_EXTEND && 10755 "Should only be called for ISD::FP_EXTEND"); 10756 10757 // We only want to custom lower an extend from v2f32 to v2f64. 10758 if (Op.getValueType() != MVT::v2f64 || 10759 Op.getOperand(0).getValueType() != MVT::v2f32) 10760 return SDValue(); 10761 10762 SDLoc dl(Op); 10763 SDValue Op0 = Op.getOperand(0); 10764 10765 switch (Op0.getOpcode()) { 10766 default: 10767 return SDValue(); 10768 case ISD::EXTRACT_SUBVECTOR: { 10769 assert(Op0.getNumOperands() == 2 && 10770 isa<ConstantSDNode>(Op0->getOperand(1)) && 10771 "Node should have 2 operands with second one being a constant!"); 10772 10773 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10774 return SDValue(); 10775 10776 // Custom lower is only done for high or low doubleword. 10777 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10778 if (Idx % 2 != 0) 10779 return SDValue(); 10780 10781 // Since input is v4f32, at this point Idx is either 0 or 2. 10782 // Shift to get the doubleword position we want. 10783 int DWord = Idx >> 1; 10784 10785 // High and low word positions are different on little endian. 10786 if (Subtarget.isLittleEndian()) 10787 DWord ^= 0x1; 10788 10789 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10790 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10791 } 10792 case ISD::FADD: 10793 case ISD::FMUL: 10794 case ISD::FSUB: { 10795 SDValue NewLoad[2]; 10796 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10797 // Ensure both input are loads. 10798 SDValue LdOp = Op0.getOperand(i); 10799 if (LdOp.getOpcode() != ISD::LOAD) 10800 return SDValue(); 10801 // Generate new load node. 10802 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10803 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10804 NewLoad[i] = DAG.getMemIntrinsicNode( 10805 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10806 LD->getMemoryVT(), LD->getMemOperand()); 10807 } 10808 SDValue NewOp = 10809 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10810 NewLoad[1], Op0.getNode()->getFlags()); 10811 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10812 DAG.getConstant(0, dl, MVT::i32)); 10813 } 10814 case ISD::LOAD: { 10815 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10816 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10817 SDValue NewLd = DAG.getMemIntrinsicNode( 10818 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10819 LD->getMemoryVT(), LD->getMemOperand()); 10820 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10821 DAG.getConstant(0, dl, MVT::i32)); 10822 } 10823 } 10824 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10825 } 10826 10827 /// LowerOperation - Provide custom lowering hooks for some operations. 10828 /// 10829 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10830 switch (Op.getOpcode()) { 10831 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10832 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10833 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10834 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10835 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10836 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10837 case ISD::SETCC: return LowerSETCC(Op, DAG); 10838 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10839 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10840 10841 // Variable argument lowering. 10842 case ISD::VASTART: return LowerVASTART(Op, DAG); 10843 case ISD::VAARG: return LowerVAARG(Op, DAG); 10844 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10845 10846 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10847 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10848 case ISD::GET_DYNAMIC_AREA_OFFSET: 10849 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10850 10851 // Exception handling lowering. 10852 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10853 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10854 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10855 10856 case ISD::LOAD: return LowerLOAD(Op, DAG); 10857 case ISD::STORE: return LowerSTORE(Op, DAG); 10858 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10859 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10860 case ISD::FP_TO_UINT: 10861 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10862 case ISD::UINT_TO_FP: 10863 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10864 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10865 10866 // Lower 64-bit shifts. 10867 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10868 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10869 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10870 10871 // Vector-related lowering. 10872 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10873 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10874 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10875 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10876 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10877 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10878 case ISD::MUL: return LowerMUL(Op, DAG); 10879 case ISD::ABS: return LowerABS(Op, DAG); 10880 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10881 10882 // For counter-based loop handling. 10883 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10884 10885 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10886 10887 // Frame & Return address. 10888 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10889 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10890 10891 case ISD::INTRINSIC_VOID: 10892 return LowerINTRINSIC_VOID(Op, DAG); 10893 case ISD::SREM: 10894 case ISD::UREM: 10895 return LowerREM(Op, DAG); 10896 case ISD::BSWAP: 10897 return LowerBSWAP(Op, DAG); 10898 case ISD::ATOMIC_CMP_SWAP: 10899 return LowerATOMIC_CMP_SWAP(Op, DAG); 10900 } 10901 } 10902 10903 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10904 SmallVectorImpl<SDValue>&Results, 10905 SelectionDAG &DAG) const { 10906 SDLoc dl(N); 10907 switch (N->getOpcode()) { 10908 default: 10909 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10910 case ISD::READCYCLECOUNTER: { 10911 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10912 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10913 10914 Results.push_back( 10915 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10916 Results.push_back(RTB.getValue(2)); 10917 break; 10918 } 10919 case ISD::INTRINSIC_W_CHAIN: { 10920 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10921 Intrinsic::loop_decrement) 10922 break; 10923 10924 assert(N->getValueType(0) == MVT::i1 && 10925 "Unexpected result type for CTR decrement intrinsic"); 10926 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10927 N->getValueType(0)); 10928 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10929 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10930 N->getOperand(1)); 10931 10932 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10933 Results.push_back(NewInt.getValue(1)); 10934 break; 10935 } 10936 case ISD::VAARG: { 10937 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10938 return; 10939 10940 EVT VT = N->getValueType(0); 10941 10942 if (VT == MVT::i64) { 10943 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10944 10945 Results.push_back(NewNode); 10946 Results.push_back(NewNode.getValue(1)); 10947 } 10948 return; 10949 } 10950 case ISD::FP_TO_SINT: 10951 case ISD::FP_TO_UINT: 10952 // LowerFP_TO_INT() can only handle f32 and f64. 10953 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10954 return; 10955 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10956 return; 10957 case ISD::TRUNCATE: { 10958 EVT TrgVT = N->getValueType(0); 10959 EVT OpVT = N->getOperand(0).getValueType(); 10960 if (TrgVT.isVector() && 10961 isOperationCustom(N->getOpcode(), TrgVT) && 10962 OpVT.getSizeInBits() <= 128 && 10963 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10964 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10965 return; 10966 } 10967 case ISD::BITCAST: 10968 // Don't handle bitcast here. 10969 return; 10970 } 10971 } 10972 10973 //===----------------------------------------------------------------------===// 10974 // Other Lowering Code 10975 //===----------------------------------------------------------------------===// 10976 10977 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10978 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10979 Function *Func = Intrinsic::getDeclaration(M, Id); 10980 return Builder.CreateCall(Func, {}); 10981 } 10982 10983 // The mappings for emitLeading/TrailingFence is taken from 10984 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10985 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10986 Instruction *Inst, 10987 AtomicOrdering Ord) const { 10988 if (Ord == AtomicOrdering::SequentiallyConsistent) 10989 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10990 if (isReleaseOrStronger(Ord)) 10991 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10992 return nullptr; 10993 } 10994 10995 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10996 Instruction *Inst, 10997 AtomicOrdering Ord) const { 10998 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10999 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11000 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11001 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11002 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11003 return Builder.CreateCall( 11004 Intrinsic::getDeclaration( 11005 Builder.GetInsertBlock()->getParent()->getParent(), 11006 Intrinsic::ppc_cfence, {Inst->getType()}), 11007 {Inst}); 11008 // FIXME: Can use isync for rmw operation. 11009 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11010 } 11011 return nullptr; 11012 } 11013 11014 MachineBasicBlock * 11015 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11016 unsigned AtomicSize, 11017 unsigned BinOpcode, 11018 unsigned CmpOpcode, 11019 unsigned CmpPred) const { 11020 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11021 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11022 11023 auto LoadMnemonic = PPC::LDARX; 11024 auto StoreMnemonic = PPC::STDCX; 11025 switch (AtomicSize) { 11026 default: 11027 llvm_unreachable("Unexpected size of atomic entity"); 11028 case 1: 11029 LoadMnemonic = PPC::LBARX; 11030 StoreMnemonic = PPC::STBCX; 11031 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11032 break; 11033 case 2: 11034 LoadMnemonic = PPC::LHARX; 11035 StoreMnemonic = PPC::STHCX; 11036 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11037 break; 11038 case 4: 11039 LoadMnemonic = PPC::LWARX; 11040 StoreMnemonic = PPC::STWCX; 11041 break; 11042 case 8: 11043 LoadMnemonic = PPC::LDARX; 11044 StoreMnemonic = PPC::STDCX; 11045 break; 11046 } 11047 11048 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11049 MachineFunction *F = BB->getParent(); 11050 MachineFunction::iterator It = ++BB->getIterator(); 11051 11052 Register dest = MI.getOperand(0).getReg(); 11053 Register ptrA = MI.getOperand(1).getReg(); 11054 Register ptrB = MI.getOperand(2).getReg(); 11055 Register incr = MI.getOperand(3).getReg(); 11056 DebugLoc dl = MI.getDebugLoc(); 11057 11058 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11059 MachineBasicBlock *loop2MBB = 11060 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11061 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11062 F->insert(It, loopMBB); 11063 if (CmpOpcode) 11064 F->insert(It, loop2MBB); 11065 F->insert(It, exitMBB); 11066 exitMBB->splice(exitMBB->begin(), BB, 11067 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11068 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11069 11070 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11071 Register TmpReg = (!BinOpcode) ? incr : 11072 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11073 : &PPC::GPRCRegClass); 11074 11075 // thisMBB: 11076 // ... 11077 // fallthrough --> loopMBB 11078 BB->addSuccessor(loopMBB); 11079 11080 // loopMBB: 11081 // l[wd]arx dest, ptr 11082 // add r0, dest, incr 11083 // st[wd]cx. r0, ptr 11084 // bne- loopMBB 11085 // fallthrough --> exitMBB 11086 11087 // For max/min... 11088 // loopMBB: 11089 // l[wd]arx dest, ptr 11090 // cmpl?[wd] incr, dest 11091 // bgt exitMBB 11092 // loop2MBB: 11093 // st[wd]cx. dest, ptr 11094 // bne- loopMBB 11095 // fallthrough --> exitMBB 11096 11097 BB = loopMBB; 11098 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11099 .addReg(ptrA).addReg(ptrB); 11100 if (BinOpcode) 11101 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11102 if (CmpOpcode) { 11103 // Signed comparisons of byte or halfword values must be sign-extended. 11104 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11105 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11106 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11107 ExtReg).addReg(dest); 11108 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11109 .addReg(incr).addReg(ExtReg); 11110 } else 11111 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11112 .addReg(incr).addReg(dest); 11113 11114 BuildMI(BB, dl, TII->get(PPC::BCC)) 11115 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11116 BB->addSuccessor(loop2MBB); 11117 BB->addSuccessor(exitMBB); 11118 BB = loop2MBB; 11119 } 11120 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11121 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11122 BuildMI(BB, dl, TII->get(PPC::BCC)) 11123 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11124 BB->addSuccessor(loopMBB); 11125 BB->addSuccessor(exitMBB); 11126 11127 // exitMBB: 11128 // ... 11129 BB = exitMBB; 11130 return BB; 11131 } 11132 11133 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11134 MachineInstr &MI, MachineBasicBlock *BB, 11135 bool is8bit, // operation 11136 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11137 // If we support part-word atomic mnemonics, just use them 11138 if (Subtarget.hasPartwordAtomics()) 11139 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11140 CmpPred); 11141 11142 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11143 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11144 // In 64 bit mode we have to use 64 bits for addresses, even though the 11145 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11146 // registers without caring whether they're 32 or 64, but here we're 11147 // doing actual arithmetic on the addresses. 11148 bool is64bit = Subtarget.isPPC64(); 11149 bool isLittleEndian = Subtarget.isLittleEndian(); 11150 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11151 11152 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11153 MachineFunction *F = BB->getParent(); 11154 MachineFunction::iterator It = ++BB->getIterator(); 11155 11156 Register dest = MI.getOperand(0).getReg(); 11157 Register ptrA = MI.getOperand(1).getReg(); 11158 Register ptrB = MI.getOperand(2).getReg(); 11159 Register incr = MI.getOperand(3).getReg(); 11160 DebugLoc dl = MI.getDebugLoc(); 11161 11162 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11163 MachineBasicBlock *loop2MBB = 11164 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11165 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11166 F->insert(It, loopMBB); 11167 if (CmpOpcode) 11168 F->insert(It, loop2MBB); 11169 F->insert(It, exitMBB); 11170 exitMBB->splice(exitMBB->begin(), BB, 11171 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11172 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11173 11174 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11175 const TargetRegisterClass *RC = 11176 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11177 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11178 11179 Register PtrReg = RegInfo.createVirtualRegister(RC); 11180 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11181 Register ShiftReg = 11182 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11183 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11184 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11185 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11186 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11187 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11188 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11189 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11190 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11191 Register Ptr1Reg; 11192 Register TmpReg = 11193 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11194 11195 // thisMBB: 11196 // ... 11197 // fallthrough --> loopMBB 11198 BB->addSuccessor(loopMBB); 11199 11200 // The 4-byte load must be aligned, while a char or short may be 11201 // anywhere in the word. Hence all this nasty bookkeeping code. 11202 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11203 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11204 // xori shift, shift1, 24 [16] 11205 // rlwinm ptr, ptr1, 0, 0, 29 11206 // slw incr2, incr, shift 11207 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11208 // slw mask, mask2, shift 11209 // loopMBB: 11210 // lwarx tmpDest, ptr 11211 // add tmp, tmpDest, incr2 11212 // andc tmp2, tmpDest, mask 11213 // and tmp3, tmp, mask 11214 // or tmp4, tmp3, tmp2 11215 // stwcx. tmp4, ptr 11216 // bne- loopMBB 11217 // fallthrough --> exitMBB 11218 // srw dest, tmpDest, shift 11219 if (ptrA != ZeroReg) { 11220 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11221 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11222 .addReg(ptrA) 11223 .addReg(ptrB); 11224 } else { 11225 Ptr1Reg = ptrB; 11226 } 11227 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11228 // mode. 11229 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11230 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11231 .addImm(3) 11232 .addImm(27) 11233 .addImm(is8bit ? 28 : 27); 11234 if (!isLittleEndian) 11235 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11236 .addReg(Shift1Reg) 11237 .addImm(is8bit ? 24 : 16); 11238 if (is64bit) 11239 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11240 .addReg(Ptr1Reg) 11241 .addImm(0) 11242 .addImm(61); 11243 else 11244 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11245 .addReg(Ptr1Reg) 11246 .addImm(0) 11247 .addImm(0) 11248 .addImm(29); 11249 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11250 if (is8bit) 11251 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11252 else { 11253 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11254 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11255 .addReg(Mask3Reg) 11256 .addImm(65535); 11257 } 11258 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11259 .addReg(Mask2Reg) 11260 .addReg(ShiftReg); 11261 11262 BB = loopMBB; 11263 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11264 .addReg(ZeroReg) 11265 .addReg(PtrReg); 11266 if (BinOpcode) 11267 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11268 .addReg(Incr2Reg) 11269 .addReg(TmpDestReg); 11270 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11271 .addReg(TmpDestReg) 11272 .addReg(MaskReg); 11273 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11274 if (CmpOpcode) { 11275 // For unsigned comparisons, we can directly compare the shifted values. 11276 // For signed comparisons we shift and sign extend. 11277 Register SReg = RegInfo.createVirtualRegister(GPRC); 11278 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11279 .addReg(TmpDestReg) 11280 .addReg(MaskReg); 11281 unsigned ValueReg = SReg; 11282 unsigned CmpReg = Incr2Reg; 11283 if (CmpOpcode == PPC::CMPW) { 11284 ValueReg = RegInfo.createVirtualRegister(GPRC); 11285 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11286 .addReg(SReg) 11287 .addReg(ShiftReg); 11288 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11289 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11290 .addReg(ValueReg); 11291 ValueReg = ValueSReg; 11292 CmpReg = incr; 11293 } 11294 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11295 .addReg(CmpReg) 11296 .addReg(ValueReg); 11297 BuildMI(BB, dl, TII->get(PPC::BCC)) 11298 .addImm(CmpPred) 11299 .addReg(PPC::CR0) 11300 .addMBB(exitMBB); 11301 BB->addSuccessor(loop2MBB); 11302 BB->addSuccessor(exitMBB); 11303 BB = loop2MBB; 11304 } 11305 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11306 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11307 .addReg(Tmp4Reg) 11308 .addReg(ZeroReg) 11309 .addReg(PtrReg); 11310 BuildMI(BB, dl, TII->get(PPC::BCC)) 11311 .addImm(PPC::PRED_NE) 11312 .addReg(PPC::CR0) 11313 .addMBB(loopMBB); 11314 BB->addSuccessor(loopMBB); 11315 BB->addSuccessor(exitMBB); 11316 11317 // exitMBB: 11318 // ... 11319 BB = exitMBB; 11320 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11321 .addReg(TmpDestReg) 11322 .addReg(ShiftReg); 11323 return BB; 11324 } 11325 11326 llvm::MachineBasicBlock * 11327 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11328 MachineBasicBlock *MBB) const { 11329 DebugLoc DL = MI.getDebugLoc(); 11330 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11331 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11332 11333 MachineFunction *MF = MBB->getParent(); 11334 MachineRegisterInfo &MRI = MF->getRegInfo(); 11335 11336 const BasicBlock *BB = MBB->getBasicBlock(); 11337 MachineFunction::iterator I = ++MBB->getIterator(); 11338 11339 Register DstReg = MI.getOperand(0).getReg(); 11340 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11341 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11342 Register mainDstReg = MRI.createVirtualRegister(RC); 11343 Register restoreDstReg = MRI.createVirtualRegister(RC); 11344 11345 MVT PVT = getPointerTy(MF->getDataLayout()); 11346 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11347 "Invalid Pointer Size!"); 11348 // For v = setjmp(buf), we generate 11349 // 11350 // thisMBB: 11351 // SjLjSetup mainMBB 11352 // bl mainMBB 11353 // v_restore = 1 11354 // b sinkMBB 11355 // 11356 // mainMBB: 11357 // buf[LabelOffset] = LR 11358 // v_main = 0 11359 // 11360 // sinkMBB: 11361 // v = phi(main, restore) 11362 // 11363 11364 MachineBasicBlock *thisMBB = MBB; 11365 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11366 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11367 MF->insert(I, mainMBB); 11368 MF->insert(I, sinkMBB); 11369 11370 MachineInstrBuilder MIB; 11371 11372 // Transfer the remainder of BB and its successor edges to sinkMBB. 11373 sinkMBB->splice(sinkMBB->begin(), MBB, 11374 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11375 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11376 11377 // Note that the structure of the jmp_buf used here is not compatible 11378 // with that used by libc, and is not designed to be. Specifically, it 11379 // stores only those 'reserved' registers that LLVM does not otherwise 11380 // understand how to spill. Also, by convention, by the time this 11381 // intrinsic is called, Clang has already stored the frame address in the 11382 // first slot of the buffer and stack address in the third. Following the 11383 // X86 target code, we'll store the jump address in the second slot. We also 11384 // need to save the TOC pointer (R2) to handle jumps between shared 11385 // libraries, and that will be stored in the fourth slot. The thread 11386 // identifier (R13) is not affected. 11387 11388 // thisMBB: 11389 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11390 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11391 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11392 11393 // Prepare IP either in reg. 11394 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11395 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11396 Register BufReg = MI.getOperand(1).getReg(); 11397 11398 if (Subtarget.is64BitELFABI()) { 11399 setUsesTOCBasePtr(*MBB->getParent()); 11400 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11401 .addReg(PPC::X2) 11402 .addImm(TOCOffset) 11403 .addReg(BufReg) 11404 .cloneMemRefs(MI); 11405 } 11406 11407 // Naked functions never have a base pointer, and so we use r1. For all 11408 // other functions, this decision must be delayed until during PEI. 11409 unsigned BaseReg; 11410 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11411 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11412 else 11413 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11414 11415 MIB = BuildMI(*thisMBB, MI, DL, 11416 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11417 .addReg(BaseReg) 11418 .addImm(BPOffset) 11419 .addReg(BufReg) 11420 .cloneMemRefs(MI); 11421 11422 // Setup 11423 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11424 MIB.addRegMask(TRI->getNoPreservedMask()); 11425 11426 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11427 11428 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11429 .addMBB(mainMBB); 11430 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11431 11432 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11433 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11434 11435 // mainMBB: 11436 // mainDstReg = 0 11437 MIB = 11438 BuildMI(mainMBB, DL, 11439 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11440 11441 // Store IP 11442 if (Subtarget.isPPC64()) { 11443 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11444 .addReg(LabelReg) 11445 .addImm(LabelOffset) 11446 .addReg(BufReg); 11447 } else { 11448 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11449 .addReg(LabelReg) 11450 .addImm(LabelOffset) 11451 .addReg(BufReg); 11452 } 11453 MIB.cloneMemRefs(MI); 11454 11455 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11456 mainMBB->addSuccessor(sinkMBB); 11457 11458 // sinkMBB: 11459 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11460 TII->get(PPC::PHI), DstReg) 11461 .addReg(mainDstReg).addMBB(mainMBB) 11462 .addReg(restoreDstReg).addMBB(thisMBB); 11463 11464 MI.eraseFromParent(); 11465 return sinkMBB; 11466 } 11467 11468 MachineBasicBlock * 11469 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11470 MachineBasicBlock *MBB) const { 11471 DebugLoc DL = MI.getDebugLoc(); 11472 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11473 11474 MachineFunction *MF = MBB->getParent(); 11475 MachineRegisterInfo &MRI = MF->getRegInfo(); 11476 11477 MVT PVT = getPointerTy(MF->getDataLayout()); 11478 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11479 "Invalid Pointer Size!"); 11480 11481 const TargetRegisterClass *RC = 11482 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11483 Register Tmp = MRI.createVirtualRegister(RC); 11484 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11485 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11486 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11487 unsigned BP = 11488 (PVT == MVT::i64) 11489 ? PPC::X30 11490 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11491 : PPC::R30); 11492 11493 MachineInstrBuilder MIB; 11494 11495 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11496 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11497 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11498 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11499 11500 Register BufReg = MI.getOperand(0).getReg(); 11501 11502 // Reload FP (the jumped-to function may not have had a 11503 // frame pointer, and if so, then its r31 will be restored 11504 // as necessary). 11505 if (PVT == MVT::i64) { 11506 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11507 .addImm(0) 11508 .addReg(BufReg); 11509 } else { 11510 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11511 .addImm(0) 11512 .addReg(BufReg); 11513 } 11514 MIB.cloneMemRefs(MI); 11515 11516 // Reload IP 11517 if (PVT == MVT::i64) { 11518 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11519 .addImm(LabelOffset) 11520 .addReg(BufReg); 11521 } else { 11522 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11523 .addImm(LabelOffset) 11524 .addReg(BufReg); 11525 } 11526 MIB.cloneMemRefs(MI); 11527 11528 // Reload SP 11529 if (PVT == MVT::i64) { 11530 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11531 .addImm(SPOffset) 11532 .addReg(BufReg); 11533 } else { 11534 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11535 .addImm(SPOffset) 11536 .addReg(BufReg); 11537 } 11538 MIB.cloneMemRefs(MI); 11539 11540 // Reload BP 11541 if (PVT == MVT::i64) { 11542 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11543 .addImm(BPOffset) 11544 .addReg(BufReg); 11545 } else { 11546 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11547 .addImm(BPOffset) 11548 .addReg(BufReg); 11549 } 11550 MIB.cloneMemRefs(MI); 11551 11552 // Reload TOC 11553 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11554 setUsesTOCBasePtr(*MBB->getParent()); 11555 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11556 .addImm(TOCOffset) 11557 .addReg(BufReg) 11558 .cloneMemRefs(MI); 11559 } 11560 11561 // Jump 11562 BuildMI(*MBB, MI, DL, 11563 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11564 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11565 11566 MI.eraseFromParent(); 11567 return MBB; 11568 } 11569 11570 MachineBasicBlock * 11571 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11572 MachineBasicBlock *BB) const { 11573 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11574 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11575 if (Subtarget.is64BitELFABI() && 11576 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11577 !Subtarget.isUsingPCRelativeCalls()) { 11578 // Call lowering should have added an r2 operand to indicate a dependence 11579 // on the TOC base pointer value. It can't however, because there is no 11580 // way to mark the dependence as implicit there, and so the stackmap code 11581 // will confuse it with a regular operand. Instead, add the dependence 11582 // here. 11583 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11584 } 11585 11586 return emitPatchPoint(MI, BB); 11587 } 11588 11589 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11590 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11591 return emitEHSjLjSetJmp(MI, BB); 11592 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11593 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11594 return emitEHSjLjLongJmp(MI, BB); 11595 } 11596 11597 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11598 11599 // To "insert" these instructions we actually have to insert their 11600 // control-flow patterns. 11601 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11602 MachineFunction::iterator It = ++BB->getIterator(); 11603 11604 MachineFunction *F = BB->getParent(); 11605 11606 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11607 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11608 MI.getOpcode() == PPC::SELECT_I8) { 11609 SmallVector<MachineOperand, 2> Cond; 11610 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11611 MI.getOpcode() == PPC::SELECT_CC_I8) 11612 Cond.push_back(MI.getOperand(4)); 11613 else 11614 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11615 Cond.push_back(MI.getOperand(1)); 11616 11617 DebugLoc dl = MI.getDebugLoc(); 11618 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11619 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11620 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11621 MI.getOpcode() == PPC::SELECT_CC_F8 || 11622 MI.getOpcode() == PPC::SELECT_CC_F16 || 11623 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11624 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11625 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11626 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11627 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11628 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11629 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11630 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11631 MI.getOpcode() == PPC::SELECT_CC_SPE || 11632 MI.getOpcode() == PPC::SELECT_F4 || 11633 MI.getOpcode() == PPC::SELECT_F8 || 11634 MI.getOpcode() == PPC::SELECT_F16 || 11635 MI.getOpcode() == PPC::SELECT_QFRC || 11636 MI.getOpcode() == PPC::SELECT_QSRC || 11637 MI.getOpcode() == PPC::SELECT_QBRC || 11638 MI.getOpcode() == PPC::SELECT_SPE || 11639 MI.getOpcode() == PPC::SELECT_SPE4 || 11640 MI.getOpcode() == PPC::SELECT_VRRC || 11641 MI.getOpcode() == PPC::SELECT_VSFRC || 11642 MI.getOpcode() == PPC::SELECT_VSSRC || 11643 MI.getOpcode() == PPC::SELECT_VSRC) { 11644 // The incoming instruction knows the destination vreg to set, the 11645 // condition code register to branch on, the true/false values to 11646 // select between, and a branch opcode to use. 11647 11648 // thisMBB: 11649 // ... 11650 // TrueVal = ... 11651 // cmpTY ccX, r1, r2 11652 // bCC copy1MBB 11653 // fallthrough --> copy0MBB 11654 MachineBasicBlock *thisMBB = BB; 11655 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11656 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11657 DebugLoc dl = MI.getDebugLoc(); 11658 F->insert(It, copy0MBB); 11659 F->insert(It, sinkMBB); 11660 11661 // Transfer the remainder of BB and its successor edges to sinkMBB. 11662 sinkMBB->splice(sinkMBB->begin(), BB, 11663 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11664 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11665 11666 // Next, add the true and fallthrough blocks as its successors. 11667 BB->addSuccessor(copy0MBB); 11668 BB->addSuccessor(sinkMBB); 11669 11670 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11671 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11672 MI.getOpcode() == PPC::SELECT_F16 || 11673 MI.getOpcode() == PPC::SELECT_SPE4 || 11674 MI.getOpcode() == PPC::SELECT_SPE || 11675 MI.getOpcode() == PPC::SELECT_QFRC || 11676 MI.getOpcode() == PPC::SELECT_QSRC || 11677 MI.getOpcode() == PPC::SELECT_QBRC || 11678 MI.getOpcode() == PPC::SELECT_VRRC || 11679 MI.getOpcode() == PPC::SELECT_VSFRC || 11680 MI.getOpcode() == PPC::SELECT_VSSRC || 11681 MI.getOpcode() == PPC::SELECT_VSRC) { 11682 BuildMI(BB, dl, TII->get(PPC::BC)) 11683 .addReg(MI.getOperand(1).getReg()) 11684 .addMBB(sinkMBB); 11685 } else { 11686 unsigned SelectPred = MI.getOperand(4).getImm(); 11687 BuildMI(BB, dl, TII->get(PPC::BCC)) 11688 .addImm(SelectPred) 11689 .addReg(MI.getOperand(1).getReg()) 11690 .addMBB(sinkMBB); 11691 } 11692 11693 // copy0MBB: 11694 // %FalseValue = ... 11695 // # fallthrough to sinkMBB 11696 BB = copy0MBB; 11697 11698 // Update machine-CFG edges 11699 BB->addSuccessor(sinkMBB); 11700 11701 // sinkMBB: 11702 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11703 // ... 11704 BB = sinkMBB; 11705 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11706 .addReg(MI.getOperand(3).getReg()) 11707 .addMBB(copy0MBB) 11708 .addReg(MI.getOperand(2).getReg()) 11709 .addMBB(thisMBB); 11710 } else if (MI.getOpcode() == PPC::ReadTB) { 11711 // To read the 64-bit time-base register on a 32-bit target, we read the 11712 // two halves. Should the counter have wrapped while it was being read, we 11713 // need to try again. 11714 // ... 11715 // readLoop: 11716 // mfspr Rx,TBU # load from TBU 11717 // mfspr Ry,TB # load from TB 11718 // mfspr Rz,TBU # load from TBU 11719 // cmpw crX,Rx,Rz # check if 'old'='new' 11720 // bne readLoop # branch if they're not equal 11721 // ... 11722 11723 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11724 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11725 DebugLoc dl = MI.getDebugLoc(); 11726 F->insert(It, readMBB); 11727 F->insert(It, sinkMBB); 11728 11729 // Transfer the remainder of BB and its successor edges to sinkMBB. 11730 sinkMBB->splice(sinkMBB->begin(), BB, 11731 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11732 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11733 11734 BB->addSuccessor(readMBB); 11735 BB = readMBB; 11736 11737 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11738 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11739 Register LoReg = MI.getOperand(0).getReg(); 11740 Register HiReg = MI.getOperand(1).getReg(); 11741 11742 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11743 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11744 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11745 11746 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11747 11748 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11749 .addReg(HiReg) 11750 .addReg(ReadAgainReg); 11751 BuildMI(BB, dl, TII->get(PPC::BCC)) 11752 .addImm(PPC::PRED_NE) 11753 .addReg(CmpReg) 11754 .addMBB(readMBB); 11755 11756 BB->addSuccessor(readMBB); 11757 BB->addSuccessor(sinkMBB); 11758 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11759 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11760 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11761 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11762 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11763 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11764 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11765 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11766 11767 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11768 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11769 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11770 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11771 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11772 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11773 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11774 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11775 11776 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11777 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11778 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11779 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11780 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11781 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11783 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11784 11785 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11786 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11787 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11788 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11789 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11790 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11792 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11793 11794 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11795 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11796 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11797 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11798 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11799 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11801 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11802 11803 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11804 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11805 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11806 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11807 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11808 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11810 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11811 11812 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11813 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11814 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11815 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11817 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11819 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11820 11821 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11822 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11824 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11826 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11828 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11829 11830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11831 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11833 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11835 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11837 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11838 11839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11840 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11842 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11844 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11846 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11847 11848 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11849 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11850 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11851 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11852 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11853 BB = EmitAtomicBinary(MI, BB, 4, 0); 11854 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11855 BB = EmitAtomicBinary(MI, BB, 8, 0); 11856 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11857 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11858 (Subtarget.hasPartwordAtomics() && 11859 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11860 (Subtarget.hasPartwordAtomics() && 11861 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11862 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11863 11864 auto LoadMnemonic = PPC::LDARX; 11865 auto StoreMnemonic = PPC::STDCX; 11866 switch (MI.getOpcode()) { 11867 default: 11868 llvm_unreachable("Compare and swap of unknown size"); 11869 case PPC::ATOMIC_CMP_SWAP_I8: 11870 LoadMnemonic = PPC::LBARX; 11871 StoreMnemonic = PPC::STBCX; 11872 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11873 break; 11874 case PPC::ATOMIC_CMP_SWAP_I16: 11875 LoadMnemonic = PPC::LHARX; 11876 StoreMnemonic = PPC::STHCX; 11877 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11878 break; 11879 case PPC::ATOMIC_CMP_SWAP_I32: 11880 LoadMnemonic = PPC::LWARX; 11881 StoreMnemonic = PPC::STWCX; 11882 break; 11883 case PPC::ATOMIC_CMP_SWAP_I64: 11884 LoadMnemonic = PPC::LDARX; 11885 StoreMnemonic = PPC::STDCX; 11886 break; 11887 } 11888 Register dest = MI.getOperand(0).getReg(); 11889 Register ptrA = MI.getOperand(1).getReg(); 11890 Register ptrB = MI.getOperand(2).getReg(); 11891 Register oldval = MI.getOperand(3).getReg(); 11892 Register newval = MI.getOperand(4).getReg(); 11893 DebugLoc dl = MI.getDebugLoc(); 11894 11895 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11896 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11897 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11898 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11899 F->insert(It, loop1MBB); 11900 F->insert(It, loop2MBB); 11901 F->insert(It, midMBB); 11902 F->insert(It, exitMBB); 11903 exitMBB->splice(exitMBB->begin(), BB, 11904 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11905 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11906 11907 // thisMBB: 11908 // ... 11909 // fallthrough --> loopMBB 11910 BB->addSuccessor(loop1MBB); 11911 11912 // loop1MBB: 11913 // l[bhwd]arx dest, ptr 11914 // cmp[wd] dest, oldval 11915 // bne- midMBB 11916 // loop2MBB: 11917 // st[bhwd]cx. newval, ptr 11918 // bne- loopMBB 11919 // b exitBB 11920 // midMBB: 11921 // st[bhwd]cx. dest, ptr 11922 // exitBB: 11923 BB = loop1MBB; 11924 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11925 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11926 .addReg(oldval) 11927 .addReg(dest); 11928 BuildMI(BB, dl, TII->get(PPC::BCC)) 11929 .addImm(PPC::PRED_NE) 11930 .addReg(PPC::CR0) 11931 .addMBB(midMBB); 11932 BB->addSuccessor(loop2MBB); 11933 BB->addSuccessor(midMBB); 11934 11935 BB = loop2MBB; 11936 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11937 .addReg(newval) 11938 .addReg(ptrA) 11939 .addReg(ptrB); 11940 BuildMI(BB, dl, TII->get(PPC::BCC)) 11941 .addImm(PPC::PRED_NE) 11942 .addReg(PPC::CR0) 11943 .addMBB(loop1MBB); 11944 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11945 BB->addSuccessor(loop1MBB); 11946 BB->addSuccessor(exitMBB); 11947 11948 BB = midMBB; 11949 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11950 .addReg(dest) 11951 .addReg(ptrA) 11952 .addReg(ptrB); 11953 BB->addSuccessor(exitMBB); 11954 11955 // exitMBB: 11956 // ... 11957 BB = exitMBB; 11958 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11959 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11960 // We must use 64-bit registers for addresses when targeting 64-bit, 11961 // since we're actually doing arithmetic on them. Other registers 11962 // can be 32-bit. 11963 bool is64bit = Subtarget.isPPC64(); 11964 bool isLittleEndian = Subtarget.isLittleEndian(); 11965 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11966 11967 Register dest = MI.getOperand(0).getReg(); 11968 Register ptrA = MI.getOperand(1).getReg(); 11969 Register ptrB = MI.getOperand(2).getReg(); 11970 Register oldval = MI.getOperand(3).getReg(); 11971 Register newval = MI.getOperand(4).getReg(); 11972 DebugLoc dl = MI.getDebugLoc(); 11973 11974 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11975 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11976 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11977 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11978 F->insert(It, loop1MBB); 11979 F->insert(It, loop2MBB); 11980 F->insert(It, midMBB); 11981 F->insert(It, exitMBB); 11982 exitMBB->splice(exitMBB->begin(), BB, 11983 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11984 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11985 11986 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11987 const TargetRegisterClass *RC = 11988 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11989 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11990 11991 Register PtrReg = RegInfo.createVirtualRegister(RC); 11992 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11993 Register ShiftReg = 11994 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11995 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11996 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11997 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11998 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11999 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12000 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12001 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12002 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12003 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12004 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12005 Register Ptr1Reg; 12006 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12007 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12008 // thisMBB: 12009 // ... 12010 // fallthrough --> loopMBB 12011 BB->addSuccessor(loop1MBB); 12012 12013 // The 4-byte load must be aligned, while a char or short may be 12014 // anywhere in the word. Hence all this nasty bookkeeping code. 12015 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12016 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12017 // xori shift, shift1, 24 [16] 12018 // rlwinm ptr, ptr1, 0, 0, 29 12019 // slw newval2, newval, shift 12020 // slw oldval2, oldval,shift 12021 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12022 // slw mask, mask2, shift 12023 // and newval3, newval2, mask 12024 // and oldval3, oldval2, mask 12025 // loop1MBB: 12026 // lwarx tmpDest, ptr 12027 // and tmp, tmpDest, mask 12028 // cmpw tmp, oldval3 12029 // bne- midMBB 12030 // loop2MBB: 12031 // andc tmp2, tmpDest, mask 12032 // or tmp4, tmp2, newval3 12033 // stwcx. tmp4, ptr 12034 // bne- loop1MBB 12035 // b exitBB 12036 // midMBB: 12037 // stwcx. tmpDest, ptr 12038 // exitBB: 12039 // srw dest, tmpDest, shift 12040 if (ptrA != ZeroReg) { 12041 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12042 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12043 .addReg(ptrA) 12044 .addReg(ptrB); 12045 } else { 12046 Ptr1Reg = ptrB; 12047 } 12048 12049 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12050 // mode. 12051 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12052 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12053 .addImm(3) 12054 .addImm(27) 12055 .addImm(is8bit ? 28 : 27); 12056 if (!isLittleEndian) 12057 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12058 .addReg(Shift1Reg) 12059 .addImm(is8bit ? 24 : 16); 12060 if (is64bit) 12061 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12062 .addReg(Ptr1Reg) 12063 .addImm(0) 12064 .addImm(61); 12065 else 12066 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12067 .addReg(Ptr1Reg) 12068 .addImm(0) 12069 .addImm(0) 12070 .addImm(29); 12071 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12072 .addReg(newval) 12073 .addReg(ShiftReg); 12074 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12075 .addReg(oldval) 12076 .addReg(ShiftReg); 12077 if (is8bit) 12078 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12079 else { 12080 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12081 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12082 .addReg(Mask3Reg) 12083 .addImm(65535); 12084 } 12085 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12086 .addReg(Mask2Reg) 12087 .addReg(ShiftReg); 12088 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12089 .addReg(NewVal2Reg) 12090 .addReg(MaskReg); 12091 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12092 .addReg(OldVal2Reg) 12093 .addReg(MaskReg); 12094 12095 BB = loop1MBB; 12096 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12097 .addReg(ZeroReg) 12098 .addReg(PtrReg); 12099 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12100 .addReg(TmpDestReg) 12101 .addReg(MaskReg); 12102 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12103 .addReg(TmpReg) 12104 .addReg(OldVal3Reg); 12105 BuildMI(BB, dl, TII->get(PPC::BCC)) 12106 .addImm(PPC::PRED_NE) 12107 .addReg(PPC::CR0) 12108 .addMBB(midMBB); 12109 BB->addSuccessor(loop2MBB); 12110 BB->addSuccessor(midMBB); 12111 12112 BB = loop2MBB; 12113 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12114 .addReg(TmpDestReg) 12115 .addReg(MaskReg); 12116 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12117 .addReg(Tmp2Reg) 12118 .addReg(NewVal3Reg); 12119 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12120 .addReg(Tmp4Reg) 12121 .addReg(ZeroReg) 12122 .addReg(PtrReg); 12123 BuildMI(BB, dl, TII->get(PPC::BCC)) 12124 .addImm(PPC::PRED_NE) 12125 .addReg(PPC::CR0) 12126 .addMBB(loop1MBB); 12127 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12128 BB->addSuccessor(loop1MBB); 12129 BB->addSuccessor(exitMBB); 12130 12131 BB = midMBB; 12132 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12133 .addReg(TmpDestReg) 12134 .addReg(ZeroReg) 12135 .addReg(PtrReg); 12136 BB->addSuccessor(exitMBB); 12137 12138 // exitMBB: 12139 // ... 12140 BB = exitMBB; 12141 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12142 .addReg(TmpReg) 12143 .addReg(ShiftReg); 12144 } else if (MI.getOpcode() == PPC::FADDrtz) { 12145 // This pseudo performs an FADD with rounding mode temporarily forced 12146 // to round-to-zero. We emit this via custom inserter since the FPSCR 12147 // is not modeled at the SelectionDAG level. 12148 Register Dest = MI.getOperand(0).getReg(); 12149 Register Src1 = MI.getOperand(1).getReg(); 12150 Register Src2 = MI.getOperand(2).getReg(); 12151 DebugLoc dl = MI.getDebugLoc(); 12152 12153 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12154 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12155 12156 // Save FPSCR value. 12157 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12158 12159 // Set rounding mode to round-to-zero. 12160 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12161 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12162 12163 // Perform addition. 12164 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12165 12166 // Restore FPSCR value. 12167 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12168 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12169 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12170 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12171 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12172 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12173 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12174 ? PPC::ANDI8_rec 12175 : PPC::ANDI_rec; 12176 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12177 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12178 12179 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12180 Register Dest = RegInfo.createVirtualRegister( 12181 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12182 12183 DebugLoc Dl = MI.getDebugLoc(); 12184 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12185 .addReg(MI.getOperand(1).getReg()) 12186 .addImm(1); 12187 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12188 MI.getOperand(0).getReg()) 12189 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12190 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12191 DebugLoc Dl = MI.getDebugLoc(); 12192 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12193 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12194 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12195 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12196 MI.getOperand(0).getReg()) 12197 .addReg(CRReg); 12198 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12199 DebugLoc Dl = MI.getDebugLoc(); 12200 unsigned Imm = MI.getOperand(1).getImm(); 12201 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12202 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12203 MI.getOperand(0).getReg()) 12204 .addReg(PPC::CR0EQ); 12205 } else if (MI.getOpcode() == PPC::SETRNDi) { 12206 DebugLoc dl = MI.getDebugLoc(); 12207 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12208 12209 // Save FPSCR value. 12210 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12211 12212 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12213 // the following settings: 12214 // 00 Round to nearest 12215 // 01 Round to 0 12216 // 10 Round to +inf 12217 // 11 Round to -inf 12218 12219 // When the operand is immediate, using the two least significant bits of 12220 // the immediate to set the bits 62:63 of FPSCR. 12221 unsigned Mode = MI.getOperand(1).getImm(); 12222 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12223 .addImm(31); 12224 12225 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12226 .addImm(30); 12227 } else if (MI.getOpcode() == PPC::SETRND) { 12228 DebugLoc dl = MI.getDebugLoc(); 12229 12230 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12231 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12232 // If the target doesn't have DirectMove, we should use stack to do the 12233 // conversion, because the target doesn't have the instructions like mtvsrd 12234 // or mfvsrd to do this conversion directly. 12235 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12236 if (Subtarget.hasDirectMove()) { 12237 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12238 .addReg(SrcReg); 12239 } else { 12240 // Use stack to do the register copy. 12241 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12242 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12243 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12244 if (RC == &PPC::F8RCRegClass) { 12245 // Copy register from F8RCRegClass to G8RCRegclass. 12246 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12247 "Unsupported RegClass."); 12248 12249 StoreOp = PPC::STFD; 12250 LoadOp = PPC::LD; 12251 } else { 12252 // Copy register from G8RCRegClass to F8RCRegclass. 12253 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12254 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12255 "Unsupported RegClass."); 12256 } 12257 12258 MachineFrameInfo &MFI = F->getFrameInfo(); 12259 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12260 12261 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12262 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12263 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12264 MFI.getObjectAlign(FrameIdx)); 12265 12266 // Store the SrcReg into the stack. 12267 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12268 .addReg(SrcReg) 12269 .addImm(0) 12270 .addFrameIndex(FrameIdx) 12271 .addMemOperand(MMOStore); 12272 12273 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12274 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12275 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12276 MFI.getObjectAlign(FrameIdx)); 12277 12278 // Load from the stack where SrcReg is stored, and save to DestReg, 12279 // so we have done the RegClass conversion from RegClass::SrcReg to 12280 // RegClass::DestReg. 12281 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12282 .addImm(0) 12283 .addFrameIndex(FrameIdx) 12284 .addMemOperand(MMOLoad); 12285 } 12286 }; 12287 12288 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12289 12290 // Save FPSCR value. 12291 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12292 12293 // When the operand is gprc register, use two least significant bits of the 12294 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12295 // 12296 // copy OldFPSCRTmpReg, OldFPSCRReg 12297 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12298 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12299 // copy NewFPSCRReg, NewFPSCRTmpReg 12300 // mtfsf 255, NewFPSCRReg 12301 MachineOperand SrcOp = MI.getOperand(1); 12302 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12303 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12304 12305 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12306 12307 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12308 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12309 12310 // The first operand of INSERT_SUBREG should be a register which has 12311 // subregisters, we only care about its RegClass, so we should use an 12312 // IMPLICIT_DEF register. 12313 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12314 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12315 .addReg(ImDefReg) 12316 .add(SrcOp) 12317 .addImm(1); 12318 12319 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12320 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12321 .addReg(OldFPSCRTmpReg) 12322 .addReg(ExtSrcReg) 12323 .addImm(0) 12324 .addImm(62); 12325 12326 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12327 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12328 12329 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12330 // bits of FPSCR. 12331 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12332 .addImm(255) 12333 .addReg(NewFPSCRReg) 12334 .addImm(0) 12335 .addImm(0); 12336 } else { 12337 llvm_unreachable("Unexpected instr type to insert"); 12338 } 12339 12340 MI.eraseFromParent(); // The pseudo instruction is gone now. 12341 return BB; 12342 } 12343 12344 //===----------------------------------------------------------------------===// 12345 // Target Optimization Hooks 12346 //===----------------------------------------------------------------------===// 12347 12348 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12349 // For the estimates, convergence is quadratic, so we essentially double the 12350 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12351 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12352 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12353 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12354 if (VT.getScalarType() == MVT::f64) 12355 RefinementSteps++; 12356 return RefinementSteps; 12357 } 12358 12359 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12360 int Enabled, int &RefinementSteps, 12361 bool &UseOneConstNR, 12362 bool Reciprocal) const { 12363 EVT VT = Operand.getValueType(); 12364 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12365 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12366 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12367 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12368 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12369 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12370 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12371 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12372 12373 // The Newton-Raphson computation with a single constant does not provide 12374 // enough accuracy on some CPUs. 12375 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12376 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12377 } 12378 return SDValue(); 12379 } 12380 12381 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12382 int Enabled, 12383 int &RefinementSteps) const { 12384 EVT VT = Operand.getValueType(); 12385 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12386 (VT == MVT::f64 && Subtarget.hasFRE()) || 12387 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12388 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12389 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12390 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12391 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12392 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12393 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12394 } 12395 return SDValue(); 12396 } 12397 12398 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12399 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12400 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12401 // enabled for division), this functionality is redundant with the default 12402 // combiner logic (once the division -> reciprocal/multiply transformation 12403 // has taken place). As a result, this matters more for older cores than for 12404 // newer ones. 12405 12406 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12407 // reciprocal if there are two or more FDIVs (for embedded cores with only 12408 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12409 switch (Subtarget.getCPUDirective()) { 12410 default: 12411 return 3; 12412 case PPC::DIR_440: 12413 case PPC::DIR_A2: 12414 case PPC::DIR_E500: 12415 case PPC::DIR_E500mc: 12416 case PPC::DIR_E5500: 12417 return 2; 12418 } 12419 } 12420 12421 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12422 // collapsed, and so we need to look through chains of them. 12423 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12424 int64_t& Offset, SelectionDAG &DAG) { 12425 if (DAG.isBaseWithConstantOffset(Loc)) { 12426 Base = Loc.getOperand(0); 12427 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12428 12429 // The base might itself be a base plus an offset, and if so, accumulate 12430 // that as well. 12431 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12432 } 12433 } 12434 12435 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12436 unsigned Bytes, int Dist, 12437 SelectionDAG &DAG) { 12438 if (VT.getSizeInBits() / 8 != Bytes) 12439 return false; 12440 12441 SDValue BaseLoc = Base->getBasePtr(); 12442 if (Loc.getOpcode() == ISD::FrameIndex) { 12443 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12444 return false; 12445 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12446 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12447 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12448 int FS = MFI.getObjectSize(FI); 12449 int BFS = MFI.getObjectSize(BFI); 12450 if (FS != BFS || FS != (int)Bytes) return false; 12451 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12452 } 12453 12454 SDValue Base1 = Loc, Base2 = BaseLoc; 12455 int64_t Offset1 = 0, Offset2 = 0; 12456 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12457 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12458 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12459 return true; 12460 12461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12462 const GlobalValue *GV1 = nullptr; 12463 const GlobalValue *GV2 = nullptr; 12464 Offset1 = 0; 12465 Offset2 = 0; 12466 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12467 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12468 if (isGA1 && isGA2 && GV1 == GV2) 12469 return Offset1 == (Offset2 + Dist*Bytes); 12470 return false; 12471 } 12472 12473 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12474 // not enforce equality of the chain operands. 12475 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12476 unsigned Bytes, int Dist, 12477 SelectionDAG &DAG) { 12478 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12479 EVT VT = LS->getMemoryVT(); 12480 SDValue Loc = LS->getBasePtr(); 12481 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12482 } 12483 12484 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12485 EVT VT; 12486 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12487 default: return false; 12488 case Intrinsic::ppc_qpx_qvlfd: 12489 case Intrinsic::ppc_qpx_qvlfda: 12490 VT = MVT::v4f64; 12491 break; 12492 case Intrinsic::ppc_qpx_qvlfs: 12493 case Intrinsic::ppc_qpx_qvlfsa: 12494 VT = MVT::v4f32; 12495 break; 12496 case Intrinsic::ppc_qpx_qvlfcd: 12497 case Intrinsic::ppc_qpx_qvlfcda: 12498 VT = MVT::v2f64; 12499 break; 12500 case Intrinsic::ppc_qpx_qvlfcs: 12501 case Intrinsic::ppc_qpx_qvlfcsa: 12502 VT = MVT::v2f32; 12503 break; 12504 case Intrinsic::ppc_qpx_qvlfiwa: 12505 case Intrinsic::ppc_qpx_qvlfiwz: 12506 case Intrinsic::ppc_altivec_lvx: 12507 case Intrinsic::ppc_altivec_lvxl: 12508 case Intrinsic::ppc_vsx_lxvw4x: 12509 case Intrinsic::ppc_vsx_lxvw4x_be: 12510 VT = MVT::v4i32; 12511 break; 12512 case Intrinsic::ppc_vsx_lxvd2x: 12513 case Intrinsic::ppc_vsx_lxvd2x_be: 12514 VT = MVT::v2f64; 12515 break; 12516 case Intrinsic::ppc_altivec_lvebx: 12517 VT = MVT::i8; 12518 break; 12519 case Intrinsic::ppc_altivec_lvehx: 12520 VT = MVT::i16; 12521 break; 12522 case Intrinsic::ppc_altivec_lvewx: 12523 VT = MVT::i32; 12524 break; 12525 } 12526 12527 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12528 } 12529 12530 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12531 EVT VT; 12532 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12533 default: return false; 12534 case Intrinsic::ppc_qpx_qvstfd: 12535 case Intrinsic::ppc_qpx_qvstfda: 12536 VT = MVT::v4f64; 12537 break; 12538 case Intrinsic::ppc_qpx_qvstfs: 12539 case Intrinsic::ppc_qpx_qvstfsa: 12540 VT = MVT::v4f32; 12541 break; 12542 case Intrinsic::ppc_qpx_qvstfcd: 12543 case Intrinsic::ppc_qpx_qvstfcda: 12544 VT = MVT::v2f64; 12545 break; 12546 case Intrinsic::ppc_qpx_qvstfcs: 12547 case Intrinsic::ppc_qpx_qvstfcsa: 12548 VT = MVT::v2f32; 12549 break; 12550 case Intrinsic::ppc_qpx_qvstfiw: 12551 case Intrinsic::ppc_qpx_qvstfiwa: 12552 case Intrinsic::ppc_altivec_stvx: 12553 case Intrinsic::ppc_altivec_stvxl: 12554 case Intrinsic::ppc_vsx_stxvw4x: 12555 VT = MVT::v4i32; 12556 break; 12557 case Intrinsic::ppc_vsx_stxvd2x: 12558 VT = MVT::v2f64; 12559 break; 12560 case Intrinsic::ppc_vsx_stxvw4x_be: 12561 VT = MVT::v4i32; 12562 break; 12563 case Intrinsic::ppc_vsx_stxvd2x_be: 12564 VT = MVT::v2f64; 12565 break; 12566 case Intrinsic::ppc_altivec_stvebx: 12567 VT = MVT::i8; 12568 break; 12569 case Intrinsic::ppc_altivec_stvehx: 12570 VT = MVT::i16; 12571 break; 12572 case Intrinsic::ppc_altivec_stvewx: 12573 VT = MVT::i32; 12574 break; 12575 } 12576 12577 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12578 } 12579 12580 return false; 12581 } 12582 12583 // Return true is there is a nearyby consecutive load to the one provided 12584 // (regardless of alignment). We search up and down the chain, looking though 12585 // token factors and other loads (but nothing else). As a result, a true result 12586 // indicates that it is safe to create a new consecutive load adjacent to the 12587 // load provided. 12588 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12589 SDValue Chain = LD->getChain(); 12590 EVT VT = LD->getMemoryVT(); 12591 12592 SmallSet<SDNode *, 16> LoadRoots; 12593 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12594 SmallSet<SDNode *, 16> Visited; 12595 12596 // First, search up the chain, branching to follow all token-factor operands. 12597 // If we find a consecutive load, then we're done, otherwise, record all 12598 // nodes just above the top-level loads and token factors. 12599 while (!Queue.empty()) { 12600 SDNode *ChainNext = Queue.pop_back_val(); 12601 if (!Visited.insert(ChainNext).second) 12602 continue; 12603 12604 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12605 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12606 return true; 12607 12608 if (!Visited.count(ChainLD->getChain().getNode())) 12609 Queue.push_back(ChainLD->getChain().getNode()); 12610 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12611 for (const SDUse &O : ChainNext->ops()) 12612 if (!Visited.count(O.getNode())) 12613 Queue.push_back(O.getNode()); 12614 } else 12615 LoadRoots.insert(ChainNext); 12616 } 12617 12618 // Second, search down the chain, starting from the top-level nodes recorded 12619 // in the first phase. These top-level nodes are the nodes just above all 12620 // loads and token factors. Starting with their uses, recursively look though 12621 // all loads (just the chain uses) and token factors to find a consecutive 12622 // load. 12623 Visited.clear(); 12624 Queue.clear(); 12625 12626 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12627 IE = LoadRoots.end(); I != IE; ++I) { 12628 Queue.push_back(*I); 12629 12630 while (!Queue.empty()) { 12631 SDNode *LoadRoot = Queue.pop_back_val(); 12632 if (!Visited.insert(LoadRoot).second) 12633 continue; 12634 12635 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12636 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12637 return true; 12638 12639 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12640 UE = LoadRoot->use_end(); UI != UE; ++UI) 12641 if (((isa<MemSDNode>(*UI) && 12642 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12643 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12644 Queue.push_back(*UI); 12645 } 12646 } 12647 12648 return false; 12649 } 12650 12651 /// This function is called when we have proved that a SETCC node can be replaced 12652 /// by subtraction (and other supporting instructions) so that the result of 12653 /// comparison is kept in a GPR instead of CR. This function is purely for 12654 /// codegen purposes and has some flags to guide the codegen process. 12655 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12656 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12657 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12658 12659 // Zero extend the operands to the largest legal integer. Originally, they 12660 // must be of a strictly smaller size. 12661 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12662 DAG.getConstant(Size, DL, MVT::i32)); 12663 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12664 DAG.getConstant(Size, DL, MVT::i32)); 12665 12666 // Swap if needed. Depends on the condition code. 12667 if (Swap) 12668 std::swap(Op0, Op1); 12669 12670 // Subtract extended integers. 12671 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12672 12673 // Move the sign bit to the least significant position and zero out the rest. 12674 // Now the least significant bit carries the result of original comparison. 12675 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12676 DAG.getConstant(Size - 1, DL, MVT::i32)); 12677 auto Final = Shifted; 12678 12679 // Complement the result if needed. Based on the condition code. 12680 if (Complement) 12681 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12682 DAG.getConstant(1, DL, MVT::i64)); 12683 12684 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12685 } 12686 12687 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12688 DAGCombinerInfo &DCI) const { 12689 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12690 12691 SelectionDAG &DAG = DCI.DAG; 12692 SDLoc DL(N); 12693 12694 // Size of integers being compared has a critical role in the following 12695 // analysis, so we prefer to do this when all types are legal. 12696 if (!DCI.isAfterLegalizeDAG()) 12697 return SDValue(); 12698 12699 // If all users of SETCC extend its value to a legal integer type 12700 // then we replace SETCC with a subtraction 12701 for (SDNode::use_iterator UI = N->use_begin(), 12702 UE = N->use_end(); UI != UE; ++UI) { 12703 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12704 return SDValue(); 12705 } 12706 12707 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12708 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12709 12710 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12711 12712 if (OpSize < Size) { 12713 switch (CC) { 12714 default: break; 12715 case ISD::SETULT: 12716 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12717 case ISD::SETULE: 12718 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12719 case ISD::SETUGT: 12720 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12721 case ISD::SETUGE: 12722 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12723 } 12724 } 12725 12726 return SDValue(); 12727 } 12728 12729 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12730 DAGCombinerInfo &DCI) const { 12731 SelectionDAG &DAG = DCI.DAG; 12732 SDLoc dl(N); 12733 12734 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12735 // If we're tracking CR bits, we need to be careful that we don't have: 12736 // trunc(binary-ops(zext(x), zext(y))) 12737 // or 12738 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12739 // such that we're unnecessarily moving things into GPRs when it would be 12740 // better to keep them in CR bits. 12741 12742 // Note that trunc here can be an actual i1 trunc, or can be the effective 12743 // truncation that comes from a setcc or select_cc. 12744 if (N->getOpcode() == ISD::TRUNCATE && 12745 N->getValueType(0) != MVT::i1) 12746 return SDValue(); 12747 12748 if (N->getOperand(0).getValueType() != MVT::i32 && 12749 N->getOperand(0).getValueType() != MVT::i64) 12750 return SDValue(); 12751 12752 if (N->getOpcode() == ISD::SETCC || 12753 N->getOpcode() == ISD::SELECT_CC) { 12754 // If we're looking at a comparison, then we need to make sure that the 12755 // high bits (all except for the first) don't matter the result. 12756 ISD::CondCode CC = 12757 cast<CondCodeSDNode>(N->getOperand( 12758 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12759 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12760 12761 if (ISD::isSignedIntSetCC(CC)) { 12762 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12763 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12764 return SDValue(); 12765 } else if (ISD::isUnsignedIntSetCC(CC)) { 12766 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12767 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12768 !DAG.MaskedValueIsZero(N->getOperand(1), 12769 APInt::getHighBitsSet(OpBits, OpBits-1))) 12770 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12771 : SDValue()); 12772 } else { 12773 // This is neither a signed nor an unsigned comparison, just make sure 12774 // that the high bits are equal. 12775 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12776 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12777 12778 // We don't really care about what is known about the first bit (if 12779 // anything), so clear it in all masks prior to comparing them. 12780 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12781 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12782 12783 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12784 return SDValue(); 12785 } 12786 } 12787 12788 // We now know that the higher-order bits are irrelevant, we just need to 12789 // make sure that all of the intermediate operations are bit operations, and 12790 // all inputs are extensions. 12791 if (N->getOperand(0).getOpcode() != ISD::AND && 12792 N->getOperand(0).getOpcode() != ISD::OR && 12793 N->getOperand(0).getOpcode() != ISD::XOR && 12794 N->getOperand(0).getOpcode() != ISD::SELECT && 12795 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12796 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12797 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12798 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12799 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12800 return SDValue(); 12801 12802 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12803 N->getOperand(1).getOpcode() != ISD::AND && 12804 N->getOperand(1).getOpcode() != ISD::OR && 12805 N->getOperand(1).getOpcode() != ISD::XOR && 12806 N->getOperand(1).getOpcode() != ISD::SELECT && 12807 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12808 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12809 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12810 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12811 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12812 return SDValue(); 12813 12814 SmallVector<SDValue, 4> Inputs; 12815 SmallVector<SDValue, 8> BinOps, PromOps; 12816 SmallPtrSet<SDNode *, 16> Visited; 12817 12818 for (unsigned i = 0; i < 2; ++i) { 12819 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12820 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12821 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12822 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12823 isa<ConstantSDNode>(N->getOperand(i))) 12824 Inputs.push_back(N->getOperand(i)); 12825 else 12826 BinOps.push_back(N->getOperand(i)); 12827 12828 if (N->getOpcode() == ISD::TRUNCATE) 12829 break; 12830 } 12831 12832 // Visit all inputs, collect all binary operations (and, or, xor and 12833 // select) that are all fed by extensions. 12834 while (!BinOps.empty()) { 12835 SDValue BinOp = BinOps.back(); 12836 BinOps.pop_back(); 12837 12838 if (!Visited.insert(BinOp.getNode()).second) 12839 continue; 12840 12841 PromOps.push_back(BinOp); 12842 12843 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12844 // The condition of the select is not promoted. 12845 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12846 continue; 12847 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12848 continue; 12849 12850 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12851 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12852 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12853 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12854 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12855 Inputs.push_back(BinOp.getOperand(i)); 12856 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12857 BinOp.getOperand(i).getOpcode() == ISD::OR || 12858 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12859 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12860 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12861 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12862 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12863 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12864 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12865 BinOps.push_back(BinOp.getOperand(i)); 12866 } else { 12867 // We have an input that is not an extension or another binary 12868 // operation; we'll abort this transformation. 12869 return SDValue(); 12870 } 12871 } 12872 } 12873 12874 // Make sure that this is a self-contained cluster of operations (which 12875 // is not quite the same thing as saying that everything has only one 12876 // use). 12877 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12878 if (isa<ConstantSDNode>(Inputs[i])) 12879 continue; 12880 12881 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12882 UE = Inputs[i].getNode()->use_end(); 12883 UI != UE; ++UI) { 12884 SDNode *User = *UI; 12885 if (User != N && !Visited.count(User)) 12886 return SDValue(); 12887 12888 // Make sure that we're not going to promote the non-output-value 12889 // operand(s) or SELECT or SELECT_CC. 12890 // FIXME: Although we could sometimes handle this, and it does occur in 12891 // practice that one of the condition inputs to the select is also one of 12892 // the outputs, we currently can't deal with this. 12893 if (User->getOpcode() == ISD::SELECT) { 12894 if (User->getOperand(0) == Inputs[i]) 12895 return SDValue(); 12896 } else if (User->getOpcode() == ISD::SELECT_CC) { 12897 if (User->getOperand(0) == Inputs[i] || 12898 User->getOperand(1) == Inputs[i]) 12899 return SDValue(); 12900 } 12901 } 12902 } 12903 12904 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12905 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12906 UE = PromOps[i].getNode()->use_end(); 12907 UI != UE; ++UI) { 12908 SDNode *User = *UI; 12909 if (User != N && !Visited.count(User)) 12910 return SDValue(); 12911 12912 // Make sure that we're not going to promote the non-output-value 12913 // operand(s) or SELECT or SELECT_CC. 12914 // FIXME: Although we could sometimes handle this, and it does occur in 12915 // practice that one of the condition inputs to the select is also one of 12916 // the outputs, we currently can't deal with this. 12917 if (User->getOpcode() == ISD::SELECT) { 12918 if (User->getOperand(0) == PromOps[i]) 12919 return SDValue(); 12920 } else if (User->getOpcode() == ISD::SELECT_CC) { 12921 if (User->getOperand(0) == PromOps[i] || 12922 User->getOperand(1) == PromOps[i]) 12923 return SDValue(); 12924 } 12925 } 12926 } 12927 12928 // Replace all inputs with the extension operand. 12929 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12930 // Constants may have users outside the cluster of to-be-promoted nodes, 12931 // and so we need to replace those as we do the promotions. 12932 if (isa<ConstantSDNode>(Inputs[i])) 12933 continue; 12934 else 12935 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12936 } 12937 12938 std::list<HandleSDNode> PromOpHandles; 12939 for (auto &PromOp : PromOps) 12940 PromOpHandles.emplace_back(PromOp); 12941 12942 // Replace all operations (these are all the same, but have a different 12943 // (i1) return type). DAG.getNode will validate that the types of 12944 // a binary operator match, so go through the list in reverse so that 12945 // we've likely promoted both operands first. Any intermediate truncations or 12946 // extensions disappear. 12947 while (!PromOpHandles.empty()) { 12948 SDValue PromOp = PromOpHandles.back().getValue(); 12949 PromOpHandles.pop_back(); 12950 12951 if (PromOp.getOpcode() == ISD::TRUNCATE || 12952 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12953 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12954 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12955 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12956 PromOp.getOperand(0).getValueType() != MVT::i1) { 12957 // The operand is not yet ready (see comment below). 12958 PromOpHandles.emplace_front(PromOp); 12959 continue; 12960 } 12961 12962 SDValue RepValue = PromOp.getOperand(0); 12963 if (isa<ConstantSDNode>(RepValue)) 12964 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12965 12966 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12967 continue; 12968 } 12969 12970 unsigned C; 12971 switch (PromOp.getOpcode()) { 12972 default: C = 0; break; 12973 case ISD::SELECT: C = 1; break; 12974 case ISD::SELECT_CC: C = 2; break; 12975 } 12976 12977 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12978 PromOp.getOperand(C).getValueType() != MVT::i1) || 12979 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12980 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12981 // The to-be-promoted operands of this node have not yet been 12982 // promoted (this should be rare because we're going through the 12983 // list backward, but if one of the operands has several users in 12984 // this cluster of to-be-promoted nodes, it is possible). 12985 PromOpHandles.emplace_front(PromOp); 12986 continue; 12987 } 12988 12989 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12990 PromOp.getNode()->op_end()); 12991 12992 // If there are any constant inputs, make sure they're replaced now. 12993 for (unsigned i = 0; i < 2; ++i) 12994 if (isa<ConstantSDNode>(Ops[C+i])) 12995 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12996 12997 DAG.ReplaceAllUsesOfValueWith(PromOp, 12998 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12999 } 13000 13001 // Now we're left with the initial truncation itself. 13002 if (N->getOpcode() == ISD::TRUNCATE) 13003 return N->getOperand(0); 13004 13005 // Otherwise, this is a comparison. The operands to be compared have just 13006 // changed type (to i1), but everything else is the same. 13007 return SDValue(N, 0); 13008 } 13009 13010 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13011 DAGCombinerInfo &DCI) const { 13012 SelectionDAG &DAG = DCI.DAG; 13013 SDLoc dl(N); 13014 13015 // If we're tracking CR bits, we need to be careful that we don't have: 13016 // zext(binary-ops(trunc(x), trunc(y))) 13017 // or 13018 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13019 // such that we're unnecessarily moving things into CR bits that can more 13020 // efficiently stay in GPRs. Note that if we're not certain that the high 13021 // bits are set as required by the final extension, we still may need to do 13022 // some masking to get the proper behavior. 13023 13024 // This same functionality is important on PPC64 when dealing with 13025 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13026 // the return values of functions. Because it is so similar, it is handled 13027 // here as well. 13028 13029 if (N->getValueType(0) != MVT::i32 && 13030 N->getValueType(0) != MVT::i64) 13031 return SDValue(); 13032 13033 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13034 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13035 return SDValue(); 13036 13037 if (N->getOperand(0).getOpcode() != ISD::AND && 13038 N->getOperand(0).getOpcode() != ISD::OR && 13039 N->getOperand(0).getOpcode() != ISD::XOR && 13040 N->getOperand(0).getOpcode() != ISD::SELECT && 13041 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13042 return SDValue(); 13043 13044 SmallVector<SDValue, 4> Inputs; 13045 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13046 SmallPtrSet<SDNode *, 16> Visited; 13047 13048 // Visit all inputs, collect all binary operations (and, or, xor and 13049 // select) that are all fed by truncations. 13050 while (!BinOps.empty()) { 13051 SDValue BinOp = BinOps.back(); 13052 BinOps.pop_back(); 13053 13054 if (!Visited.insert(BinOp.getNode()).second) 13055 continue; 13056 13057 PromOps.push_back(BinOp); 13058 13059 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13060 // The condition of the select is not promoted. 13061 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13062 continue; 13063 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13064 continue; 13065 13066 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13067 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13068 Inputs.push_back(BinOp.getOperand(i)); 13069 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13070 BinOp.getOperand(i).getOpcode() == ISD::OR || 13071 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13072 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13073 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13074 BinOps.push_back(BinOp.getOperand(i)); 13075 } else { 13076 // We have an input that is not a truncation or another binary 13077 // operation; we'll abort this transformation. 13078 return SDValue(); 13079 } 13080 } 13081 } 13082 13083 // The operands of a select that must be truncated when the select is 13084 // promoted because the operand is actually part of the to-be-promoted set. 13085 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13086 13087 // Make sure that this is a self-contained cluster of operations (which 13088 // is not quite the same thing as saying that everything has only one 13089 // use). 13090 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13091 if (isa<ConstantSDNode>(Inputs[i])) 13092 continue; 13093 13094 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13095 UE = Inputs[i].getNode()->use_end(); 13096 UI != UE; ++UI) { 13097 SDNode *User = *UI; 13098 if (User != N && !Visited.count(User)) 13099 return SDValue(); 13100 13101 // If we're going to promote the non-output-value operand(s) or SELECT or 13102 // SELECT_CC, record them for truncation. 13103 if (User->getOpcode() == ISD::SELECT) { 13104 if (User->getOperand(0) == Inputs[i]) 13105 SelectTruncOp[0].insert(std::make_pair(User, 13106 User->getOperand(0).getValueType())); 13107 } else if (User->getOpcode() == ISD::SELECT_CC) { 13108 if (User->getOperand(0) == Inputs[i]) 13109 SelectTruncOp[0].insert(std::make_pair(User, 13110 User->getOperand(0).getValueType())); 13111 if (User->getOperand(1) == Inputs[i]) 13112 SelectTruncOp[1].insert(std::make_pair(User, 13113 User->getOperand(1).getValueType())); 13114 } 13115 } 13116 } 13117 13118 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13119 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13120 UE = PromOps[i].getNode()->use_end(); 13121 UI != UE; ++UI) { 13122 SDNode *User = *UI; 13123 if (User != N && !Visited.count(User)) 13124 return SDValue(); 13125 13126 // If we're going to promote the non-output-value operand(s) or SELECT or 13127 // SELECT_CC, record them for truncation. 13128 if (User->getOpcode() == ISD::SELECT) { 13129 if (User->getOperand(0) == PromOps[i]) 13130 SelectTruncOp[0].insert(std::make_pair(User, 13131 User->getOperand(0).getValueType())); 13132 } else if (User->getOpcode() == ISD::SELECT_CC) { 13133 if (User->getOperand(0) == PromOps[i]) 13134 SelectTruncOp[0].insert(std::make_pair(User, 13135 User->getOperand(0).getValueType())); 13136 if (User->getOperand(1) == PromOps[i]) 13137 SelectTruncOp[1].insert(std::make_pair(User, 13138 User->getOperand(1).getValueType())); 13139 } 13140 } 13141 } 13142 13143 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13144 bool ReallyNeedsExt = false; 13145 if (N->getOpcode() != ISD::ANY_EXTEND) { 13146 // If all of the inputs are not already sign/zero extended, then 13147 // we'll still need to do that at the end. 13148 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13149 if (isa<ConstantSDNode>(Inputs[i])) 13150 continue; 13151 13152 unsigned OpBits = 13153 Inputs[i].getOperand(0).getValueSizeInBits(); 13154 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13155 13156 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13157 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13158 APInt::getHighBitsSet(OpBits, 13159 OpBits-PromBits))) || 13160 (N->getOpcode() == ISD::SIGN_EXTEND && 13161 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13162 (OpBits-(PromBits-1)))) { 13163 ReallyNeedsExt = true; 13164 break; 13165 } 13166 } 13167 } 13168 13169 // Replace all inputs, either with the truncation operand, or a 13170 // truncation or extension to the final output type. 13171 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13172 // Constant inputs need to be replaced with the to-be-promoted nodes that 13173 // use them because they might have users outside of the cluster of 13174 // promoted nodes. 13175 if (isa<ConstantSDNode>(Inputs[i])) 13176 continue; 13177 13178 SDValue InSrc = Inputs[i].getOperand(0); 13179 if (Inputs[i].getValueType() == N->getValueType(0)) 13180 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13181 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13182 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13183 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13184 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13185 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13186 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13187 else 13188 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13189 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13190 } 13191 13192 std::list<HandleSDNode> PromOpHandles; 13193 for (auto &PromOp : PromOps) 13194 PromOpHandles.emplace_back(PromOp); 13195 13196 // Replace all operations (these are all the same, but have a different 13197 // (promoted) return type). DAG.getNode will validate that the types of 13198 // a binary operator match, so go through the list in reverse so that 13199 // we've likely promoted both operands first. 13200 while (!PromOpHandles.empty()) { 13201 SDValue PromOp = PromOpHandles.back().getValue(); 13202 PromOpHandles.pop_back(); 13203 13204 unsigned C; 13205 switch (PromOp.getOpcode()) { 13206 default: C = 0; break; 13207 case ISD::SELECT: C = 1; break; 13208 case ISD::SELECT_CC: C = 2; break; 13209 } 13210 13211 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13212 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13213 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13214 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13215 // The to-be-promoted operands of this node have not yet been 13216 // promoted (this should be rare because we're going through the 13217 // list backward, but if one of the operands has several users in 13218 // this cluster of to-be-promoted nodes, it is possible). 13219 PromOpHandles.emplace_front(PromOp); 13220 continue; 13221 } 13222 13223 // For SELECT and SELECT_CC nodes, we do a similar check for any 13224 // to-be-promoted comparison inputs. 13225 if (PromOp.getOpcode() == ISD::SELECT || 13226 PromOp.getOpcode() == ISD::SELECT_CC) { 13227 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13228 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13229 (SelectTruncOp[1].count(PromOp.getNode()) && 13230 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13231 PromOpHandles.emplace_front(PromOp); 13232 continue; 13233 } 13234 } 13235 13236 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13237 PromOp.getNode()->op_end()); 13238 13239 // If this node has constant inputs, then they'll need to be promoted here. 13240 for (unsigned i = 0; i < 2; ++i) { 13241 if (!isa<ConstantSDNode>(Ops[C+i])) 13242 continue; 13243 if (Ops[C+i].getValueType() == N->getValueType(0)) 13244 continue; 13245 13246 if (N->getOpcode() == ISD::SIGN_EXTEND) 13247 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13248 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13249 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13250 else 13251 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13252 } 13253 13254 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13255 // truncate them again to the original value type. 13256 if (PromOp.getOpcode() == ISD::SELECT || 13257 PromOp.getOpcode() == ISD::SELECT_CC) { 13258 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13259 if (SI0 != SelectTruncOp[0].end()) 13260 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13261 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13262 if (SI1 != SelectTruncOp[1].end()) 13263 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13264 } 13265 13266 DAG.ReplaceAllUsesOfValueWith(PromOp, 13267 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13268 } 13269 13270 // Now we're left with the initial extension itself. 13271 if (!ReallyNeedsExt) 13272 return N->getOperand(0); 13273 13274 // To zero extend, just mask off everything except for the first bit (in the 13275 // i1 case). 13276 if (N->getOpcode() == ISD::ZERO_EXTEND) 13277 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13278 DAG.getConstant(APInt::getLowBitsSet( 13279 N->getValueSizeInBits(0), PromBits), 13280 dl, N->getValueType(0))); 13281 13282 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13283 "Invalid extension type"); 13284 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13285 SDValue ShiftCst = 13286 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13287 return DAG.getNode( 13288 ISD::SRA, dl, N->getValueType(0), 13289 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13290 ShiftCst); 13291 } 13292 13293 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13294 DAGCombinerInfo &DCI) const { 13295 assert(N->getOpcode() == ISD::SETCC && 13296 "Should be called with a SETCC node"); 13297 13298 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13299 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13300 SDValue LHS = N->getOperand(0); 13301 SDValue RHS = N->getOperand(1); 13302 13303 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13304 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13305 LHS.hasOneUse()) 13306 std::swap(LHS, RHS); 13307 13308 // x == 0-y --> x+y == 0 13309 // x != 0-y --> x+y != 0 13310 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13311 RHS.hasOneUse()) { 13312 SDLoc DL(N); 13313 SelectionDAG &DAG = DCI.DAG; 13314 EVT VT = N->getValueType(0); 13315 EVT OpVT = LHS.getValueType(); 13316 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13317 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13318 } 13319 } 13320 13321 return DAGCombineTruncBoolExt(N, DCI); 13322 } 13323 13324 // Is this an extending load from an f32 to an f64? 13325 static bool isFPExtLoad(SDValue Op) { 13326 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13327 return LD->getExtensionType() == ISD::EXTLOAD && 13328 Op.getValueType() == MVT::f64; 13329 return false; 13330 } 13331 13332 /// Reduces the number of fp-to-int conversion when building a vector. 13333 /// 13334 /// If this vector is built out of floating to integer conversions, 13335 /// transform it to a vector built out of floating point values followed by a 13336 /// single floating to integer conversion of the vector. 13337 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13338 /// becomes (fptosi (build_vector ($A, $B, ...))) 13339 SDValue PPCTargetLowering:: 13340 combineElementTruncationToVectorTruncation(SDNode *N, 13341 DAGCombinerInfo &DCI) const { 13342 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13343 "Should be called with a BUILD_VECTOR node"); 13344 13345 SelectionDAG &DAG = DCI.DAG; 13346 SDLoc dl(N); 13347 13348 SDValue FirstInput = N->getOperand(0); 13349 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13350 "The input operand must be an fp-to-int conversion."); 13351 13352 // This combine happens after legalization so the fp_to_[su]i nodes are 13353 // already converted to PPCSISD nodes. 13354 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13355 if (FirstConversion == PPCISD::FCTIDZ || 13356 FirstConversion == PPCISD::FCTIDUZ || 13357 FirstConversion == PPCISD::FCTIWZ || 13358 FirstConversion == PPCISD::FCTIWUZ) { 13359 bool IsSplat = true; 13360 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13361 FirstConversion == PPCISD::FCTIWUZ; 13362 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13363 SmallVector<SDValue, 4> Ops; 13364 EVT TargetVT = N->getValueType(0); 13365 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13366 SDValue NextOp = N->getOperand(i); 13367 if (NextOp.getOpcode() != PPCISD::MFVSR) 13368 return SDValue(); 13369 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13370 if (NextConversion != FirstConversion) 13371 return SDValue(); 13372 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13373 // This is not valid if the input was originally double precision. It is 13374 // also not profitable to do unless this is an extending load in which 13375 // case doing this combine will allow us to combine consecutive loads. 13376 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13377 return SDValue(); 13378 if (N->getOperand(i) != FirstInput) 13379 IsSplat = false; 13380 } 13381 13382 // If this is a splat, we leave it as-is since there will be only a single 13383 // fp-to-int conversion followed by a splat of the integer. This is better 13384 // for 32-bit and smaller ints and neutral for 64-bit ints. 13385 if (IsSplat) 13386 return SDValue(); 13387 13388 // Now that we know we have the right type of node, get its operands 13389 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13390 SDValue In = N->getOperand(i).getOperand(0); 13391 if (Is32Bit) { 13392 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13393 // here, we know that all inputs are extending loads so this is safe). 13394 if (In.isUndef()) 13395 Ops.push_back(DAG.getUNDEF(SrcVT)); 13396 else { 13397 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13398 MVT::f32, In.getOperand(0), 13399 DAG.getIntPtrConstant(1, dl)); 13400 Ops.push_back(Trunc); 13401 } 13402 } else 13403 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13404 } 13405 13406 unsigned Opcode; 13407 if (FirstConversion == PPCISD::FCTIDZ || 13408 FirstConversion == PPCISD::FCTIWZ) 13409 Opcode = ISD::FP_TO_SINT; 13410 else 13411 Opcode = ISD::FP_TO_UINT; 13412 13413 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13414 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13415 return DAG.getNode(Opcode, dl, TargetVT, BV); 13416 } 13417 return SDValue(); 13418 } 13419 13420 /// Reduce the number of loads when building a vector. 13421 /// 13422 /// Building a vector out of multiple loads can be converted to a load 13423 /// of the vector type if the loads are consecutive. If the loads are 13424 /// consecutive but in descending order, a shuffle is added at the end 13425 /// to reorder the vector. 13426 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13427 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13428 "Should be called with a BUILD_VECTOR node"); 13429 13430 SDLoc dl(N); 13431 13432 // Return early for non byte-sized type, as they can't be consecutive. 13433 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13434 return SDValue(); 13435 13436 bool InputsAreConsecutiveLoads = true; 13437 bool InputsAreReverseConsecutive = true; 13438 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13439 SDValue FirstInput = N->getOperand(0); 13440 bool IsRoundOfExtLoad = false; 13441 13442 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13443 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13444 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13445 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13446 } 13447 // Not a build vector of (possibly fp_rounded) loads. 13448 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13449 N->getNumOperands() == 1) 13450 return SDValue(); 13451 13452 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13453 // If any inputs are fp_round(extload), they all must be. 13454 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13455 return SDValue(); 13456 13457 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13458 N->getOperand(i); 13459 if (NextInput.getOpcode() != ISD::LOAD) 13460 return SDValue(); 13461 13462 SDValue PreviousInput = 13463 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13464 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13465 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13466 13467 // If any inputs are fp_round(extload), they all must be. 13468 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13469 return SDValue(); 13470 13471 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13472 InputsAreConsecutiveLoads = false; 13473 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13474 InputsAreReverseConsecutive = false; 13475 13476 // Exit early if the loads are neither consecutive nor reverse consecutive. 13477 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13478 return SDValue(); 13479 } 13480 13481 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13482 "The loads cannot be both consecutive and reverse consecutive."); 13483 13484 SDValue FirstLoadOp = 13485 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13486 SDValue LastLoadOp = 13487 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13488 N->getOperand(N->getNumOperands()-1); 13489 13490 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13491 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13492 if (InputsAreConsecutiveLoads) { 13493 assert(LD1 && "Input needs to be a LoadSDNode."); 13494 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13495 LD1->getBasePtr(), LD1->getPointerInfo(), 13496 LD1->getAlignment()); 13497 } 13498 if (InputsAreReverseConsecutive) { 13499 assert(LDL && "Input needs to be a LoadSDNode."); 13500 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13501 LDL->getBasePtr(), LDL->getPointerInfo(), 13502 LDL->getAlignment()); 13503 SmallVector<int, 16> Ops; 13504 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13505 Ops.push_back(i); 13506 13507 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13508 DAG.getUNDEF(N->getValueType(0)), Ops); 13509 } 13510 return SDValue(); 13511 } 13512 13513 // This function adds the required vector_shuffle needed to get 13514 // the elements of the vector extract in the correct position 13515 // as specified by the CorrectElems encoding. 13516 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13517 SDValue Input, uint64_t Elems, 13518 uint64_t CorrectElems) { 13519 SDLoc dl(N); 13520 13521 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13522 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13523 13524 // Knowing the element indices being extracted from the original 13525 // vector and the order in which they're being inserted, just put 13526 // them at element indices required for the instruction. 13527 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13528 if (DAG.getDataLayout().isLittleEndian()) 13529 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13530 else 13531 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13532 CorrectElems = CorrectElems >> 8; 13533 Elems = Elems >> 8; 13534 } 13535 13536 SDValue Shuffle = 13537 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13538 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13539 13540 EVT VT = N->getValueType(0); 13541 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13542 13543 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13544 Input.getValueType().getVectorElementType(), 13545 VT.getVectorNumElements()); 13546 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13547 DAG.getValueType(ExtVT)); 13548 } 13549 13550 // Look for build vector patterns where input operands come from sign 13551 // extended vector_extract elements of specific indices. If the correct indices 13552 // aren't used, add a vector shuffle to fix up the indices and create 13553 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13554 // during instruction selection. 13555 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13556 // This array encodes the indices that the vector sign extend instructions 13557 // extract from when extending from one type to another for both BE and LE. 13558 // The right nibble of each byte corresponds to the LE incides. 13559 // and the left nibble of each byte corresponds to the BE incides. 13560 // For example: 0x3074B8FC byte->word 13561 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13562 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13563 // For example: 0x000070F8 byte->double word 13564 // For LE: the allowed indices are: 0x0,0x8 13565 // For BE: the allowed indices are: 0x7,0xF 13566 uint64_t TargetElems[] = { 13567 0x3074B8FC, // b->w 13568 0x000070F8, // b->d 13569 0x10325476, // h->w 13570 0x00003074, // h->d 13571 0x00001032, // w->d 13572 }; 13573 13574 uint64_t Elems = 0; 13575 int Index; 13576 SDValue Input; 13577 13578 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13579 if (!Op) 13580 return false; 13581 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13582 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13583 return false; 13584 13585 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13586 // of the right width. 13587 SDValue Extract = Op.getOperand(0); 13588 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13589 Extract = Extract.getOperand(0); 13590 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13591 return false; 13592 13593 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13594 if (!ExtOp) 13595 return false; 13596 13597 Index = ExtOp->getZExtValue(); 13598 if (Input && Input != Extract.getOperand(0)) 13599 return false; 13600 13601 if (!Input) 13602 Input = Extract.getOperand(0); 13603 13604 Elems = Elems << 8; 13605 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13606 Elems |= Index; 13607 13608 return true; 13609 }; 13610 13611 // If the build vector operands aren't sign extended vector extracts, 13612 // of the same input vector, then return. 13613 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13614 if (!isSExtOfVecExtract(N->getOperand(i))) { 13615 return SDValue(); 13616 } 13617 } 13618 13619 // If the vector extract indicies are not correct, add the appropriate 13620 // vector_shuffle. 13621 int TgtElemArrayIdx; 13622 int InputSize = Input.getValueType().getScalarSizeInBits(); 13623 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13624 if (InputSize + OutputSize == 40) 13625 TgtElemArrayIdx = 0; 13626 else if (InputSize + OutputSize == 72) 13627 TgtElemArrayIdx = 1; 13628 else if (InputSize + OutputSize == 48) 13629 TgtElemArrayIdx = 2; 13630 else if (InputSize + OutputSize == 80) 13631 TgtElemArrayIdx = 3; 13632 else if (InputSize + OutputSize == 96) 13633 TgtElemArrayIdx = 4; 13634 else 13635 return SDValue(); 13636 13637 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13638 CorrectElems = DAG.getDataLayout().isLittleEndian() 13639 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13640 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13641 if (Elems != CorrectElems) { 13642 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13643 } 13644 13645 // Regular lowering will catch cases where a shuffle is not needed. 13646 return SDValue(); 13647 } 13648 13649 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13650 DAGCombinerInfo &DCI) const { 13651 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13652 "Should be called with a BUILD_VECTOR node"); 13653 13654 SelectionDAG &DAG = DCI.DAG; 13655 SDLoc dl(N); 13656 13657 if (!Subtarget.hasVSX()) 13658 return SDValue(); 13659 13660 // The target independent DAG combiner will leave a build_vector of 13661 // float-to-int conversions intact. We can generate MUCH better code for 13662 // a float-to-int conversion of a vector of floats. 13663 SDValue FirstInput = N->getOperand(0); 13664 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13665 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13666 if (Reduced) 13667 return Reduced; 13668 } 13669 13670 // If we're building a vector out of consecutive loads, just load that 13671 // vector type. 13672 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13673 if (Reduced) 13674 return Reduced; 13675 13676 // If we're building a vector out of extended elements from another vector 13677 // we have P9 vector integer extend instructions. The code assumes legal 13678 // input types (i.e. it can't handle things like v4i16) so do not run before 13679 // legalization. 13680 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13681 Reduced = combineBVOfVecSExt(N, DAG); 13682 if (Reduced) 13683 return Reduced; 13684 } 13685 13686 13687 if (N->getValueType(0) != MVT::v2f64) 13688 return SDValue(); 13689 13690 // Looking for: 13691 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13692 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13693 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13694 return SDValue(); 13695 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13696 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13697 return SDValue(); 13698 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13699 return SDValue(); 13700 13701 SDValue Ext1 = FirstInput.getOperand(0); 13702 SDValue Ext2 = N->getOperand(1).getOperand(0); 13703 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13704 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13705 return SDValue(); 13706 13707 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13708 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13709 if (!Ext1Op || !Ext2Op) 13710 return SDValue(); 13711 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13712 Ext1.getOperand(0) != Ext2.getOperand(0)) 13713 return SDValue(); 13714 13715 int FirstElem = Ext1Op->getZExtValue(); 13716 int SecondElem = Ext2Op->getZExtValue(); 13717 int SubvecIdx; 13718 if (FirstElem == 0 && SecondElem == 1) 13719 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13720 else if (FirstElem == 2 && SecondElem == 3) 13721 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13722 else 13723 return SDValue(); 13724 13725 SDValue SrcVec = Ext1.getOperand(0); 13726 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13727 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13728 return DAG.getNode(NodeType, dl, MVT::v2f64, 13729 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13730 } 13731 13732 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13733 DAGCombinerInfo &DCI) const { 13734 assert((N->getOpcode() == ISD::SINT_TO_FP || 13735 N->getOpcode() == ISD::UINT_TO_FP) && 13736 "Need an int -> FP conversion node here"); 13737 13738 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13739 return SDValue(); 13740 13741 SelectionDAG &DAG = DCI.DAG; 13742 SDLoc dl(N); 13743 SDValue Op(N, 0); 13744 13745 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13746 // from the hardware. 13747 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13748 return SDValue(); 13749 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13750 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13751 return SDValue(); 13752 13753 SDValue FirstOperand(Op.getOperand(0)); 13754 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13755 (FirstOperand.getValueType() == MVT::i8 || 13756 FirstOperand.getValueType() == MVT::i16); 13757 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13758 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13759 bool DstDouble = Op.getValueType() == MVT::f64; 13760 unsigned ConvOp = Signed ? 13761 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13762 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13763 SDValue WidthConst = 13764 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13765 dl, false); 13766 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13767 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13768 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13769 DAG.getVTList(MVT::f64, MVT::Other), 13770 Ops, MVT::i8, LDN->getMemOperand()); 13771 13772 // For signed conversion, we need to sign-extend the value in the VSR 13773 if (Signed) { 13774 SDValue ExtOps[] = { Ld, WidthConst }; 13775 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13776 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13777 } else 13778 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13779 } 13780 13781 13782 // For i32 intermediate values, unfortunately, the conversion functions 13783 // leave the upper 32 bits of the value are undefined. Within the set of 13784 // scalar instructions, we have no method for zero- or sign-extending the 13785 // value. Thus, we cannot handle i32 intermediate values here. 13786 if (Op.getOperand(0).getValueType() == MVT::i32) 13787 return SDValue(); 13788 13789 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13790 "UINT_TO_FP is supported only with FPCVT"); 13791 13792 // If we have FCFIDS, then use it when converting to single-precision. 13793 // Otherwise, convert to double-precision and then round. 13794 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13795 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13796 : PPCISD::FCFIDS) 13797 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13798 : PPCISD::FCFID); 13799 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13800 ? MVT::f32 13801 : MVT::f64; 13802 13803 // If we're converting from a float, to an int, and back to a float again, 13804 // then we don't need the store/load pair at all. 13805 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13806 Subtarget.hasFPCVT()) || 13807 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13808 SDValue Src = Op.getOperand(0).getOperand(0); 13809 if (Src.getValueType() == MVT::f32) { 13810 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13811 DCI.AddToWorklist(Src.getNode()); 13812 } else if (Src.getValueType() != MVT::f64) { 13813 // Make sure that we don't pick up a ppc_fp128 source value. 13814 return SDValue(); 13815 } 13816 13817 unsigned FCTOp = 13818 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13819 PPCISD::FCTIDUZ; 13820 13821 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13822 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13823 13824 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13825 FP = DAG.getNode(ISD::FP_ROUND, dl, 13826 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13827 DCI.AddToWorklist(FP.getNode()); 13828 } 13829 13830 return FP; 13831 } 13832 13833 return SDValue(); 13834 } 13835 13836 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13837 // builtins) into loads with swaps. 13838 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13839 DAGCombinerInfo &DCI) const { 13840 SelectionDAG &DAG = DCI.DAG; 13841 SDLoc dl(N); 13842 SDValue Chain; 13843 SDValue Base; 13844 MachineMemOperand *MMO; 13845 13846 switch (N->getOpcode()) { 13847 default: 13848 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13849 case ISD::LOAD: { 13850 LoadSDNode *LD = cast<LoadSDNode>(N); 13851 Chain = LD->getChain(); 13852 Base = LD->getBasePtr(); 13853 MMO = LD->getMemOperand(); 13854 // If the MMO suggests this isn't a load of a full vector, leave 13855 // things alone. For a built-in, we have to make the change for 13856 // correctness, so if there is a size problem that will be a bug. 13857 if (MMO->getSize() < 16) 13858 return SDValue(); 13859 break; 13860 } 13861 case ISD::INTRINSIC_W_CHAIN: { 13862 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13863 Chain = Intrin->getChain(); 13864 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13865 // us what we want. Get operand 2 instead. 13866 Base = Intrin->getOperand(2); 13867 MMO = Intrin->getMemOperand(); 13868 break; 13869 } 13870 } 13871 13872 MVT VecTy = N->getValueType(0).getSimpleVT(); 13873 13874 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13875 // aligned and the type is a vector with elements up to 4 bytes 13876 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13877 VecTy.getScalarSizeInBits() <= 32) { 13878 return SDValue(); 13879 } 13880 13881 SDValue LoadOps[] = { Chain, Base }; 13882 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13883 DAG.getVTList(MVT::v2f64, MVT::Other), 13884 LoadOps, MVT::v2f64, MMO); 13885 13886 DCI.AddToWorklist(Load.getNode()); 13887 Chain = Load.getValue(1); 13888 SDValue Swap = DAG.getNode( 13889 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13890 DCI.AddToWorklist(Swap.getNode()); 13891 13892 // Add a bitcast if the resulting load type doesn't match v2f64. 13893 if (VecTy != MVT::v2f64) { 13894 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13895 DCI.AddToWorklist(N.getNode()); 13896 // Package {bitcast value, swap's chain} to match Load's shape. 13897 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13898 N, Swap.getValue(1)); 13899 } 13900 13901 return Swap; 13902 } 13903 13904 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13905 // builtins) into stores with swaps. 13906 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13907 DAGCombinerInfo &DCI) const { 13908 SelectionDAG &DAG = DCI.DAG; 13909 SDLoc dl(N); 13910 SDValue Chain; 13911 SDValue Base; 13912 unsigned SrcOpnd; 13913 MachineMemOperand *MMO; 13914 13915 switch (N->getOpcode()) { 13916 default: 13917 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13918 case ISD::STORE: { 13919 StoreSDNode *ST = cast<StoreSDNode>(N); 13920 Chain = ST->getChain(); 13921 Base = ST->getBasePtr(); 13922 MMO = ST->getMemOperand(); 13923 SrcOpnd = 1; 13924 // If the MMO suggests this isn't a store of a full vector, leave 13925 // things alone. For a built-in, we have to make the change for 13926 // correctness, so if there is a size problem that will be a bug. 13927 if (MMO->getSize() < 16) 13928 return SDValue(); 13929 break; 13930 } 13931 case ISD::INTRINSIC_VOID: { 13932 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13933 Chain = Intrin->getChain(); 13934 // Intrin->getBasePtr() oddly does not get what we want. 13935 Base = Intrin->getOperand(3); 13936 MMO = Intrin->getMemOperand(); 13937 SrcOpnd = 2; 13938 break; 13939 } 13940 } 13941 13942 SDValue Src = N->getOperand(SrcOpnd); 13943 MVT VecTy = Src.getValueType().getSimpleVT(); 13944 13945 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13946 // aligned and the type is a vector with elements up to 4 bytes 13947 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13948 VecTy.getScalarSizeInBits() <= 32) { 13949 return SDValue(); 13950 } 13951 13952 // All stores are done as v2f64 and possible bit cast. 13953 if (VecTy != MVT::v2f64) { 13954 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13955 DCI.AddToWorklist(Src.getNode()); 13956 } 13957 13958 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13959 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13960 DCI.AddToWorklist(Swap.getNode()); 13961 Chain = Swap.getValue(1); 13962 SDValue StoreOps[] = { Chain, Swap, Base }; 13963 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13964 DAG.getVTList(MVT::Other), 13965 StoreOps, VecTy, MMO); 13966 DCI.AddToWorklist(Store.getNode()); 13967 return Store; 13968 } 13969 13970 // Handle DAG combine for STORE (FP_TO_INT F). 13971 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13972 DAGCombinerInfo &DCI) const { 13973 13974 SelectionDAG &DAG = DCI.DAG; 13975 SDLoc dl(N); 13976 unsigned Opcode = N->getOperand(1).getOpcode(); 13977 13978 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13979 && "Not a FP_TO_INT Instruction!"); 13980 13981 SDValue Val = N->getOperand(1).getOperand(0); 13982 EVT Op1VT = N->getOperand(1).getValueType(); 13983 EVT ResVT = Val.getValueType(); 13984 13985 // Floating point types smaller than 32 bits are not legal on Power. 13986 if (ResVT.getScalarSizeInBits() < 32) 13987 return SDValue(); 13988 13989 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13990 bool ValidTypeForStoreFltAsInt = 13991 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13992 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13993 13994 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13995 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13996 return SDValue(); 13997 13998 // Extend f32 values to f64 13999 if (ResVT.getScalarSizeInBits() == 32) { 14000 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14001 DCI.AddToWorklist(Val.getNode()); 14002 } 14003 14004 // Set signed or unsigned conversion opcode. 14005 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14006 PPCISD::FP_TO_SINT_IN_VSR : 14007 PPCISD::FP_TO_UINT_IN_VSR; 14008 14009 Val = DAG.getNode(ConvOpcode, 14010 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14011 DCI.AddToWorklist(Val.getNode()); 14012 14013 // Set number of bytes being converted. 14014 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14015 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14016 DAG.getIntPtrConstant(ByteSize, dl, false), 14017 DAG.getValueType(Op1VT) }; 14018 14019 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14020 DAG.getVTList(MVT::Other), Ops, 14021 cast<StoreSDNode>(N)->getMemoryVT(), 14022 cast<StoreSDNode>(N)->getMemOperand()); 14023 14024 DCI.AddToWorklist(Val.getNode()); 14025 return Val; 14026 } 14027 14028 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14029 LSBaseSDNode *LSBase, 14030 DAGCombinerInfo &DCI) const { 14031 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14032 "Not a reverse memop pattern!"); 14033 14034 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14035 auto Mask = SVN->getMask(); 14036 int i = 0; 14037 auto I = Mask.rbegin(); 14038 auto E = Mask.rend(); 14039 14040 for (; I != E; ++I) { 14041 if (*I != i) 14042 return false; 14043 i++; 14044 } 14045 return true; 14046 }; 14047 14048 SelectionDAG &DAG = DCI.DAG; 14049 EVT VT = SVN->getValueType(0); 14050 14051 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14052 return SDValue(); 14053 14054 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14055 // See comment in PPCVSXSwapRemoval.cpp. 14056 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14057 if (!Subtarget.hasP9Vector()) 14058 return SDValue(); 14059 14060 if(!IsElementReverse(SVN)) 14061 return SDValue(); 14062 14063 if (LSBase->getOpcode() == ISD::LOAD) { 14064 SDLoc dl(SVN); 14065 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14066 return DAG.getMemIntrinsicNode( 14067 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14068 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14069 } 14070 14071 if (LSBase->getOpcode() == ISD::STORE) { 14072 SDLoc dl(LSBase); 14073 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14074 LSBase->getBasePtr()}; 14075 return DAG.getMemIntrinsicNode( 14076 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14077 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14078 } 14079 14080 llvm_unreachable("Expected a load or store node here"); 14081 } 14082 14083 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14084 DAGCombinerInfo &DCI) const { 14085 SelectionDAG &DAG = DCI.DAG; 14086 SDLoc dl(N); 14087 switch (N->getOpcode()) { 14088 default: break; 14089 case ISD::ADD: 14090 return combineADD(N, DCI); 14091 case ISD::SHL: 14092 return combineSHL(N, DCI); 14093 case ISD::SRA: 14094 return combineSRA(N, DCI); 14095 case ISD::SRL: 14096 return combineSRL(N, DCI); 14097 case ISD::MUL: 14098 return combineMUL(N, DCI); 14099 case PPCISD::SHL: 14100 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14101 return N->getOperand(0); 14102 break; 14103 case PPCISD::SRL: 14104 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14105 return N->getOperand(0); 14106 break; 14107 case PPCISD::SRA: 14108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14109 if (C->isNullValue() || // 0 >>s V -> 0. 14110 C->isAllOnesValue()) // -1 >>s V -> -1. 14111 return N->getOperand(0); 14112 } 14113 break; 14114 case ISD::SIGN_EXTEND: 14115 case ISD::ZERO_EXTEND: 14116 case ISD::ANY_EXTEND: 14117 return DAGCombineExtBoolTrunc(N, DCI); 14118 case ISD::TRUNCATE: 14119 return combineTRUNCATE(N, DCI); 14120 case ISD::SETCC: 14121 if (SDValue CSCC = combineSetCC(N, DCI)) 14122 return CSCC; 14123 LLVM_FALLTHROUGH; 14124 case ISD::SELECT_CC: 14125 return DAGCombineTruncBoolExt(N, DCI); 14126 case ISD::SINT_TO_FP: 14127 case ISD::UINT_TO_FP: 14128 return combineFPToIntToFP(N, DCI); 14129 case ISD::VECTOR_SHUFFLE: 14130 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14131 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14132 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14133 } 14134 break; 14135 case ISD::STORE: { 14136 14137 EVT Op1VT = N->getOperand(1).getValueType(); 14138 unsigned Opcode = N->getOperand(1).getOpcode(); 14139 14140 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14141 SDValue Val= combineStoreFPToInt(N, DCI); 14142 if (Val) 14143 return Val; 14144 } 14145 14146 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14147 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14148 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14149 if (Val) 14150 return Val; 14151 } 14152 14153 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14154 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14155 N->getOperand(1).getNode()->hasOneUse() && 14156 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14157 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14158 14159 // STBRX can only handle simple types and it makes no sense to store less 14160 // two bytes in byte-reversed order. 14161 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14162 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14163 break; 14164 14165 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14166 // Do an any-extend to 32-bits if this is a half-word input. 14167 if (BSwapOp.getValueType() == MVT::i16) 14168 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14169 14170 // If the type of BSWAP operand is wider than stored memory width 14171 // it need to be shifted to the right side before STBRX. 14172 if (Op1VT.bitsGT(mVT)) { 14173 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14174 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14175 DAG.getConstant(Shift, dl, MVT::i32)); 14176 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14177 if (Op1VT == MVT::i64) 14178 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14179 } 14180 14181 SDValue Ops[] = { 14182 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14183 }; 14184 return 14185 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14186 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14187 cast<StoreSDNode>(N)->getMemOperand()); 14188 } 14189 14190 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14191 // So it can increase the chance of CSE constant construction. 14192 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14193 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14194 // Need to sign-extended to 64-bits to handle negative values. 14195 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14196 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14197 MemVT.getSizeInBits()); 14198 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14199 14200 // DAG.getTruncStore() can't be used here because it doesn't accept 14201 // the general (base + offset) addressing mode. 14202 // So we use UpdateNodeOperands and setTruncatingStore instead. 14203 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14204 N->getOperand(3)); 14205 cast<StoreSDNode>(N)->setTruncatingStore(true); 14206 return SDValue(N, 0); 14207 } 14208 14209 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14210 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14211 if (Op1VT.isSimple()) { 14212 MVT StoreVT = Op1VT.getSimpleVT(); 14213 if (Subtarget.needsSwapsForVSXMemOps() && 14214 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14215 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14216 return expandVSXStoreForLE(N, DCI); 14217 } 14218 break; 14219 } 14220 case ISD::LOAD: { 14221 LoadSDNode *LD = cast<LoadSDNode>(N); 14222 EVT VT = LD->getValueType(0); 14223 14224 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14225 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14226 if (VT.isSimple()) { 14227 MVT LoadVT = VT.getSimpleVT(); 14228 if (Subtarget.needsSwapsForVSXMemOps() && 14229 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14230 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14231 return expandVSXLoadForLE(N, DCI); 14232 } 14233 14234 // We sometimes end up with a 64-bit integer load, from which we extract 14235 // two single-precision floating-point numbers. This happens with 14236 // std::complex<float>, and other similar structures, because of the way we 14237 // canonicalize structure copies. However, if we lack direct moves, 14238 // then the final bitcasts from the extracted integer values to the 14239 // floating-point numbers turn into store/load pairs. Even with direct moves, 14240 // just loading the two floating-point numbers is likely better. 14241 auto ReplaceTwoFloatLoad = [&]() { 14242 if (VT != MVT::i64) 14243 return false; 14244 14245 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14246 LD->isVolatile()) 14247 return false; 14248 14249 // We're looking for a sequence like this: 14250 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14251 // t16: i64 = srl t13, Constant:i32<32> 14252 // t17: i32 = truncate t16 14253 // t18: f32 = bitcast t17 14254 // t19: i32 = truncate t13 14255 // t20: f32 = bitcast t19 14256 14257 if (!LD->hasNUsesOfValue(2, 0)) 14258 return false; 14259 14260 auto UI = LD->use_begin(); 14261 while (UI.getUse().getResNo() != 0) ++UI; 14262 SDNode *Trunc = *UI++; 14263 while (UI.getUse().getResNo() != 0) ++UI; 14264 SDNode *RightShift = *UI; 14265 if (Trunc->getOpcode() != ISD::TRUNCATE) 14266 std::swap(Trunc, RightShift); 14267 14268 if (Trunc->getOpcode() != ISD::TRUNCATE || 14269 Trunc->getValueType(0) != MVT::i32 || 14270 !Trunc->hasOneUse()) 14271 return false; 14272 if (RightShift->getOpcode() != ISD::SRL || 14273 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14274 RightShift->getConstantOperandVal(1) != 32 || 14275 !RightShift->hasOneUse()) 14276 return false; 14277 14278 SDNode *Trunc2 = *RightShift->use_begin(); 14279 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14280 Trunc2->getValueType(0) != MVT::i32 || 14281 !Trunc2->hasOneUse()) 14282 return false; 14283 14284 SDNode *Bitcast = *Trunc->use_begin(); 14285 SDNode *Bitcast2 = *Trunc2->use_begin(); 14286 14287 if (Bitcast->getOpcode() != ISD::BITCAST || 14288 Bitcast->getValueType(0) != MVT::f32) 14289 return false; 14290 if (Bitcast2->getOpcode() != ISD::BITCAST || 14291 Bitcast2->getValueType(0) != MVT::f32) 14292 return false; 14293 14294 if (Subtarget.isLittleEndian()) 14295 std::swap(Bitcast, Bitcast2); 14296 14297 // Bitcast has the second float (in memory-layout order) and Bitcast2 14298 // has the first one. 14299 14300 SDValue BasePtr = LD->getBasePtr(); 14301 if (LD->isIndexed()) { 14302 assert(LD->getAddressingMode() == ISD::PRE_INC && 14303 "Non-pre-inc AM on PPC?"); 14304 BasePtr = 14305 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14306 LD->getOffset()); 14307 } 14308 14309 auto MMOFlags = 14310 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14311 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14312 LD->getPointerInfo(), LD->getAlignment(), 14313 MMOFlags, LD->getAAInfo()); 14314 SDValue AddPtr = 14315 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14316 BasePtr, DAG.getIntPtrConstant(4, dl)); 14317 SDValue FloatLoad2 = DAG.getLoad( 14318 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14319 LD->getPointerInfo().getWithOffset(4), 14320 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14321 14322 if (LD->isIndexed()) { 14323 // Note that DAGCombine should re-form any pre-increment load(s) from 14324 // what is produced here if that makes sense. 14325 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14326 } 14327 14328 DCI.CombineTo(Bitcast2, FloatLoad); 14329 DCI.CombineTo(Bitcast, FloatLoad2); 14330 14331 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14332 SDValue(FloatLoad2.getNode(), 1)); 14333 return true; 14334 }; 14335 14336 if (ReplaceTwoFloatLoad()) 14337 return SDValue(N, 0); 14338 14339 EVT MemVT = LD->getMemoryVT(); 14340 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14341 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14342 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14343 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14344 if (LD->isUnindexed() && VT.isVector() && 14345 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14346 // P8 and later hardware should just use LOAD. 14347 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14348 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14349 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14350 LD->getAlignment() >= ScalarABIAlignment)) && 14351 LD->getAlignment() < ABIAlignment) { 14352 // This is a type-legal unaligned Altivec or QPX load. 14353 SDValue Chain = LD->getChain(); 14354 SDValue Ptr = LD->getBasePtr(); 14355 bool isLittleEndian = Subtarget.isLittleEndian(); 14356 14357 // This implements the loading of unaligned vectors as described in 14358 // the venerable Apple Velocity Engine overview. Specifically: 14359 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14360 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14361 // 14362 // The general idea is to expand a sequence of one or more unaligned 14363 // loads into an alignment-based permutation-control instruction (lvsl 14364 // or lvsr), a series of regular vector loads (which always truncate 14365 // their input address to an aligned address), and a series of 14366 // permutations. The results of these permutations are the requested 14367 // loaded values. The trick is that the last "extra" load is not taken 14368 // from the address you might suspect (sizeof(vector) bytes after the 14369 // last requested load), but rather sizeof(vector) - 1 bytes after the 14370 // last requested vector. The point of this is to avoid a page fault if 14371 // the base address happened to be aligned. This works because if the 14372 // base address is aligned, then adding less than a full vector length 14373 // will cause the last vector in the sequence to be (re)loaded. 14374 // Otherwise, the next vector will be fetched as you might suspect was 14375 // necessary. 14376 14377 // We might be able to reuse the permutation generation from 14378 // a different base address offset from this one by an aligned amount. 14379 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14380 // optimization later. 14381 Intrinsic::ID Intr, IntrLD, IntrPerm; 14382 MVT PermCntlTy, PermTy, LDTy; 14383 if (Subtarget.hasAltivec()) { 14384 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14385 Intrinsic::ppc_altivec_lvsl; 14386 IntrLD = Intrinsic::ppc_altivec_lvx; 14387 IntrPerm = Intrinsic::ppc_altivec_vperm; 14388 PermCntlTy = MVT::v16i8; 14389 PermTy = MVT::v4i32; 14390 LDTy = MVT::v4i32; 14391 } else { 14392 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14393 Intrinsic::ppc_qpx_qvlpcls; 14394 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14395 Intrinsic::ppc_qpx_qvlfs; 14396 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14397 PermCntlTy = MVT::v4f64; 14398 PermTy = MVT::v4f64; 14399 LDTy = MemVT.getSimpleVT(); 14400 } 14401 14402 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14403 14404 // Create the new MMO for the new base load. It is like the original MMO, 14405 // but represents an area in memory almost twice the vector size centered 14406 // on the original address. If the address is unaligned, we might start 14407 // reading up to (sizeof(vector)-1) bytes below the address of the 14408 // original unaligned load. 14409 MachineFunction &MF = DAG.getMachineFunction(); 14410 MachineMemOperand *BaseMMO = 14411 MF.getMachineMemOperand(LD->getMemOperand(), 14412 -(long)MemVT.getStoreSize()+1, 14413 2*MemVT.getStoreSize()-1); 14414 14415 // Create the new base load. 14416 SDValue LDXIntID = 14417 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14418 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14419 SDValue BaseLoad = 14420 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14421 DAG.getVTList(PermTy, MVT::Other), 14422 BaseLoadOps, LDTy, BaseMMO); 14423 14424 // Note that the value of IncOffset (which is provided to the next 14425 // load's pointer info offset value, and thus used to calculate the 14426 // alignment), and the value of IncValue (which is actually used to 14427 // increment the pointer value) are different! This is because we 14428 // require the next load to appear to be aligned, even though it 14429 // is actually offset from the base pointer by a lesser amount. 14430 int IncOffset = VT.getSizeInBits() / 8; 14431 int IncValue = IncOffset; 14432 14433 // Walk (both up and down) the chain looking for another load at the real 14434 // (aligned) offset (the alignment of the other load does not matter in 14435 // this case). If found, then do not use the offset reduction trick, as 14436 // that will prevent the loads from being later combined (as they would 14437 // otherwise be duplicates). 14438 if (!findConsecutiveLoad(LD, DAG)) 14439 --IncValue; 14440 14441 SDValue Increment = 14442 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14443 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14444 14445 MachineMemOperand *ExtraMMO = 14446 MF.getMachineMemOperand(LD->getMemOperand(), 14447 1, 2*MemVT.getStoreSize()-1); 14448 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14449 SDValue ExtraLoad = 14450 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14451 DAG.getVTList(PermTy, MVT::Other), 14452 ExtraLoadOps, LDTy, ExtraMMO); 14453 14454 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14455 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14456 14457 // Because vperm has a big-endian bias, we must reverse the order 14458 // of the input vectors and complement the permute control vector 14459 // when generating little endian code. We have already handled the 14460 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14461 // and ExtraLoad here. 14462 SDValue Perm; 14463 if (isLittleEndian) 14464 Perm = BuildIntrinsicOp(IntrPerm, 14465 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14466 else 14467 Perm = BuildIntrinsicOp(IntrPerm, 14468 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14469 14470 if (VT != PermTy) 14471 Perm = Subtarget.hasAltivec() ? 14472 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14473 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14474 DAG.getTargetConstant(1, dl, MVT::i64)); 14475 // second argument is 1 because this rounding 14476 // is always exact. 14477 14478 // The output of the permutation is our loaded result, the TokenFactor is 14479 // our new chain. 14480 DCI.CombineTo(N, Perm, TF); 14481 return SDValue(N, 0); 14482 } 14483 } 14484 break; 14485 case ISD::INTRINSIC_WO_CHAIN: { 14486 bool isLittleEndian = Subtarget.isLittleEndian(); 14487 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14488 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14489 : Intrinsic::ppc_altivec_lvsl); 14490 if ((IID == Intr || 14491 IID == Intrinsic::ppc_qpx_qvlpcld || 14492 IID == Intrinsic::ppc_qpx_qvlpcls) && 14493 N->getOperand(1)->getOpcode() == ISD::ADD) { 14494 SDValue Add = N->getOperand(1); 14495 14496 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14497 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14498 14499 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14500 APInt::getAllOnesValue(Bits /* alignment */) 14501 .zext(Add.getScalarValueSizeInBits()))) { 14502 SDNode *BasePtr = Add->getOperand(0).getNode(); 14503 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14504 UE = BasePtr->use_end(); 14505 UI != UE; ++UI) { 14506 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14507 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14508 // We've found another LVSL/LVSR, and this address is an aligned 14509 // multiple of that one. The results will be the same, so use the 14510 // one we've just found instead. 14511 14512 return SDValue(*UI, 0); 14513 } 14514 } 14515 } 14516 14517 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14518 SDNode *BasePtr = Add->getOperand(0).getNode(); 14519 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14520 UE = BasePtr->use_end(); UI != UE; ++UI) { 14521 if (UI->getOpcode() == ISD::ADD && 14522 isa<ConstantSDNode>(UI->getOperand(1)) && 14523 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14524 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14525 (1ULL << Bits) == 0) { 14526 SDNode *OtherAdd = *UI; 14527 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14528 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14529 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14530 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14531 return SDValue(*VI, 0); 14532 } 14533 } 14534 } 14535 } 14536 } 14537 } 14538 14539 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14540 // Expose the vabsduw/h/b opportunity for down stream 14541 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14542 (IID == Intrinsic::ppc_altivec_vmaxsw || 14543 IID == Intrinsic::ppc_altivec_vmaxsh || 14544 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14545 SDValue V1 = N->getOperand(1); 14546 SDValue V2 = N->getOperand(2); 14547 if ((V1.getSimpleValueType() == MVT::v4i32 || 14548 V1.getSimpleValueType() == MVT::v8i16 || 14549 V1.getSimpleValueType() == MVT::v16i8) && 14550 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14551 // (0-a, a) 14552 if (V1.getOpcode() == ISD::SUB && 14553 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14554 V1.getOperand(1) == V2) { 14555 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14556 } 14557 // (a, 0-a) 14558 if (V2.getOpcode() == ISD::SUB && 14559 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14560 V2.getOperand(1) == V1) { 14561 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14562 } 14563 // (x-y, y-x) 14564 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14565 V1.getOperand(0) == V2.getOperand(1) && 14566 V1.getOperand(1) == V2.getOperand(0)) { 14567 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14568 } 14569 } 14570 } 14571 } 14572 14573 break; 14574 case ISD::INTRINSIC_W_CHAIN: 14575 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14576 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14577 if (Subtarget.needsSwapsForVSXMemOps()) { 14578 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14579 default: 14580 break; 14581 case Intrinsic::ppc_vsx_lxvw4x: 14582 case Intrinsic::ppc_vsx_lxvd2x: 14583 return expandVSXLoadForLE(N, DCI); 14584 } 14585 } 14586 break; 14587 case ISD::INTRINSIC_VOID: 14588 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14589 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14590 if (Subtarget.needsSwapsForVSXMemOps()) { 14591 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14592 default: 14593 break; 14594 case Intrinsic::ppc_vsx_stxvw4x: 14595 case Intrinsic::ppc_vsx_stxvd2x: 14596 return expandVSXStoreForLE(N, DCI); 14597 } 14598 } 14599 break; 14600 case ISD::BSWAP: 14601 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14602 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14603 N->getOperand(0).hasOneUse() && 14604 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14605 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14606 N->getValueType(0) == MVT::i64))) { 14607 SDValue Load = N->getOperand(0); 14608 LoadSDNode *LD = cast<LoadSDNode>(Load); 14609 // Create the byte-swapping load. 14610 SDValue Ops[] = { 14611 LD->getChain(), // Chain 14612 LD->getBasePtr(), // Ptr 14613 DAG.getValueType(N->getValueType(0)) // VT 14614 }; 14615 SDValue BSLoad = 14616 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14617 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14618 MVT::i64 : MVT::i32, MVT::Other), 14619 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14620 14621 // If this is an i16 load, insert the truncate. 14622 SDValue ResVal = BSLoad; 14623 if (N->getValueType(0) == MVT::i16) 14624 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14625 14626 // First, combine the bswap away. This makes the value produced by the 14627 // load dead. 14628 DCI.CombineTo(N, ResVal); 14629 14630 // Next, combine the load away, we give it a bogus result value but a real 14631 // chain result. The result value is dead because the bswap is dead. 14632 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14633 14634 // Return N so it doesn't get rechecked! 14635 return SDValue(N, 0); 14636 } 14637 break; 14638 case PPCISD::VCMP: 14639 // If a VCMPo node already exists with exactly the same operands as this 14640 // node, use its result instead of this node (VCMPo computes both a CR6 and 14641 // a normal output). 14642 // 14643 if (!N->getOperand(0).hasOneUse() && 14644 !N->getOperand(1).hasOneUse() && 14645 !N->getOperand(2).hasOneUse()) { 14646 14647 // Scan all of the users of the LHS, looking for VCMPo's that match. 14648 SDNode *VCMPoNode = nullptr; 14649 14650 SDNode *LHSN = N->getOperand(0).getNode(); 14651 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14652 UI != E; ++UI) 14653 if (UI->getOpcode() == PPCISD::VCMPo && 14654 UI->getOperand(1) == N->getOperand(1) && 14655 UI->getOperand(2) == N->getOperand(2) && 14656 UI->getOperand(0) == N->getOperand(0)) { 14657 VCMPoNode = *UI; 14658 break; 14659 } 14660 14661 // If there is no VCMPo node, or if the flag value has a single use, don't 14662 // transform this. 14663 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14664 break; 14665 14666 // Look at the (necessarily single) use of the flag value. If it has a 14667 // chain, this transformation is more complex. Note that multiple things 14668 // could use the value result, which we should ignore. 14669 SDNode *FlagUser = nullptr; 14670 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14671 FlagUser == nullptr; ++UI) { 14672 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14673 SDNode *User = *UI; 14674 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14675 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14676 FlagUser = User; 14677 break; 14678 } 14679 } 14680 } 14681 14682 // If the user is a MFOCRF instruction, we know this is safe. 14683 // Otherwise we give up for right now. 14684 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14685 return SDValue(VCMPoNode, 0); 14686 } 14687 break; 14688 case ISD::BRCOND: { 14689 SDValue Cond = N->getOperand(1); 14690 SDValue Target = N->getOperand(2); 14691 14692 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14693 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14694 Intrinsic::loop_decrement) { 14695 14696 // We now need to make the intrinsic dead (it cannot be instruction 14697 // selected). 14698 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14699 assert(Cond.getNode()->hasOneUse() && 14700 "Counter decrement has more than one use"); 14701 14702 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14703 N->getOperand(0), Target); 14704 } 14705 } 14706 break; 14707 case ISD::BR_CC: { 14708 // If this is a branch on an altivec predicate comparison, lower this so 14709 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14710 // lowering is done pre-legalize, because the legalizer lowers the predicate 14711 // compare down to code that is difficult to reassemble. 14712 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14713 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14714 14715 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14716 // value. If so, pass-through the AND to get to the intrinsic. 14717 if (LHS.getOpcode() == ISD::AND && 14718 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14719 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14720 Intrinsic::loop_decrement && 14721 isa<ConstantSDNode>(LHS.getOperand(1)) && 14722 !isNullConstant(LHS.getOperand(1))) 14723 LHS = LHS.getOperand(0); 14724 14725 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14726 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14727 Intrinsic::loop_decrement && 14728 isa<ConstantSDNode>(RHS)) { 14729 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14730 "Counter decrement comparison is not EQ or NE"); 14731 14732 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14733 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14734 (CC == ISD::SETNE && !Val); 14735 14736 // We now need to make the intrinsic dead (it cannot be instruction 14737 // selected). 14738 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14739 assert(LHS.getNode()->hasOneUse() && 14740 "Counter decrement has more than one use"); 14741 14742 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14743 N->getOperand(0), N->getOperand(4)); 14744 } 14745 14746 int CompareOpc; 14747 bool isDot; 14748 14749 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14750 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14751 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14752 assert(isDot && "Can't compare against a vector result!"); 14753 14754 // If this is a comparison against something other than 0/1, then we know 14755 // that the condition is never/always true. 14756 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14757 if (Val != 0 && Val != 1) { 14758 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14759 return N->getOperand(0); 14760 // Always !=, turn it into an unconditional branch. 14761 return DAG.getNode(ISD::BR, dl, MVT::Other, 14762 N->getOperand(0), N->getOperand(4)); 14763 } 14764 14765 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14766 14767 // Create the PPCISD altivec 'dot' comparison node. 14768 SDValue Ops[] = { 14769 LHS.getOperand(2), // LHS of compare 14770 LHS.getOperand(3), // RHS of compare 14771 DAG.getConstant(CompareOpc, dl, MVT::i32) 14772 }; 14773 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14774 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14775 14776 // Unpack the result based on how the target uses it. 14777 PPC::Predicate CompOpc; 14778 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14779 default: // Can't happen, don't crash on invalid number though. 14780 case 0: // Branch on the value of the EQ bit of CR6. 14781 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14782 break; 14783 case 1: // Branch on the inverted value of the EQ bit of CR6. 14784 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14785 break; 14786 case 2: // Branch on the value of the LT bit of CR6. 14787 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14788 break; 14789 case 3: // Branch on the inverted value of the LT bit of CR6. 14790 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14791 break; 14792 } 14793 14794 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14795 DAG.getConstant(CompOpc, dl, MVT::i32), 14796 DAG.getRegister(PPC::CR6, MVT::i32), 14797 N->getOperand(4), CompNode.getValue(1)); 14798 } 14799 break; 14800 } 14801 case ISD::BUILD_VECTOR: 14802 return DAGCombineBuildVector(N, DCI); 14803 case ISD::ABS: 14804 return combineABS(N, DCI); 14805 case ISD::VSELECT: 14806 return combineVSelect(N, DCI); 14807 } 14808 14809 return SDValue(); 14810 } 14811 14812 SDValue 14813 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14814 SelectionDAG &DAG, 14815 SmallVectorImpl<SDNode *> &Created) const { 14816 // fold (sdiv X, pow2) 14817 EVT VT = N->getValueType(0); 14818 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14819 return SDValue(); 14820 if ((VT != MVT::i32 && VT != MVT::i64) || 14821 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14822 return SDValue(); 14823 14824 SDLoc DL(N); 14825 SDValue N0 = N->getOperand(0); 14826 14827 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14828 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14829 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14830 14831 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14832 Created.push_back(Op.getNode()); 14833 14834 if (IsNegPow2) { 14835 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14836 Created.push_back(Op.getNode()); 14837 } 14838 14839 return Op; 14840 } 14841 14842 //===----------------------------------------------------------------------===// 14843 // Inline Assembly Support 14844 //===----------------------------------------------------------------------===// 14845 14846 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14847 KnownBits &Known, 14848 const APInt &DemandedElts, 14849 const SelectionDAG &DAG, 14850 unsigned Depth) const { 14851 Known.resetAll(); 14852 switch (Op.getOpcode()) { 14853 default: break; 14854 case PPCISD::LBRX: { 14855 // lhbrx is known to have the top bits cleared out. 14856 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14857 Known.Zero = 0xFFFF0000; 14858 break; 14859 } 14860 case ISD::INTRINSIC_WO_CHAIN: { 14861 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14862 default: break; 14863 case Intrinsic::ppc_altivec_vcmpbfp_p: 14864 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14865 case Intrinsic::ppc_altivec_vcmpequb_p: 14866 case Intrinsic::ppc_altivec_vcmpequh_p: 14867 case Intrinsic::ppc_altivec_vcmpequw_p: 14868 case Intrinsic::ppc_altivec_vcmpequd_p: 14869 case Intrinsic::ppc_altivec_vcmpgefp_p: 14870 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14871 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14872 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14873 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14874 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14875 case Intrinsic::ppc_altivec_vcmpgtub_p: 14876 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14877 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14878 case Intrinsic::ppc_altivec_vcmpgtud_p: 14879 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14880 break; 14881 } 14882 } 14883 } 14884 } 14885 14886 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14887 switch (Subtarget.getCPUDirective()) { 14888 default: break; 14889 case PPC::DIR_970: 14890 case PPC::DIR_PWR4: 14891 case PPC::DIR_PWR5: 14892 case PPC::DIR_PWR5X: 14893 case PPC::DIR_PWR6: 14894 case PPC::DIR_PWR6X: 14895 case PPC::DIR_PWR7: 14896 case PPC::DIR_PWR8: 14897 case PPC::DIR_PWR9: 14898 case PPC::DIR_PWR_FUTURE: { 14899 if (!ML) 14900 break; 14901 14902 if (!DisableInnermostLoopAlign32) { 14903 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14904 // so that we can decrease cache misses and branch-prediction misses. 14905 // Actual alignment of the loop will depend on the hotness check and other 14906 // logic in alignBlocks. 14907 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14908 return Align(32); 14909 } 14910 14911 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14912 14913 // For small loops (between 5 and 8 instructions), align to a 32-byte 14914 // boundary so that the entire loop fits in one instruction-cache line. 14915 uint64_t LoopSize = 0; 14916 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14917 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14918 LoopSize += TII->getInstSizeInBytes(*J); 14919 if (LoopSize > 32) 14920 break; 14921 } 14922 14923 if (LoopSize > 16 && LoopSize <= 32) 14924 return Align(32); 14925 14926 break; 14927 } 14928 } 14929 14930 return TargetLowering::getPrefLoopAlignment(ML); 14931 } 14932 14933 /// getConstraintType - Given a constraint, return the type of 14934 /// constraint it is for this target. 14935 PPCTargetLowering::ConstraintType 14936 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14937 if (Constraint.size() == 1) { 14938 switch (Constraint[0]) { 14939 default: break; 14940 case 'b': 14941 case 'r': 14942 case 'f': 14943 case 'd': 14944 case 'v': 14945 case 'y': 14946 return C_RegisterClass; 14947 case 'Z': 14948 // FIXME: While Z does indicate a memory constraint, it specifically 14949 // indicates an r+r address (used in conjunction with the 'y' modifier 14950 // in the replacement string). Currently, we're forcing the base 14951 // register to be r0 in the asm printer (which is interpreted as zero) 14952 // and forming the complete address in the second register. This is 14953 // suboptimal. 14954 return C_Memory; 14955 } 14956 } else if (Constraint == "wc") { // individual CR bits. 14957 return C_RegisterClass; 14958 } else if (Constraint == "wa" || Constraint == "wd" || 14959 Constraint == "wf" || Constraint == "ws" || 14960 Constraint == "wi" || Constraint == "ww") { 14961 return C_RegisterClass; // VSX registers. 14962 } 14963 return TargetLowering::getConstraintType(Constraint); 14964 } 14965 14966 /// Examine constraint type and operand type and determine a weight value. 14967 /// This object must already have been set up with the operand type 14968 /// and the current alternative constraint selected. 14969 TargetLowering::ConstraintWeight 14970 PPCTargetLowering::getSingleConstraintMatchWeight( 14971 AsmOperandInfo &info, const char *constraint) const { 14972 ConstraintWeight weight = CW_Invalid; 14973 Value *CallOperandVal = info.CallOperandVal; 14974 // If we don't have a value, we can't do a match, 14975 // but allow it at the lowest weight. 14976 if (!CallOperandVal) 14977 return CW_Default; 14978 Type *type = CallOperandVal->getType(); 14979 14980 // Look at the constraint type. 14981 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14982 return CW_Register; // an individual CR bit. 14983 else if ((StringRef(constraint) == "wa" || 14984 StringRef(constraint) == "wd" || 14985 StringRef(constraint) == "wf") && 14986 type->isVectorTy()) 14987 return CW_Register; 14988 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14989 return CW_Register; // just hold 64-bit integers data. 14990 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14991 return CW_Register; 14992 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14993 return CW_Register; 14994 14995 switch (*constraint) { 14996 default: 14997 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14998 break; 14999 case 'b': 15000 if (type->isIntegerTy()) 15001 weight = CW_Register; 15002 break; 15003 case 'f': 15004 if (type->isFloatTy()) 15005 weight = CW_Register; 15006 break; 15007 case 'd': 15008 if (type->isDoubleTy()) 15009 weight = CW_Register; 15010 break; 15011 case 'v': 15012 if (type->isVectorTy()) 15013 weight = CW_Register; 15014 break; 15015 case 'y': 15016 weight = CW_Register; 15017 break; 15018 case 'Z': 15019 weight = CW_Memory; 15020 break; 15021 } 15022 return weight; 15023 } 15024 15025 std::pair<unsigned, const TargetRegisterClass *> 15026 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15027 StringRef Constraint, 15028 MVT VT) const { 15029 if (Constraint.size() == 1) { 15030 // GCC RS6000 Constraint Letters 15031 switch (Constraint[0]) { 15032 case 'b': // R1-R31 15033 if (VT == MVT::i64 && Subtarget.isPPC64()) 15034 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15035 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15036 case 'r': // R0-R31 15037 if (VT == MVT::i64 && Subtarget.isPPC64()) 15038 return std::make_pair(0U, &PPC::G8RCRegClass); 15039 return std::make_pair(0U, &PPC::GPRCRegClass); 15040 // 'd' and 'f' constraints are both defined to be "the floating point 15041 // registers", where one is for 32-bit and the other for 64-bit. We don't 15042 // really care overly much here so just give them all the same reg classes. 15043 case 'd': 15044 case 'f': 15045 if (Subtarget.hasSPE()) { 15046 if (VT == MVT::f32 || VT == MVT::i32) 15047 return std::make_pair(0U, &PPC::GPRCRegClass); 15048 if (VT == MVT::f64 || VT == MVT::i64) 15049 return std::make_pair(0U, &PPC::SPERCRegClass); 15050 } else { 15051 if (VT == MVT::f32 || VT == MVT::i32) 15052 return std::make_pair(0U, &PPC::F4RCRegClass); 15053 if (VT == MVT::f64 || VT == MVT::i64) 15054 return std::make_pair(0U, &PPC::F8RCRegClass); 15055 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15056 return std::make_pair(0U, &PPC::QFRCRegClass); 15057 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15058 return std::make_pair(0U, &PPC::QSRCRegClass); 15059 } 15060 break; 15061 case 'v': 15062 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15063 return std::make_pair(0U, &PPC::QFRCRegClass); 15064 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15065 return std::make_pair(0U, &PPC::QSRCRegClass); 15066 if (Subtarget.hasAltivec()) 15067 return std::make_pair(0U, &PPC::VRRCRegClass); 15068 break; 15069 case 'y': // crrc 15070 return std::make_pair(0U, &PPC::CRRCRegClass); 15071 } 15072 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15073 // An individual CR bit. 15074 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15075 } else if ((Constraint == "wa" || Constraint == "wd" || 15076 Constraint == "wf" || Constraint == "wi") && 15077 Subtarget.hasVSX()) { 15078 return std::make_pair(0U, &PPC::VSRCRegClass); 15079 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15080 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15081 return std::make_pair(0U, &PPC::VSSRCRegClass); 15082 else 15083 return std::make_pair(0U, &PPC::VSFRCRegClass); 15084 } 15085 15086 // If we name a VSX register, we can't defer to the base class because it 15087 // will not recognize the correct register (their names will be VSL{0-31} 15088 // and V{0-31} so they won't match). So we match them here. 15089 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15090 int VSNum = atoi(Constraint.data() + 3); 15091 assert(VSNum >= 0 && VSNum <= 63 && 15092 "Attempted to access a vsr out of range"); 15093 if (VSNum < 32) 15094 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15095 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15096 } 15097 std::pair<unsigned, const TargetRegisterClass *> R = 15098 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15099 15100 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15101 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15102 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15103 // register. 15104 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15105 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15106 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15107 PPC::GPRCRegClass.contains(R.first)) 15108 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15109 PPC::sub_32, &PPC::G8RCRegClass), 15110 &PPC::G8RCRegClass); 15111 15112 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15113 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15114 R.first = PPC::CR0; 15115 R.second = &PPC::CRRCRegClass; 15116 } 15117 15118 return R; 15119 } 15120 15121 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15122 /// vector. If it is invalid, don't add anything to Ops. 15123 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15124 std::string &Constraint, 15125 std::vector<SDValue>&Ops, 15126 SelectionDAG &DAG) const { 15127 SDValue Result; 15128 15129 // Only support length 1 constraints. 15130 if (Constraint.length() > 1) return; 15131 15132 char Letter = Constraint[0]; 15133 switch (Letter) { 15134 default: break; 15135 case 'I': 15136 case 'J': 15137 case 'K': 15138 case 'L': 15139 case 'M': 15140 case 'N': 15141 case 'O': 15142 case 'P': { 15143 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15144 if (!CST) return; // Must be an immediate to match. 15145 SDLoc dl(Op); 15146 int64_t Value = CST->getSExtValue(); 15147 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15148 // numbers are printed as such. 15149 switch (Letter) { 15150 default: llvm_unreachable("Unknown constraint letter!"); 15151 case 'I': // "I" is a signed 16-bit constant. 15152 if (isInt<16>(Value)) 15153 Result = DAG.getTargetConstant(Value, dl, TCVT); 15154 break; 15155 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15156 if (isShiftedUInt<16, 16>(Value)) 15157 Result = DAG.getTargetConstant(Value, dl, TCVT); 15158 break; 15159 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15160 if (isShiftedInt<16, 16>(Value)) 15161 Result = DAG.getTargetConstant(Value, dl, TCVT); 15162 break; 15163 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15164 if (isUInt<16>(Value)) 15165 Result = DAG.getTargetConstant(Value, dl, TCVT); 15166 break; 15167 case 'M': // "M" is a constant that is greater than 31. 15168 if (Value > 31) 15169 Result = DAG.getTargetConstant(Value, dl, TCVT); 15170 break; 15171 case 'N': // "N" is a positive constant that is an exact power of two. 15172 if (Value > 0 && isPowerOf2_64(Value)) 15173 Result = DAG.getTargetConstant(Value, dl, TCVT); 15174 break; 15175 case 'O': // "O" is the constant zero. 15176 if (Value == 0) 15177 Result = DAG.getTargetConstant(Value, dl, TCVT); 15178 break; 15179 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15180 if (isInt<16>(-Value)) 15181 Result = DAG.getTargetConstant(Value, dl, TCVT); 15182 break; 15183 } 15184 break; 15185 } 15186 } 15187 15188 if (Result.getNode()) { 15189 Ops.push_back(Result); 15190 return; 15191 } 15192 15193 // Handle standard constraint letters. 15194 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15195 } 15196 15197 // isLegalAddressingMode - Return true if the addressing mode represented 15198 // by AM is legal for this target, for a load/store of the specified type. 15199 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15200 const AddrMode &AM, Type *Ty, 15201 unsigned AS, Instruction *I) const { 15202 // PPC does not allow r+i addressing modes for vectors! 15203 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15204 return false; 15205 15206 // PPC allows a sign-extended 16-bit immediate field. 15207 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15208 return false; 15209 15210 // No global is ever allowed as a base. 15211 if (AM.BaseGV) 15212 return false; 15213 15214 // PPC only support r+r, 15215 switch (AM.Scale) { 15216 case 0: // "r+i" or just "i", depending on HasBaseReg. 15217 break; 15218 case 1: 15219 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15220 return false; 15221 // Otherwise we have r+r or r+i. 15222 break; 15223 case 2: 15224 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15225 return false; 15226 // Allow 2*r as r+r. 15227 break; 15228 default: 15229 // No other scales are supported. 15230 return false; 15231 } 15232 15233 return true; 15234 } 15235 15236 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15237 SelectionDAG &DAG) const { 15238 MachineFunction &MF = DAG.getMachineFunction(); 15239 MachineFrameInfo &MFI = MF.getFrameInfo(); 15240 MFI.setReturnAddressIsTaken(true); 15241 15242 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15243 return SDValue(); 15244 15245 SDLoc dl(Op); 15246 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15247 15248 // Make sure the function does not optimize away the store of the RA to 15249 // the stack. 15250 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15251 FuncInfo->setLRStoreRequired(); 15252 bool isPPC64 = Subtarget.isPPC64(); 15253 auto PtrVT = getPointerTy(MF.getDataLayout()); 15254 15255 if (Depth > 0) { 15256 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15257 SDValue Offset = 15258 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15259 isPPC64 ? MVT::i64 : MVT::i32); 15260 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15261 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15262 MachinePointerInfo()); 15263 } 15264 15265 // Just load the return address off the stack. 15266 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15267 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15268 MachinePointerInfo()); 15269 } 15270 15271 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15272 SelectionDAG &DAG) const { 15273 SDLoc dl(Op); 15274 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15275 15276 MachineFunction &MF = DAG.getMachineFunction(); 15277 MachineFrameInfo &MFI = MF.getFrameInfo(); 15278 MFI.setFrameAddressIsTaken(true); 15279 15280 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15281 bool isPPC64 = PtrVT == MVT::i64; 15282 15283 // Naked functions never have a frame pointer, and so we use r1. For all 15284 // other functions, this decision must be delayed until during PEI. 15285 unsigned FrameReg; 15286 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15287 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15288 else 15289 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15290 15291 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15292 PtrVT); 15293 while (Depth--) 15294 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15295 FrameAddr, MachinePointerInfo()); 15296 return FrameAddr; 15297 } 15298 15299 // FIXME? Maybe this could be a TableGen attribute on some registers and 15300 // this table could be generated automatically from RegInfo. 15301 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15302 const MachineFunction &MF) const { 15303 bool isPPC64 = Subtarget.isPPC64(); 15304 15305 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15306 if (!is64Bit && VT != LLT::scalar(32)) 15307 report_fatal_error("Invalid register global variable type"); 15308 15309 Register Reg = StringSwitch<Register>(RegName) 15310 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15311 .Case("r2", isPPC64 ? Register() : PPC::R2) 15312 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15313 .Default(Register()); 15314 15315 if (Reg) 15316 return Reg; 15317 report_fatal_error("Invalid register name global variable"); 15318 } 15319 15320 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15321 // 32-bit SVR4 ABI access everything as got-indirect. 15322 if (Subtarget.is32BitELFABI()) 15323 return true; 15324 15325 // AIX accesses everything indirectly through the TOC, which is similar to 15326 // the GOT. 15327 if (Subtarget.isAIXABI()) 15328 return true; 15329 15330 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15331 // If it is small or large code model, module locals are accessed 15332 // indirectly by loading their address from .toc/.got. 15333 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15334 return true; 15335 15336 // JumpTable and BlockAddress are accessed as got-indirect. 15337 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15338 return true; 15339 15340 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15341 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15342 15343 return false; 15344 } 15345 15346 bool 15347 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15348 // The PowerPC target isn't yet aware of offsets. 15349 return false; 15350 } 15351 15352 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15353 const CallInst &I, 15354 MachineFunction &MF, 15355 unsigned Intrinsic) const { 15356 switch (Intrinsic) { 15357 case Intrinsic::ppc_qpx_qvlfd: 15358 case Intrinsic::ppc_qpx_qvlfs: 15359 case Intrinsic::ppc_qpx_qvlfcd: 15360 case Intrinsic::ppc_qpx_qvlfcs: 15361 case Intrinsic::ppc_qpx_qvlfiwa: 15362 case Intrinsic::ppc_qpx_qvlfiwz: 15363 case Intrinsic::ppc_altivec_lvx: 15364 case Intrinsic::ppc_altivec_lvxl: 15365 case Intrinsic::ppc_altivec_lvebx: 15366 case Intrinsic::ppc_altivec_lvehx: 15367 case Intrinsic::ppc_altivec_lvewx: 15368 case Intrinsic::ppc_vsx_lxvd2x: 15369 case Intrinsic::ppc_vsx_lxvw4x: { 15370 EVT VT; 15371 switch (Intrinsic) { 15372 case Intrinsic::ppc_altivec_lvebx: 15373 VT = MVT::i8; 15374 break; 15375 case Intrinsic::ppc_altivec_lvehx: 15376 VT = MVT::i16; 15377 break; 15378 case Intrinsic::ppc_altivec_lvewx: 15379 VT = MVT::i32; 15380 break; 15381 case Intrinsic::ppc_vsx_lxvd2x: 15382 VT = MVT::v2f64; 15383 break; 15384 case Intrinsic::ppc_qpx_qvlfd: 15385 VT = MVT::v4f64; 15386 break; 15387 case Intrinsic::ppc_qpx_qvlfs: 15388 VT = MVT::v4f32; 15389 break; 15390 case Intrinsic::ppc_qpx_qvlfcd: 15391 VT = MVT::v2f64; 15392 break; 15393 case Intrinsic::ppc_qpx_qvlfcs: 15394 VT = MVT::v2f32; 15395 break; 15396 default: 15397 VT = MVT::v4i32; 15398 break; 15399 } 15400 15401 Info.opc = ISD::INTRINSIC_W_CHAIN; 15402 Info.memVT = VT; 15403 Info.ptrVal = I.getArgOperand(0); 15404 Info.offset = -VT.getStoreSize()+1; 15405 Info.size = 2*VT.getStoreSize()-1; 15406 Info.align = Align(1); 15407 Info.flags = MachineMemOperand::MOLoad; 15408 return true; 15409 } 15410 case Intrinsic::ppc_qpx_qvlfda: 15411 case Intrinsic::ppc_qpx_qvlfsa: 15412 case Intrinsic::ppc_qpx_qvlfcda: 15413 case Intrinsic::ppc_qpx_qvlfcsa: 15414 case Intrinsic::ppc_qpx_qvlfiwaa: 15415 case Intrinsic::ppc_qpx_qvlfiwza: { 15416 EVT VT; 15417 switch (Intrinsic) { 15418 case Intrinsic::ppc_qpx_qvlfda: 15419 VT = MVT::v4f64; 15420 break; 15421 case Intrinsic::ppc_qpx_qvlfsa: 15422 VT = MVT::v4f32; 15423 break; 15424 case Intrinsic::ppc_qpx_qvlfcda: 15425 VT = MVT::v2f64; 15426 break; 15427 case Intrinsic::ppc_qpx_qvlfcsa: 15428 VT = MVT::v2f32; 15429 break; 15430 default: 15431 VT = MVT::v4i32; 15432 break; 15433 } 15434 15435 Info.opc = ISD::INTRINSIC_W_CHAIN; 15436 Info.memVT = VT; 15437 Info.ptrVal = I.getArgOperand(0); 15438 Info.offset = 0; 15439 Info.size = VT.getStoreSize(); 15440 Info.align = Align(1); 15441 Info.flags = MachineMemOperand::MOLoad; 15442 return true; 15443 } 15444 case Intrinsic::ppc_qpx_qvstfd: 15445 case Intrinsic::ppc_qpx_qvstfs: 15446 case Intrinsic::ppc_qpx_qvstfcd: 15447 case Intrinsic::ppc_qpx_qvstfcs: 15448 case Intrinsic::ppc_qpx_qvstfiw: 15449 case Intrinsic::ppc_altivec_stvx: 15450 case Intrinsic::ppc_altivec_stvxl: 15451 case Intrinsic::ppc_altivec_stvebx: 15452 case Intrinsic::ppc_altivec_stvehx: 15453 case Intrinsic::ppc_altivec_stvewx: 15454 case Intrinsic::ppc_vsx_stxvd2x: 15455 case Intrinsic::ppc_vsx_stxvw4x: { 15456 EVT VT; 15457 switch (Intrinsic) { 15458 case Intrinsic::ppc_altivec_stvebx: 15459 VT = MVT::i8; 15460 break; 15461 case Intrinsic::ppc_altivec_stvehx: 15462 VT = MVT::i16; 15463 break; 15464 case Intrinsic::ppc_altivec_stvewx: 15465 VT = MVT::i32; 15466 break; 15467 case Intrinsic::ppc_vsx_stxvd2x: 15468 VT = MVT::v2f64; 15469 break; 15470 case Intrinsic::ppc_qpx_qvstfd: 15471 VT = MVT::v4f64; 15472 break; 15473 case Intrinsic::ppc_qpx_qvstfs: 15474 VT = MVT::v4f32; 15475 break; 15476 case Intrinsic::ppc_qpx_qvstfcd: 15477 VT = MVT::v2f64; 15478 break; 15479 case Intrinsic::ppc_qpx_qvstfcs: 15480 VT = MVT::v2f32; 15481 break; 15482 default: 15483 VT = MVT::v4i32; 15484 break; 15485 } 15486 15487 Info.opc = ISD::INTRINSIC_VOID; 15488 Info.memVT = VT; 15489 Info.ptrVal = I.getArgOperand(1); 15490 Info.offset = -VT.getStoreSize()+1; 15491 Info.size = 2*VT.getStoreSize()-1; 15492 Info.align = Align(1); 15493 Info.flags = MachineMemOperand::MOStore; 15494 return true; 15495 } 15496 case Intrinsic::ppc_qpx_qvstfda: 15497 case Intrinsic::ppc_qpx_qvstfsa: 15498 case Intrinsic::ppc_qpx_qvstfcda: 15499 case Intrinsic::ppc_qpx_qvstfcsa: 15500 case Intrinsic::ppc_qpx_qvstfiwa: { 15501 EVT VT; 15502 switch (Intrinsic) { 15503 case Intrinsic::ppc_qpx_qvstfda: 15504 VT = MVT::v4f64; 15505 break; 15506 case Intrinsic::ppc_qpx_qvstfsa: 15507 VT = MVT::v4f32; 15508 break; 15509 case Intrinsic::ppc_qpx_qvstfcda: 15510 VT = MVT::v2f64; 15511 break; 15512 case Intrinsic::ppc_qpx_qvstfcsa: 15513 VT = MVT::v2f32; 15514 break; 15515 default: 15516 VT = MVT::v4i32; 15517 break; 15518 } 15519 15520 Info.opc = ISD::INTRINSIC_VOID; 15521 Info.memVT = VT; 15522 Info.ptrVal = I.getArgOperand(1); 15523 Info.offset = 0; 15524 Info.size = VT.getStoreSize(); 15525 Info.align = Align(1); 15526 Info.flags = MachineMemOperand::MOStore; 15527 return true; 15528 } 15529 default: 15530 break; 15531 } 15532 15533 return false; 15534 } 15535 15536 /// It returns EVT::Other if the type should be determined using generic 15537 /// target-independent logic. 15538 EVT PPCTargetLowering::getOptimalMemOpType( 15539 const MemOp &Op, const AttributeList &FuncAttributes) const { 15540 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15541 // When expanding a memset, require at least two QPX instructions to cover 15542 // the cost of loading the value to be stored from the constant pool. 15543 if (Subtarget.hasQPX() && Op.size() >= 32 && 15544 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15545 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15546 return MVT::v4f64; 15547 } 15548 15549 // We should use Altivec/VSX loads and stores when available. For unaligned 15550 // addresses, unaligned VSX loads are only fast starting with the P8. 15551 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15552 (Op.isAligned(Align(16)) || 15553 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15554 return MVT::v4i32; 15555 } 15556 15557 if (Subtarget.isPPC64()) { 15558 return MVT::i64; 15559 } 15560 15561 return MVT::i32; 15562 } 15563 15564 /// Returns true if it is beneficial to convert a load of a constant 15565 /// to just the constant itself. 15566 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15567 Type *Ty) const { 15568 assert(Ty->isIntegerTy()); 15569 15570 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15571 return !(BitSize == 0 || BitSize > 64); 15572 } 15573 15574 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15575 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15576 return false; 15577 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15578 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15579 return NumBits1 == 64 && NumBits2 == 32; 15580 } 15581 15582 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15583 if (!VT1.isInteger() || !VT2.isInteger()) 15584 return false; 15585 unsigned NumBits1 = VT1.getSizeInBits(); 15586 unsigned NumBits2 = VT2.getSizeInBits(); 15587 return NumBits1 == 64 && NumBits2 == 32; 15588 } 15589 15590 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15591 // Generally speaking, zexts are not free, but they are free when they can be 15592 // folded with other operations. 15593 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15594 EVT MemVT = LD->getMemoryVT(); 15595 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15596 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15597 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15598 LD->getExtensionType() == ISD::ZEXTLOAD)) 15599 return true; 15600 } 15601 15602 // FIXME: Add other cases... 15603 // - 32-bit shifts with a zext to i64 15604 // - zext after ctlz, bswap, etc. 15605 // - zext after and by a constant mask 15606 15607 return TargetLowering::isZExtFree(Val, VT2); 15608 } 15609 15610 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15611 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15612 "invalid fpext types"); 15613 // Extending to float128 is not free. 15614 if (DestVT == MVT::f128) 15615 return false; 15616 return true; 15617 } 15618 15619 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15620 return isInt<16>(Imm) || isUInt<16>(Imm); 15621 } 15622 15623 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15624 return isInt<16>(Imm) || isUInt<16>(Imm); 15625 } 15626 15627 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15628 unsigned, 15629 unsigned, 15630 MachineMemOperand::Flags, 15631 bool *Fast) const { 15632 if (DisablePPCUnaligned) 15633 return false; 15634 15635 // PowerPC supports unaligned memory access for simple non-vector types. 15636 // Although accessing unaligned addresses is not as efficient as accessing 15637 // aligned addresses, it is generally more efficient than manual expansion, 15638 // and generally only traps for software emulation when crossing page 15639 // boundaries. 15640 15641 if (!VT.isSimple()) 15642 return false; 15643 15644 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15645 return false; 15646 15647 if (VT.getSimpleVT().isVector()) { 15648 if (Subtarget.hasVSX()) { 15649 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15650 VT != MVT::v4f32 && VT != MVT::v4i32) 15651 return false; 15652 } else { 15653 return false; 15654 } 15655 } 15656 15657 if (VT == MVT::ppcf128) 15658 return false; 15659 15660 if (Fast) 15661 *Fast = true; 15662 15663 return true; 15664 } 15665 15666 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15667 EVT VT) const { 15668 return isFMAFasterThanFMulAndFAdd( 15669 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15670 } 15671 15672 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15673 Type *Ty) const { 15674 switch (Ty->getScalarType()->getTypeID()) { 15675 case Type::FloatTyID: 15676 case Type::DoubleTyID: 15677 return true; 15678 case Type::FP128TyID: 15679 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15680 default: 15681 return false; 15682 } 15683 } 15684 15685 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15686 // FIXME: add more patterns which are profitable to hoist. 15687 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15688 if (I->getOpcode() != Instruction::FMul) 15689 return true; 15690 15691 if (!I->hasOneUse()) 15692 return true; 15693 15694 Instruction *User = I->user_back(); 15695 assert(User && "A single use instruction with no uses."); 15696 15697 if (User->getOpcode() != Instruction::FSub && 15698 User->getOpcode() != Instruction::FAdd) 15699 return true; 15700 15701 const TargetOptions &Options = getTargetMachine().Options; 15702 const Function *F = I->getFunction(); 15703 const DataLayout &DL = F->getParent()->getDataLayout(); 15704 Type *Ty = User->getOperand(0)->getType(); 15705 15706 return !( 15707 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15708 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15709 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15710 } 15711 15712 const MCPhysReg * 15713 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15714 // LR is a callee-save register, but we must treat it as clobbered by any call 15715 // site. Hence we include LR in the scratch registers, which are in turn added 15716 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15717 // to CTR, which is used by any indirect call. 15718 static const MCPhysReg ScratchRegs[] = { 15719 PPC::X12, PPC::LR8, PPC::CTR8, 0 15720 }; 15721 15722 return ScratchRegs; 15723 } 15724 15725 Register PPCTargetLowering::getExceptionPointerRegister( 15726 const Constant *PersonalityFn) const { 15727 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15728 } 15729 15730 Register PPCTargetLowering::getExceptionSelectorRegister( 15731 const Constant *PersonalityFn) const { 15732 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15733 } 15734 15735 bool 15736 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15737 EVT VT , unsigned DefinedValues) const { 15738 if (VT == MVT::v2i64) 15739 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15740 15741 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15742 return true; 15743 15744 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15745 } 15746 15747 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15748 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15749 return TargetLowering::getSchedulingPreference(N); 15750 15751 return Sched::ILP; 15752 } 15753 15754 // Create a fast isel object. 15755 FastISel * 15756 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15757 const TargetLibraryInfo *LibInfo) const { 15758 return PPC::createFastISel(FuncInfo, LibInfo); 15759 } 15760 15761 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15762 if (!Subtarget.isPPC64()) return; 15763 15764 // Update IsSplitCSR in PPCFunctionInfo 15765 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15766 PFI->setIsSplitCSR(true); 15767 } 15768 15769 void PPCTargetLowering::insertCopiesSplitCSR( 15770 MachineBasicBlock *Entry, 15771 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15772 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15773 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15774 if (!IStart) 15775 return; 15776 15777 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15778 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15779 MachineBasicBlock::iterator MBBI = Entry->begin(); 15780 for (const MCPhysReg *I = IStart; *I; ++I) { 15781 const TargetRegisterClass *RC = nullptr; 15782 if (PPC::G8RCRegClass.contains(*I)) 15783 RC = &PPC::G8RCRegClass; 15784 else if (PPC::F8RCRegClass.contains(*I)) 15785 RC = &PPC::F8RCRegClass; 15786 else if (PPC::CRRCRegClass.contains(*I)) 15787 RC = &PPC::CRRCRegClass; 15788 else if (PPC::VRRCRegClass.contains(*I)) 15789 RC = &PPC::VRRCRegClass; 15790 else 15791 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15792 15793 Register NewVR = MRI->createVirtualRegister(RC); 15794 // Create copy from CSR to a virtual register. 15795 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15796 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15797 // nounwind. If we want to generalize this later, we may need to emit 15798 // CFI pseudo-instructions. 15799 assert(Entry->getParent()->getFunction().hasFnAttribute( 15800 Attribute::NoUnwind) && 15801 "Function should be nounwind in insertCopiesSplitCSR!"); 15802 Entry->addLiveIn(*I); 15803 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15804 .addReg(*I); 15805 15806 // Insert the copy-back instructions right before the terminator. 15807 for (auto *Exit : Exits) 15808 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15809 TII->get(TargetOpcode::COPY), *I) 15810 .addReg(NewVR); 15811 } 15812 } 15813 15814 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15815 bool PPCTargetLowering::useLoadStackGuardNode() const { 15816 if (!Subtarget.isTargetLinux()) 15817 return TargetLowering::useLoadStackGuardNode(); 15818 return true; 15819 } 15820 15821 // Override to disable global variable loading on Linux. 15822 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15823 if (!Subtarget.isTargetLinux()) 15824 return TargetLowering::insertSSPDeclarations(M); 15825 } 15826 15827 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15828 bool ForCodeSize) const { 15829 if (!VT.isSimple() || !Subtarget.hasVSX()) 15830 return false; 15831 15832 switch(VT.getSimpleVT().SimpleTy) { 15833 default: 15834 // For FP types that are currently not supported by PPC backend, return 15835 // false. Examples: f16, f80. 15836 return false; 15837 case MVT::f32: 15838 case MVT::f64: 15839 case MVT::ppcf128: 15840 return Imm.isPosZero(); 15841 } 15842 } 15843 15844 // For vector shift operation op, fold 15845 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15846 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15847 SelectionDAG &DAG) { 15848 SDValue N0 = N->getOperand(0); 15849 SDValue N1 = N->getOperand(1); 15850 EVT VT = N0.getValueType(); 15851 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15852 unsigned Opcode = N->getOpcode(); 15853 unsigned TargetOpcode; 15854 15855 switch (Opcode) { 15856 default: 15857 llvm_unreachable("Unexpected shift operation"); 15858 case ISD::SHL: 15859 TargetOpcode = PPCISD::SHL; 15860 break; 15861 case ISD::SRL: 15862 TargetOpcode = PPCISD::SRL; 15863 break; 15864 case ISD::SRA: 15865 TargetOpcode = PPCISD::SRA; 15866 break; 15867 } 15868 15869 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15870 N1->getOpcode() == ISD::AND) 15871 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15872 if (Mask->getZExtValue() == OpSizeInBits - 1) 15873 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15874 15875 return SDValue(); 15876 } 15877 15878 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15879 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15880 return Value; 15881 15882 SDValue N0 = N->getOperand(0); 15883 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15884 if (!Subtarget.isISA3_0() || 15885 N0.getOpcode() != ISD::SIGN_EXTEND || 15886 N0.getOperand(0).getValueType() != MVT::i32 || 15887 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15888 return SDValue(); 15889 15890 // We can't save an operation here if the value is already extended, and 15891 // the existing shift is easier to combine. 15892 SDValue ExtsSrc = N0.getOperand(0); 15893 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15894 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15895 return SDValue(); 15896 15897 SDLoc DL(N0); 15898 SDValue ShiftBy = SDValue(CN1, 0); 15899 // We want the shift amount to be i32 on the extswli, but the shift could 15900 // have an i64. 15901 if (ShiftBy.getValueType() == MVT::i64) 15902 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15903 15904 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15905 ShiftBy); 15906 } 15907 15908 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15909 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15910 return Value; 15911 15912 return SDValue(); 15913 } 15914 15915 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15916 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15917 return Value; 15918 15919 return SDValue(); 15920 } 15921 15922 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15923 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15924 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15925 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15926 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15927 const PPCSubtarget &Subtarget) { 15928 if (!Subtarget.isPPC64()) 15929 return SDValue(); 15930 15931 SDValue LHS = N->getOperand(0); 15932 SDValue RHS = N->getOperand(1); 15933 15934 auto isZextOfCompareWithConstant = [](SDValue Op) { 15935 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15936 Op.getValueType() != MVT::i64) 15937 return false; 15938 15939 SDValue Cmp = Op.getOperand(0); 15940 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15941 Cmp.getOperand(0).getValueType() != MVT::i64) 15942 return false; 15943 15944 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15945 int64_t NegConstant = 0 - Constant->getSExtValue(); 15946 // Due to the limitations of the addi instruction, 15947 // -C is required to be [-32768, 32767]. 15948 return isInt<16>(NegConstant); 15949 } 15950 15951 return false; 15952 }; 15953 15954 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15955 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15956 15957 // If there is a pattern, canonicalize a zext operand to the RHS. 15958 if (LHSHasPattern && !RHSHasPattern) 15959 std::swap(LHS, RHS); 15960 else if (!LHSHasPattern && !RHSHasPattern) 15961 return SDValue(); 15962 15963 SDLoc DL(N); 15964 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15965 SDValue Cmp = RHS.getOperand(0); 15966 SDValue Z = Cmp.getOperand(0); 15967 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15968 15969 assert(Constant && "Constant Should not be a null pointer."); 15970 int64_t NegConstant = 0 - Constant->getSExtValue(); 15971 15972 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15973 default: break; 15974 case ISD::SETNE: { 15975 // when C == 0 15976 // --> addze X, (addic Z, -1).carry 15977 // / 15978 // add X, (zext(setne Z, C))-- 15979 // \ when -32768 <= -C <= 32767 && C != 0 15980 // --> addze X, (addic (addi Z, -C), -1).carry 15981 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15982 DAG.getConstant(NegConstant, DL, MVT::i64)); 15983 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15984 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15985 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15986 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15987 SDValue(Addc.getNode(), 1)); 15988 } 15989 case ISD::SETEQ: { 15990 // when C == 0 15991 // --> addze X, (subfic Z, 0).carry 15992 // / 15993 // add X, (zext(sete Z, C))-- 15994 // \ when -32768 <= -C <= 32767 && C != 0 15995 // --> addze X, (subfic (addi Z, -C), 0).carry 15996 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15997 DAG.getConstant(NegConstant, DL, MVT::i64)); 15998 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15999 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16000 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16001 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16002 SDValue(Subc.getNode(), 1)); 16003 } 16004 } 16005 16006 return SDValue(); 16007 } 16008 16009 // Transform 16010 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16011 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16012 // In this case both C1 and C2 must be known constants. 16013 // C1+C2 must fit into a 34 bit signed integer. 16014 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16015 const PPCSubtarget &Subtarget) { 16016 if (!Subtarget.isUsingPCRelativeCalls()) 16017 return SDValue(); 16018 16019 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16020 // If we find that node try to cast the Global Address and the Constant. 16021 SDValue LHS = N->getOperand(0); 16022 SDValue RHS = N->getOperand(1); 16023 16024 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16025 std::swap(LHS, RHS); 16026 16027 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16028 return SDValue(); 16029 16030 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16031 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16032 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16033 16034 // Check that both casts succeeded. 16035 if (!GSDN || !ConstNode) 16036 return SDValue(); 16037 16038 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16039 SDLoc DL(GSDN); 16040 16041 // The signed int offset needs to fit in 34 bits. 16042 if (!isInt<34>(NewOffset)) 16043 return SDValue(); 16044 16045 // The new global address is a copy of the old global address except 16046 // that it has the updated Offset. 16047 SDValue GA = 16048 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16049 NewOffset, GSDN->getTargetFlags()); 16050 SDValue MatPCRel = 16051 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16052 return MatPCRel; 16053 } 16054 16055 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16056 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16057 return Value; 16058 16059 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16060 return Value; 16061 16062 return SDValue(); 16063 } 16064 16065 // Detect TRUNCATE operations on bitcasts of float128 values. 16066 // What we are looking for here is the situtation where we extract a subset 16067 // of bits from a 128 bit float. 16068 // This can be of two forms: 16069 // 1) BITCAST of f128 feeding TRUNCATE 16070 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16071 // The reason this is required is because we do not have a legal i128 type 16072 // and so we want to prevent having to store the f128 and then reload part 16073 // of it. 16074 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16075 DAGCombinerInfo &DCI) const { 16076 // If we are using CRBits then try that first. 16077 if (Subtarget.useCRBits()) { 16078 // Check if CRBits did anything and return that if it did. 16079 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16080 return CRTruncValue; 16081 } 16082 16083 SDLoc dl(N); 16084 SDValue Op0 = N->getOperand(0); 16085 16086 // Looking for a truncate of i128 to i64. 16087 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16088 return SDValue(); 16089 16090 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16091 16092 // SRL feeding TRUNCATE. 16093 if (Op0.getOpcode() == ISD::SRL) { 16094 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16095 // The right shift has to be by 64 bits. 16096 if (!ConstNode || ConstNode->getZExtValue() != 64) 16097 return SDValue(); 16098 16099 // Switch the element number to extract. 16100 EltToExtract = EltToExtract ? 0 : 1; 16101 // Update Op0 past the SRL. 16102 Op0 = Op0.getOperand(0); 16103 } 16104 16105 // BITCAST feeding a TRUNCATE possibly via SRL. 16106 if (Op0.getOpcode() == ISD::BITCAST && 16107 Op0.getValueType() == MVT::i128 && 16108 Op0.getOperand(0).getValueType() == MVT::f128) { 16109 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16110 return DCI.DAG.getNode( 16111 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16112 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16113 } 16114 return SDValue(); 16115 } 16116 16117 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16118 SelectionDAG &DAG = DCI.DAG; 16119 16120 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16121 if (!ConstOpOrElement) 16122 return SDValue(); 16123 16124 // An imul is usually smaller than the alternative sequence for legal type. 16125 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16126 isOperationLegal(ISD::MUL, N->getValueType(0))) 16127 return SDValue(); 16128 16129 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16130 switch (this->Subtarget.getCPUDirective()) { 16131 default: 16132 // TODO: enhance the condition for subtarget before pwr8 16133 return false; 16134 case PPC::DIR_PWR8: 16135 // type mul add shl 16136 // scalar 4 1 1 16137 // vector 7 2 2 16138 return true; 16139 case PPC::DIR_PWR9: 16140 case PPC::DIR_PWR_FUTURE: 16141 // type mul add shl 16142 // scalar 5 2 2 16143 // vector 7 2 2 16144 16145 // The cycle RATIO of related operations are showed as a table above. 16146 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16147 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16148 // are 4, it is always profitable; but for 3 instrs patterns 16149 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16150 // So we should only do it for vector type. 16151 return IsAddOne && IsNeg ? VT.isVector() : true; 16152 } 16153 }; 16154 16155 EVT VT = N->getValueType(0); 16156 SDLoc DL(N); 16157 16158 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16159 bool IsNeg = MulAmt.isNegative(); 16160 APInt MulAmtAbs = MulAmt.abs(); 16161 16162 if ((MulAmtAbs - 1).isPowerOf2()) { 16163 // (mul x, 2^N + 1) => (add (shl x, N), x) 16164 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16165 16166 if (!IsProfitable(IsNeg, true, VT)) 16167 return SDValue(); 16168 16169 SDValue Op0 = N->getOperand(0); 16170 SDValue Op1 = 16171 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16172 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16173 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16174 16175 if (!IsNeg) 16176 return Res; 16177 16178 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16179 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16180 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16181 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16182 16183 if (!IsProfitable(IsNeg, false, VT)) 16184 return SDValue(); 16185 16186 SDValue Op0 = N->getOperand(0); 16187 SDValue Op1 = 16188 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16189 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16190 16191 if (!IsNeg) 16192 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16193 else 16194 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16195 16196 } else { 16197 return SDValue(); 16198 } 16199 } 16200 16201 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16202 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16203 if (!Subtarget.is64BitELFABI()) 16204 return false; 16205 16206 // If not a tail call then no need to proceed. 16207 if (!CI->isTailCall()) 16208 return false; 16209 16210 // If sibling calls have been disabled and tail-calls aren't guaranteed 16211 // there is no reason to duplicate. 16212 auto &TM = getTargetMachine(); 16213 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16214 return false; 16215 16216 // Can't tail call a function called indirectly, or if it has variadic args. 16217 const Function *Callee = CI->getCalledFunction(); 16218 if (!Callee || Callee->isVarArg()) 16219 return false; 16220 16221 // Make sure the callee and caller calling conventions are eligible for tco. 16222 const Function *Caller = CI->getParent()->getParent(); 16223 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16224 CI->getCallingConv())) 16225 return false; 16226 16227 // If the function is local then we have a good chance at tail-calling it 16228 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16229 } 16230 16231 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16232 if (!Subtarget.hasVSX()) 16233 return false; 16234 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16235 return true; 16236 return VT == MVT::f32 || VT == MVT::f64 || 16237 VT == MVT::v4f32 || VT == MVT::v2f64; 16238 } 16239 16240 bool PPCTargetLowering:: 16241 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16242 const Value *Mask = AndI.getOperand(1); 16243 // If the mask is suitable for andi. or andis. we should sink the and. 16244 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16245 // Can't handle constants wider than 64-bits. 16246 if (CI->getBitWidth() > 64) 16247 return false; 16248 int64_t ConstVal = CI->getZExtValue(); 16249 return isUInt<16>(ConstVal) || 16250 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16251 } 16252 16253 // For non-constant masks, we can always use the record-form and. 16254 return true; 16255 } 16256 16257 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16258 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16259 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16260 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16261 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16262 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16263 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16264 assert(Subtarget.hasP9Altivec() && 16265 "Only combine this when P9 altivec supported!"); 16266 EVT VT = N->getValueType(0); 16267 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16268 return SDValue(); 16269 16270 SelectionDAG &DAG = DCI.DAG; 16271 SDLoc dl(N); 16272 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16273 // Even for signed integers, if it's known to be positive (as signed 16274 // integer) due to zero-extended inputs. 16275 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16276 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16277 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16278 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16279 (SubOpcd1 == ISD::ZERO_EXTEND || 16280 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16281 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16282 N->getOperand(0)->getOperand(0), 16283 N->getOperand(0)->getOperand(1), 16284 DAG.getTargetConstant(0, dl, MVT::i32)); 16285 } 16286 16287 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16288 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16289 N->getOperand(0).hasOneUse()) { 16290 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16291 N->getOperand(0)->getOperand(0), 16292 N->getOperand(0)->getOperand(1), 16293 DAG.getTargetConstant(1, dl, MVT::i32)); 16294 } 16295 } 16296 16297 return SDValue(); 16298 } 16299 16300 // For type v4i32/v8ii16/v16i8, transform 16301 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16302 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16303 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16304 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16305 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16306 DAGCombinerInfo &DCI) const { 16307 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16308 assert(Subtarget.hasP9Altivec() && 16309 "Only combine this when P9 altivec supported!"); 16310 16311 SelectionDAG &DAG = DCI.DAG; 16312 SDLoc dl(N); 16313 SDValue Cond = N->getOperand(0); 16314 SDValue TrueOpnd = N->getOperand(1); 16315 SDValue FalseOpnd = N->getOperand(2); 16316 EVT VT = N->getOperand(1).getValueType(); 16317 16318 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16319 FalseOpnd.getOpcode() != ISD::SUB) 16320 return SDValue(); 16321 16322 // ABSD only available for type v4i32/v8i16/v16i8 16323 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16324 return SDValue(); 16325 16326 // At least to save one more dependent computation 16327 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16328 return SDValue(); 16329 16330 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16331 16332 // Can only handle unsigned comparison here 16333 switch (CC) { 16334 default: 16335 return SDValue(); 16336 case ISD::SETUGT: 16337 case ISD::SETUGE: 16338 break; 16339 case ISD::SETULT: 16340 case ISD::SETULE: 16341 std::swap(TrueOpnd, FalseOpnd); 16342 break; 16343 } 16344 16345 SDValue CmpOpnd1 = Cond.getOperand(0); 16346 SDValue CmpOpnd2 = Cond.getOperand(1); 16347 16348 // SETCC CmpOpnd1 CmpOpnd2 cond 16349 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16350 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16351 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16352 TrueOpnd.getOperand(1) == CmpOpnd2 && 16353 FalseOpnd.getOperand(0) == CmpOpnd2 && 16354 FalseOpnd.getOperand(1) == CmpOpnd1) { 16355 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16356 CmpOpnd1, CmpOpnd2, 16357 DAG.getTargetConstant(0, dl, MVT::i32)); 16358 } 16359 16360 return SDValue(); 16361 } 16362