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/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/CallSite.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/Module.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/MC/MCExpr.h" 73 #include "llvm/MC/MCRegisterInfo.h" 74 #include "llvm/Support/AtomicOrdering.h" 75 #include "llvm/Support/BranchProbability.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CodeGen.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/Format.h" 83 #include "llvm/Support/KnownBits.h" 84 #include "llvm/Support/MachineValueType.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <iterator> 93 #include <list> 94 #include <utility> 95 #include <vector> 96 97 using namespace llvm; 98 99 #define DEBUG_TYPE "ppc-lowering" 100 101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 103 104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisableSCO("disable-ppc-sco", 111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 112 113 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 114 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 115 116 STATISTIC(NumTailCalls, "Number of tail calls"); 117 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 118 119 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 120 121 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 122 123 // FIXME: Remove this once the bug has been fixed! 124 extern cl::opt<bool> ANDIGlueBug; 125 126 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 127 const PPCSubtarget &STI) 128 : TargetLowering(TM), Subtarget(STI) { 129 // Use _setjmp/_longjmp instead of setjmp/longjmp. 130 setUseUnderscoreSetJmp(true); 131 setUseUnderscoreLongJmp(true); 132 133 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 134 // arguments are at least 4/8 bytes aligned. 135 bool isPPC64 = Subtarget.isPPC64(); 136 setMinStackArgumentAlignment(isPPC64 ? 8:4); 137 138 // Set up the register classes. 139 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 140 if (!useSoftFloat()) { 141 if (hasSPE()) { 142 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 143 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 144 } else { 145 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 146 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 147 } 148 } 149 150 // Match BITREVERSE to customized fast code sequence in the td file. 151 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 152 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 153 154 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 155 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 156 157 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 158 for (MVT VT : MVT::integer_valuetypes()) { 159 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 160 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 161 } 162 163 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 164 165 // PowerPC has pre-inc load and store's. 166 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 167 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 168 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 169 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 170 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 174 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 175 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 176 if (!Subtarget.hasSPE()) { 177 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 178 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 181 } 182 183 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 184 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 185 for (MVT VT : ScalarIntVTs) { 186 setOperationAction(ISD::ADDC, VT, Legal); 187 setOperationAction(ISD::ADDE, VT, Legal); 188 setOperationAction(ISD::SUBC, VT, Legal); 189 setOperationAction(ISD::SUBE, VT, Legal); 190 } 191 192 if (Subtarget.useCRBits()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 194 195 if (isPPC64 || Subtarget.hasFPCVT()) { 196 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 197 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 198 isPPC64 ? MVT::i64 : MVT::i32); 199 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 200 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 201 isPPC64 ? MVT::i64 : MVT::i32); 202 } else { 203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 204 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 205 } 206 207 // PowerPC does not support direct load/store of condition registers. 208 setOperationAction(ISD::LOAD, MVT::i1, Custom); 209 setOperationAction(ISD::STORE, MVT::i1, Custom); 210 211 // FIXME: Remove this once the ANDI glue bug is fixed: 212 if (ANDIGlueBug) 213 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 214 215 for (MVT VT : MVT::integer_valuetypes()) { 216 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 217 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 218 setTruncStoreAction(VT, MVT::i1, Expand); 219 } 220 221 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 222 } 223 224 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 225 // PPC (the libcall is not available). 226 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 227 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 228 229 // We do not currently implement these libm ops for PowerPC. 230 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 231 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 232 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 233 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 234 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 235 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 236 237 // PowerPC has no SREM/UREM instructions unless we are on P9 238 // On P9 we may use a hardware instruction to compute the remainder. 239 // The instructions are not legalized directly because in the cases where the 240 // result of both the remainder and the division is required it is more 241 // efficient to compute the remainder from the result of the division rather 242 // than use the remainder instruction. 243 if (Subtarget.isISA3_0()) { 244 setOperationAction(ISD::SREM, MVT::i32, Custom); 245 setOperationAction(ISD::UREM, MVT::i32, Custom); 246 setOperationAction(ISD::SREM, MVT::i64, Custom); 247 setOperationAction(ISD::UREM, MVT::i64, Custom); 248 } else { 249 setOperationAction(ISD::SREM, MVT::i32, Expand); 250 setOperationAction(ISD::UREM, MVT::i32, Expand); 251 setOperationAction(ISD::SREM, MVT::i64, Expand); 252 setOperationAction(ISD::UREM, MVT::i64, Expand); 253 } 254 255 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 256 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 257 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 258 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 259 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 261 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 262 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 263 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 264 265 // We don't support sin/cos/sqrt/fmod/pow 266 setOperationAction(ISD::FSIN , MVT::f64, Expand); 267 setOperationAction(ISD::FCOS , MVT::f64, Expand); 268 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 269 setOperationAction(ISD::FREM , MVT::f64, Expand); 270 setOperationAction(ISD::FPOW , MVT::f64, Expand); 271 setOperationAction(ISD::FSIN , MVT::f32, Expand); 272 setOperationAction(ISD::FCOS , MVT::f32, Expand); 273 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 274 setOperationAction(ISD::FREM , MVT::f32, Expand); 275 setOperationAction(ISD::FPOW , MVT::f32, Expand); 276 if (Subtarget.hasSPE()) { 277 setOperationAction(ISD::FMA , MVT::f64, Expand); 278 setOperationAction(ISD::FMA , MVT::f32, Expand); 279 } else { 280 setOperationAction(ISD::FMA , MVT::f64, Legal); 281 setOperationAction(ISD::FMA , MVT::f32, Legal); 282 } 283 284 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 285 286 // If we're enabling GP optimizations, use hardware square root 287 if (!Subtarget.hasFSQRT() && 288 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 289 Subtarget.hasFRE())) 290 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 291 292 if (!Subtarget.hasFSQRT() && 293 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 294 Subtarget.hasFRES())) 295 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 296 297 if (Subtarget.hasFCPSGN()) { 298 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 299 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 300 } else { 301 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 302 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 303 } 304 305 if (Subtarget.hasFPRND()) { 306 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 307 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 308 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 309 setOperationAction(ISD::FROUND, MVT::f64, Legal); 310 311 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 312 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 313 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 314 setOperationAction(ISD::FROUND, MVT::f32, Legal); 315 } 316 317 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 318 // to speed up scalar BSWAP64. 319 // CTPOP or CTTZ were introduced in P8/P9 respectively 320 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 321 if (Subtarget.hasP9Vector()) 322 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 323 else 324 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 325 if (Subtarget.isISA3_0()) { 326 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 327 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 328 } else { 329 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 330 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 331 } 332 333 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 334 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 335 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 336 } else { 337 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 338 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 339 } 340 341 // PowerPC does not have ROTR 342 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 343 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 344 345 if (!Subtarget.useCRBits()) { 346 // PowerPC does not have Select 347 setOperationAction(ISD::SELECT, MVT::i32, Expand); 348 setOperationAction(ISD::SELECT, MVT::i64, Expand); 349 setOperationAction(ISD::SELECT, MVT::f32, Expand); 350 setOperationAction(ISD::SELECT, MVT::f64, Expand); 351 } 352 353 // PowerPC wants to turn select_cc of FP into fsel when possible. 354 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 356 357 // PowerPC wants to optimize integer setcc a bit 358 if (!Subtarget.useCRBits()) 359 setOperationAction(ISD::SETCC, MVT::i32, Custom); 360 361 // PowerPC does not have BRCOND which requires SetCC 362 if (!Subtarget.useCRBits()) 363 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 364 365 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 366 367 if (Subtarget.hasSPE()) { 368 // SPE has built-in conversions 369 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 370 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 371 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 372 } else { 373 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 374 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 375 376 // PowerPC does not have [U|S]INT_TO_FP 377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 379 } 380 381 if (Subtarget.hasDirectMove() && isPPC64) { 382 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 383 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 384 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 385 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 386 } else { 387 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 388 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 389 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 390 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 391 } 392 393 // We cannot sextinreg(i1). Expand to shifts. 394 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 395 396 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 397 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 398 // support continuation, user-level threading, and etc.. As a result, no 399 // other SjLj exception interfaces are implemented and please don't build 400 // your own exception handling based on them. 401 // LLVM/Clang supports zero-cost DWARF exception handling. 402 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 403 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 404 405 // We want to legalize GlobalAddress and ConstantPool nodes into the 406 // appropriate instructions to materialize the address. 407 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 408 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 409 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 410 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 411 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 412 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 413 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 414 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 415 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 416 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 417 418 // TRAP is legal. 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 421 // TRAMPOLINE is custom lowered. 422 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 423 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 424 425 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 426 setOperationAction(ISD::VASTART , MVT::Other, Custom); 427 428 if (Subtarget.isSVR4ABI()) { 429 if (isPPC64) { 430 // VAARG always uses double-word chunks, so promote anything smaller. 431 setOperationAction(ISD::VAARG, MVT::i1, Promote); 432 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 433 setOperationAction(ISD::VAARG, MVT::i8, Promote); 434 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 435 setOperationAction(ISD::VAARG, MVT::i16, Promote); 436 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 437 setOperationAction(ISD::VAARG, MVT::i32, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::Other, Expand); 440 } else { 441 // VAARG is custom lowered with the 32-bit SVR4 ABI. 442 setOperationAction(ISD::VAARG, MVT::Other, Custom); 443 setOperationAction(ISD::VAARG, MVT::i64, Custom); 444 } 445 } else 446 setOperationAction(ISD::VAARG, MVT::Other, Expand); 447 448 if (Subtarget.isSVR4ABI() && !isPPC64) 449 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 450 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 451 else 452 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 453 454 // Use the default implementation. 455 setOperationAction(ISD::VAEND , MVT::Other, Expand); 456 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 457 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 458 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 459 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 460 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 461 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 462 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 463 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 464 465 // We want to custom lower some of our intrinsics. 466 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 467 468 // To handle counter-based loop conditions. 469 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 470 471 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 475 476 // Comparisons that require checking two conditions. 477 if (Subtarget.hasSPE()) { 478 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 479 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 480 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 481 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 482 } 483 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 484 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 485 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 486 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 487 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 495 496 if (Subtarget.has64BitSupport()) { 497 // They also have instructions for converting between i64 and fp. 498 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 499 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 500 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 501 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 502 // This is just the low 32 bits of a (signed) fp->i64 conversion. 503 // We cannot do this with Promote because i64 is not a legal type. 504 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 505 506 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 507 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 508 } else { 509 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 510 if (Subtarget.hasSPE()) 511 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 512 else 513 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 514 } 515 516 // With the instructions enabled under FPCVT, we can do everything. 517 if (Subtarget.hasFPCVT()) { 518 if (Subtarget.has64BitSupport()) { 519 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 520 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 521 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 522 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 523 } 524 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 529 } 530 531 if (Subtarget.use64BitRegs()) { 532 // 64-bit PowerPC implementations can support i64 types directly 533 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 534 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 535 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 536 // 64-bit PowerPC wants to expand i128 shifts itself. 537 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 538 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 539 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 540 } else { 541 // 32-bit PowerPC wants to expand i64 shifts itself. 542 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 543 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 544 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 545 } 546 547 if (Subtarget.hasAltivec()) { 548 // First set operation action for all vector types to expand. Then we 549 // will selectively turn on ones that can be effectively codegen'd. 550 for (MVT VT : MVT::vector_valuetypes()) { 551 // add/sub are legal for all supported vector VT's. 552 setOperationAction(ISD::ADD, VT, Legal); 553 setOperationAction(ISD::SUB, VT, Legal); 554 555 // Vector instructions introduced in P8 556 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 557 setOperationAction(ISD::CTPOP, VT, Legal); 558 setOperationAction(ISD::CTLZ, VT, Legal); 559 } 560 else { 561 setOperationAction(ISD::CTPOP, VT, Expand); 562 setOperationAction(ISD::CTLZ, VT, Expand); 563 } 564 565 // Vector instructions introduced in P9 566 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 567 setOperationAction(ISD::CTTZ, VT, Legal); 568 else 569 setOperationAction(ISD::CTTZ, VT, Expand); 570 571 // We promote all shuffles to v16i8. 572 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 573 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 574 575 // We promote all non-typed operations to v4i32. 576 setOperationAction(ISD::AND , VT, Promote); 577 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 578 setOperationAction(ISD::OR , VT, Promote); 579 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 580 setOperationAction(ISD::XOR , VT, Promote); 581 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 582 setOperationAction(ISD::LOAD , VT, Promote); 583 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 584 setOperationAction(ISD::SELECT, VT, Promote); 585 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 586 setOperationAction(ISD::VSELECT, VT, Legal); 587 setOperationAction(ISD::SELECT_CC, VT, Promote); 588 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 589 setOperationAction(ISD::STORE, VT, Promote); 590 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 591 592 // No other operations are legal. 593 setOperationAction(ISD::MUL , VT, Expand); 594 setOperationAction(ISD::SDIV, VT, Expand); 595 setOperationAction(ISD::SREM, VT, Expand); 596 setOperationAction(ISD::UDIV, VT, Expand); 597 setOperationAction(ISD::UREM, VT, Expand); 598 setOperationAction(ISD::FDIV, VT, Expand); 599 setOperationAction(ISD::FREM, VT, Expand); 600 setOperationAction(ISD::FNEG, VT, Expand); 601 setOperationAction(ISD::FSQRT, VT, Expand); 602 setOperationAction(ISD::FLOG, VT, Expand); 603 setOperationAction(ISD::FLOG10, VT, Expand); 604 setOperationAction(ISD::FLOG2, VT, Expand); 605 setOperationAction(ISD::FEXP, VT, Expand); 606 setOperationAction(ISD::FEXP2, VT, Expand); 607 setOperationAction(ISD::FSIN, VT, Expand); 608 setOperationAction(ISD::FCOS, VT, Expand); 609 setOperationAction(ISD::FABS, VT, Expand); 610 setOperationAction(ISD::FFLOOR, VT, Expand); 611 setOperationAction(ISD::FCEIL, VT, Expand); 612 setOperationAction(ISD::FTRUNC, VT, Expand); 613 setOperationAction(ISD::FRINT, VT, Expand); 614 setOperationAction(ISD::FNEARBYINT, VT, Expand); 615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 616 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 617 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 618 setOperationAction(ISD::MULHU, VT, Expand); 619 setOperationAction(ISD::MULHS, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UDIVREM, VT, Expand); 623 setOperationAction(ISD::SDIVREM, VT, Expand); 624 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 625 setOperationAction(ISD::FPOW, VT, Expand); 626 setOperationAction(ISD::BSWAP, VT, Expand); 627 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 628 setOperationAction(ISD::ROTL, VT, Expand); 629 setOperationAction(ISD::ROTR, VT, Expand); 630 631 for (MVT InnerVT : MVT::vector_valuetypes()) { 632 setTruncStoreAction(VT, InnerVT, Expand); 633 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 634 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 635 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 636 } 637 } 638 639 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 640 setOperationAction(ISD::ABS, VT, Custom); 641 642 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 643 // with merges, splats, etc. 644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 645 646 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 647 // are cheap, so handle them before they get expanded to scalar. 648 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 649 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 650 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 651 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 652 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 653 654 setOperationAction(ISD::AND , MVT::v4i32, Legal); 655 setOperationAction(ISD::OR , MVT::v4i32, Legal); 656 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 657 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 658 setOperationAction(ISD::SELECT, MVT::v4i32, 659 Subtarget.useCRBits() ? Legal : Expand); 660 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 661 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 663 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 664 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 665 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 666 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 667 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 668 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 669 670 // Without hasP8Altivec set, v2i64 SMAX isn't available. 671 // But ABS custom lowering requires SMAX support. 672 if (!Subtarget.hasP8Altivec()) 673 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 674 675 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 676 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 677 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 678 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 679 680 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 681 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 682 683 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 684 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 685 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 686 } 687 688 if (Subtarget.hasP8Altivec()) 689 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 690 else 691 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 692 693 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 694 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 695 696 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 697 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 698 699 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 700 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 701 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 702 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 703 704 // Altivec does not contain unordered floating-point compare instructions 705 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 706 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 707 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 708 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 709 710 if (Subtarget.hasVSX()) { 711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 713 if (Subtarget.hasP8Vector()) { 714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 716 } 717 if (Subtarget.hasDirectMove() && isPPC64) { 718 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 719 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 722 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 724 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 725 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 726 } 727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 728 729 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 730 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 731 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 732 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 733 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 734 735 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 736 737 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 738 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 739 740 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 741 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 742 743 // Share the Altivec comparison restrictions. 744 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 745 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 746 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 747 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 748 749 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 750 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 751 752 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 753 754 if (Subtarget.hasP8Vector()) 755 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 756 757 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 758 759 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 760 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 761 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 762 763 if (Subtarget.hasP8Altivec()) { 764 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 765 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 766 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 767 768 // 128 bit shifts can be accomplished via 3 instructions for SHL and 769 // SRL, but not for SRA because of the instructions available: 770 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 771 // doing 772 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 773 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 774 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 775 776 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 777 } 778 else { 779 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 780 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 781 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 782 783 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 784 785 // VSX v2i64 only supports non-arithmetic operations. 786 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 787 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 788 } 789 790 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 791 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 792 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 793 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 794 795 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 796 797 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 798 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 799 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 800 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 801 802 // Custom handling for partial vectors of integers converted to 803 // floating point. We already have optimal handling for v2i32 through 804 // the DAG combine, so those aren't necessary. 805 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 806 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 807 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 808 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 809 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 810 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 811 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 812 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 813 814 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 815 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 816 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 817 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 818 819 if (Subtarget.hasDirectMove()) 820 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 821 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 822 823 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 824 } 825 826 if (Subtarget.hasP8Altivec()) { 827 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 828 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 829 } 830 831 if (Subtarget.hasP9Vector()) { 832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 834 835 // 128 bit shifts can be accomplished via 3 instructions for SHL and 836 // SRL, but not for SRA because of the instructions available: 837 // VS{RL} and VS{RL}O. 838 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 839 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 840 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 841 842 if (EnableQuadPrecision) { 843 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 844 setOperationAction(ISD::FADD, MVT::f128, Legal); 845 setOperationAction(ISD::FSUB, MVT::f128, Legal); 846 setOperationAction(ISD::FDIV, MVT::f128, Legal); 847 setOperationAction(ISD::FMUL, MVT::f128, Legal); 848 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 849 // No extending loads to f128 on PPC. 850 for (MVT FPT : MVT::fp_valuetypes()) 851 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 852 setOperationAction(ISD::FMA, MVT::f128, Legal); 853 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 854 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 855 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 856 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 857 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 858 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 859 860 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 861 setOperationAction(ISD::FRINT, MVT::f128, Legal); 862 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 863 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 864 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 865 setOperationAction(ISD::FROUND, MVT::f128, Legal); 866 867 setOperationAction(ISD::SELECT, MVT::f128, Expand); 868 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 869 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 870 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 871 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 872 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 873 // No implementation for these ops for PowerPC. 874 setOperationAction(ISD::FSIN , MVT::f128, Expand); 875 setOperationAction(ISD::FCOS , MVT::f128, Expand); 876 setOperationAction(ISD::FPOW, MVT::f128, Expand); 877 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 878 setOperationAction(ISD::FREM, MVT::f128, Expand); 879 } 880 881 } 882 883 if (Subtarget.hasP9Altivec()) { 884 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 886 } 887 } 888 889 if (Subtarget.hasQPX()) { 890 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 891 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 892 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 893 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 894 895 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 896 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 897 898 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 899 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 900 901 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 902 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 903 904 if (!Subtarget.useCRBits()) 905 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 906 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 907 908 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 909 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 910 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 911 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 912 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 915 916 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 917 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 918 919 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 920 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 921 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 922 923 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 924 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 925 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 926 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 927 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 928 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 929 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 930 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 931 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 932 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 933 934 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 935 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 936 937 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 938 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 939 940 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 941 942 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 945 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 946 947 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 948 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 949 950 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 951 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 952 953 if (!Subtarget.useCRBits()) 954 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 955 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 956 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 958 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 959 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 960 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 961 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 963 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 964 965 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 966 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 967 968 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 969 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 970 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 971 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 972 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 973 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 974 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 975 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 976 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 977 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 978 979 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 980 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 981 982 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 983 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 984 985 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 986 987 setOperationAction(ISD::AND , MVT::v4i1, Legal); 988 setOperationAction(ISD::OR , MVT::v4i1, Legal); 989 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 990 991 if (!Subtarget.useCRBits()) 992 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 993 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 994 995 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 996 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 997 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 999 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1000 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1001 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1002 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1003 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1004 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1005 1006 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1007 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1008 1009 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1010 1011 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1012 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1013 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1014 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1015 1016 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1017 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1018 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1020 1021 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1022 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1023 1024 // These need to set FE_INEXACT, and so cannot be vectorized here. 1025 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1026 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1027 1028 if (TM.Options.UnsafeFPMath) { 1029 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1030 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1031 1032 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1034 } else { 1035 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1036 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1037 1038 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1039 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1040 } 1041 } 1042 1043 if (Subtarget.has64BitSupport()) 1044 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1045 1046 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1047 1048 if (!isPPC64) { 1049 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1050 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1051 } 1052 1053 setBooleanContents(ZeroOrOneBooleanContent); 1054 1055 if (Subtarget.hasAltivec()) { 1056 // Altivec instructions set fields to all zeros or all ones. 1057 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1058 } 1059 1060 if (!isPPC64) { 1061 // These libcalls are not available in 32-bit. 1062 setLibcallName(RTLIB::SHL_I128, nullptr); 1063 setLibcallName(RTLIB::SRL_I128, nullptr); 1064 setLibcallName(RTLIB::SRA_I128, nullptr); 1065 } 1066 1067 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1068 1069 // We have target-specific dag combine patterns for the following nodes: 1070 setTargetDAGCombine(ISD::ADD); 1071 setTargetDAGCombine(ISD::SHL); 1072 setTargetDAGCombine(ISD::SRA); 1073 setTargetDAGCombine(ISD::SRL); 1074 setTargetDAGCombine(ISD::MUL); 1075 setTargetDAGCombine(ISD::SINT_TO_FP); 1076 setTargetDAGCombine(ISD::BUILD_VECTOR); 1077 if (Subtarget.hasFPCVT()) 1078 setTargetDAGCombine(ISD::UINT_TO_FP); 1079 setTargetDAGCombine(ISD::LOAD); 1080 setTargetDAGCombine(ISD::STORE); 1081 setTargetDAGCombine(ISD::BR_CC); 1082 if (Subtarget.useCRBits()) 1083 setTargetDAGCombine(ISD::BRCOND); 1084 setTargetDAGCombine(ISD::BSWAP); 1085 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1086 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1087 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1088 1089 setTargetDAGCombine(ISD::SIGN_EXTEND); 1090 setTargetDAGCombine(ISD::ZERO_EXTEND); 1091 setTargetDAGCombine(ISD::ANY_EXTEND); 1092 1093 setTargetDAGCombine(ISD::TRUNCATE); 1094 1095 if (Subtarget.useCRBits()) { 1096 setTargetDAGCombine(ISD::TRUNCATE); 1097 setTargetDAGCombine(ISD::SETCC); 1098 setTargetDAGCombine(ISD::SELECT_CC); 1099 } 1100 1101 // Use reciprocal estimates. 1102 if (TM.Options.UnsafeFPMath) { 1103 setTargetDAGCombine(ISD::FDIV); 1104 setTargetDAGCombine(ISD::FSQRT); 1105 } 1106 1107 if (Subtarget.hasP9Altivec()) { 1108 setTargetDAGCombine(ISD::ABS); 1109 setTargetDAGCombine(ISD::VSELECT); 1110 } 1111 1112 // Darwin long double math library functions have $LDBL128 appended. 1113 if (Subtarget.isDarwin()) { 1114 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1115 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1116 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1117 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1118 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1119 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1120 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1121 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1122 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1123 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1124 } 1125 1126 if (EnableQuadPrecision) { 1127 setLibcallName(RTLIB::LOG_F128, "logf128"); 1128 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1129 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1130 setLibcallName(RTLIB::EXP_F128, "expf128"); 1131 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1132 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1133 setLibcallName(RTLIB::COS_F128, "cosf128"); 1134 setLibcallName(RTLIB::POW_F128, "powf128"); 1135 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1136 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1137 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1138 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1139 } 1140 1141 // With 32 condition bits, we don't need to sink (and duplicate) compares 1142 // aggressively in CodeGenPrep. 1143 if (Subtarget.useCRBits()) { 1144 setHasMultipleConditionRegisters(); 1145 setJumpIsExpensive(); 1146 } 1147 1148 setMinFunctionAlignment(2); 1149 if (Subtarget.isDarwin()) 1150 setPrefFunctionAlignment(4); 1151 1152 switch (Subtarget.getDarwinDirective()) { 1153 default: break; 1154 case PPC::DIR_970: 1155 case PPC::DIR_A2: 1156 case PPC::DIR_E500: 1157 case PPC::DIR_E500mc: 1158 case PPC::DIR_E5500: 1159 case PPC::DIR_PWR4: 1160 case PPC::DIR_PWR5: 1161 case PPC::DIR_PWR5X: 1162 case PPC::DIR_PWR6: 1163 case PPC::DIR_PWR6X: 1164 case PPC::DIR_PWR7: 1165 case PPC::DIR_PWR8: 1166 case PPC::DIR_PWR9: 1167 setPrefFunctionAlignment(4); 1168 setPrefLoopAlignment(4); 1169 break; 1170 } 1171 1172 if (Subtarget.enableMachineScheduler()) 1173 setSchedulingPreference(Sched::Source); 1174 else 1175 setSchedulingPreference(Sched::Hybrid); 1176 1177 computeRegisterProperties(STI.getRegisterInfo()); 1178 1179 // The Freescale cores do better with aggressive inlining of memcpy and 1180 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1181 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1182 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1183 MaxStoresPerMemset = 32; 1184 MaxStoresPerMemsetOptSize = 16; 1185 MaxStoresPerMemcpy = 32; 1186 MaxStoresPerMemcpyOptSize = 8; 1187 MaxStoresPerMemmove = 32; 1188 MaxStoresPerMemmoveOptSize = 8; 1189 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1190 // The A2 also benefits from (very) aggressive inlining of memcpy and 1191 // friends. The overhead of a the function call, even when warm, can be 1192 // over one hundred cycles. 1193 MaxStoresPerMemset = 128; 1194 MaxStoresPerMemcpy = 128; 1195 MaxStoresPerMemmove = 128; 1196 MaxLoadsPerMemcmp = 128; 1197 } else { 1198 MaxLoadsPerMemcmp = 8; 1199 MaxLoadsPerMemcmpOptSize = 4; 1200 } 1201 } 1202 1203 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1204 /// the desired ByVal argument alignment. 1205 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1206 unsigned MaxMaxAlign) { 1207 if (MaxAlign == MaxMaxAlign) 1208 return; 1209 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1210 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1211 MaxAlign = 32; 1212 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1213 MaxAlign = 16; 1214 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1215 unsigned EltAlign = 0; 1216 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1217 if (EltAlign > MaxAlign) 1218 MaxAlign = EltAlign; 1219 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1220 for (auto *EltTy : STy->elements()) { 1221 unsigned EltAlign = 0; 1222 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1223 if (EltAlign > MaxAlign) 1224 MaxAlign = EltAlign; 1225 if (MaxAlign == MaxMaxAlign) 1226 break; 1227 } 1228 } 1229 } 1230 1231 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1232 /// function arguments in the caller parameter area. 1233 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1234 const DataLayout &DL) const { 1235 // Darwin passes everything on 4 byte boundary. 1236 if (Subtarget.isDarwin()) 1237 return 4; 1238 1239 // 16byte and wider vectors are passed on 16byte boundary. 1240 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1241 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1242 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1243 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1244 return Align; 1245 } 1246 1247 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1248 CallingConv:: ID CC, 1249 EVT VT) const { 1250 if (Subtarget.hasSPE() && VT == MVT::f64) 1251 return 2; 1252 return PPCTargetLowering::getNumRegisters(Context, VT); 1253 } 1254 1255 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1256 CallingConv:: ID CC, 1257 EVT VT) const { 1258 if (Subtarget.hasSPE() && VT == MVT::f64) 1259 return MVT::i32; 1260 return PPCTargetLowering::getRegisterType(Context, VT); 1261 } 1262 1263 bool PPCTargetLowering::useSoftFloat() const { 1264 return Subtarget.useSoftFloat(); 1265 } 1266 1267 bool PPCTargetLowering::hasSPE() const { 1268 return Subtarget.hasSPE(); 1269 } 1270 1271 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1272 switch ((PPCISD::NodeType)Opcode) { 1273 case PPCISD::FIRST_NUMBER: break; 1274 case PPCISD::FSEL: return "PPCISD::FSEL"; 1275 case PPCISD::FCFID: return "PPCISD::FCFID"; 1276 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1277 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1278 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1279 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1280 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1281 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1282 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1283 case PPCISD::FP_TO_UINT_IN_VSR: 1284 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1285 case PPCISD::FP_TO_SINT_IN_VSR: 1286 return "PPCISD::FP_TO_SINT_IN_VSR"; 1287 case PPCISD::FRE: return "PPCISD::FRE"; 1288 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1289 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1290 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1291 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1292 case PPCISD::VPERM: return "PPCISD::VPERM"; 1293 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1294 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1295 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1296 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1297 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1298 case PPCISD::CMPB: return "PPCISD::CMPB"; 1299 case PPCISD::Hi: return "PPCISD::Hi"; 1300 case PPCISD::Lo: return "PPCISD::Lo"; 1301 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1302 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1303 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1304 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1305 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1306 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1307 case PPCISD::SRL: return "PPCISD::SRL"; 1308 case PPCISD::SRA: return "PPCISD::SRA"; 1309 case PPCISD::SHL: return "PPCISD::SHL"; 1310 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1311 case PPCISD::CALL: return "PPCISD::CALL"; 1312 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1313 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1314 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1315 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1316 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1317 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1318 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1319 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1320 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1321 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1322 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1323 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1324 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1325 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1326 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1327 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1328 case PPCISD::VCMP: return "PPCISD::VCMP"; 1329 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1330 case PPCISD::LBRX: return "PPCISD::LBRX"; 1331 case PPCISD::STBRX: return "PPCISD::STBRX"; 1332 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1333 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1334 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1335 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1336 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1337 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1338 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1339 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1340 case PPCISD::ST_VSR_SCAL_INT: 1341 return "PPCISD::ST_VSR_SCAL_INT"; 1342 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1343 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1344 case PPCISD::BDZ: return "PPCISD::BDZ"; 1345 case PPCISD::MFFS: return "PPCISD::MFFS"; 1346 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1347 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1348 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1349 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1350 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1351 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1352 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1353 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1354 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1355 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1356 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1357 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1358 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1359 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1360 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1361 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1362 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1363 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1364 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1365 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1366 case PPCISD::SC: return "PPCISD::SC"; 1367 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1368 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1369 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1370 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1371 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1372 case PPCISD::VABSD: return "PPCISD::VABSD"; 1373 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1374 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1375 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1376 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1377 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1378 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1379 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1380 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1381 } 1382 return nullptr; 1383 } 1384 1385 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1386 EVT VT) const { 1387 if (!VT.isVector()) 1388 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1389 1390 if (Subtarget.hasQPX()) 1391 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1392 1393 return VT.changeVectorElementTypeToInteger(); 1394 } 1395 1396 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1397 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1398 return true; 1399 } 1400 1401 //===----------------------------------------------------------------------===// 1402 // Node matching predicates, for use by the tblgen matching code. 1403 //===----------------------------------------------------------------------===// 1404 1405 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1406 static bool isFloatingPointZero(SDValue Op) { 1407 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1408 return CFP->getValueAPF().isZero(); 1409 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1410 // Maybe this has already been legalized into the constant pool? 1411 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1412 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1413 return CFP->getValueAPF().isZero(); 1414 } 1415 return false; 1416 } 1417 1418 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1419 /// true if Op is undef or if it matches the specified value. 1420 static bool isConstantOrUndef(int Op, int Val) { 1421 return Op < 0 || Op == Val; 1422 } 1423 1424 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1425 /// VPKUHUM instruction. 1426 /// The ShuffleKind distinguishes between big-endian operations with 1427 /// two different inputs (0), either-endian operations with two identical 1428 /// inputs (1), and little-endian operations with two different inputs (2). 1429 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1430 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1431 SelectionDAG &DAG) { 1432 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1433 if (ShuffleKind == 0) { 1434 if (IsLE) 1435 return false; 1436 for (unsigned i = 0; i != 16; ++i) 1437 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1438 return false; 1439 } else if (ShuffleKind == 2) { 1440 if (!IsLE) 1441 return false; 1442 for (unsigned i = 0; i != 16; ++i) 1443 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1444 return false; 1445 } else if (ShuffleKind == 1) { 1446 unsigned j = IsLE ? 0 : 1; 1447 for (unsigned i = 0; i != 8; ++i) 1448 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1449 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1450 return false; 1451 } 1452 return true; 1453 } 1454 1455 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1456 /// VPKUWUM instruction. 1457 /// The ShuffleKind distinguishes between big-endian operations with 1458 /// two different inputs (0), either-endian operations with two identical 1459 /// inputs (1), and little-endian operations with two different inputs (2). 1460 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1461 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1462 SelectionDAG &DAG) { 1463 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1464 if (ShuffleKind == 0) { 1465 if (IsLE) 1466 return false; 1467 for (unsigned i = 0; i != 16; i += 2) 1468 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1469 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1470 return false; 1471 } else if (ShuffleKind == 2) { 1472 if (!IsLE) 1473 return false; 1474 for (unsigned i = 0; i != 16; i += 2) 1475 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1476 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1477 return false; 1478 } else if (ShuffleKind == 1) { 1479 unsigned j = IsLE ? 0 : 2; 1480 for (unsigned i = 0; i != 8; i += 2) 1481 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1482 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1483 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1484 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1485 return false; 1486 } 1487 return true; 1488 } 1489 1490 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1491 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1492 /// current subtarget. 1493 /// 1494 /// The ShuffleKind distinguishes between big-endian operations with 1495 /// two different inputs (0), either-endian operations with two identical 1496 /// inputs (1), and little-endian operations with two different inputs (2). 1497 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1498 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1499 SelectionDAG &DAG) { 1500 const PPCSubtarget& Subtarget = 1501 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1502 if (!Subtarget.hasP8Vector()) 1503 return false; 1504 1505 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1506 if (ShuffleKind == 0) { 1507 if (IsLE) 1508 return false; 1509 for (unsigned i = 0; i != 16; i += 4) 1510 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1511 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1512 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1513 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1514 return false; 1515 } else if (ShuffleKind == 2) { 1516 if (!IsLE) 1517 return false; 1518 for (unsigned i = 0; i != 16; i += 4) 1519 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1520 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1521 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1522 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1523 return false; 1524 } else if (ShuffleKind == 1) { 1525 unsigned j = IsLE ? 0 : 4; 1526 for (unsigned i = 0; i != 8; i += 4) 1527 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1528 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1529 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1530 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1531 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1532 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1533 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1534 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1535 return false; 1536 } 1537 return true; 1538 } 1539 1540 /// isVMerge - Common function, used to match vmrg* shuffles. 1541 /// 1542 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1543 unsigned LHSStart, unsigned RHSStart) { 1544 if (N->getValueType(0) != MVT::v16i8) 1545 return false; 1546 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1547 "Unsupported merge size!"); 1548 1549 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1550 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1551 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1552 LHSStart+j+i*UnitSize) || 1553 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1554 RHSStart+j+i*UnitSize)) 1555 return false; 1556 } 1557 return true; 1558 } 1559 1560 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1561 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1562 /// The ShuffleKind distinguishes between big-endian merges with two 1563 /// different inputs (0), either-endian merges with two identical inputs (1), 1564 /// and little-endian merges with two different inputs (2). For the latter, 1565 /// the input operands are swapped (see PPCInstrAltivec.td). 1566 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1567 unsigned ShuffleKind, SelectionDAG &DAG) { 1568 if (DAG.getDataLayout().isLittleEndian()) { 1569 if (ShuffleKind == 1) // unary 1570 return isVMerge(N, UnitSize, 0, 0); 1571 else if (ShuffleKind == 2) // swapped 1572 return isVMerge(N, UnitSize, 0, 16); 1573 else 1574 return false; 1575 } else { 1576 if (ShuffleKind == 1) // unary 1577 return isVMerge(N, UnitSize, 8, 8); 1578 else if (ShuffleKind == 0) // normal 1579 return isVMerge(N, UnitSize, 8, 24); 1580 else 1581 return false; 1582 } 1583 } 1584 1585 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1586 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1587 /// The ShuffleKind distinguishes between big-endian merges with two 1588 /// different inputs (0), either-endian merges with two identical inputs (1), 1589 /// and little-endian merges with two different inputs (2). For the latter, 1590 /// the input operands are swapped (see PPCInstrAltivec.td). 1591 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1592 unsigned ShuffleKind, SelectionDAG &DAG) { 1593 if (DAG.getDataLayout().isLittleEndian()) { 1594 if (ShuffleKind == 1) // unary 1595 return isVMerge(N, UnitSize, 8, 8); 1596 else if (ShuffleKind == 2) // swapped 1597 return isVMerge(N, UnitSize, 8, 24); 1598 else 1599 return false; 1600 } else { 1601 if (ShuffleKind == 1) // unary 1602 return isVMerge(N, UnitSize, 0, 0); 1603 else if (ShuffleKind == 0) // normal 1604 return isVMerge(N, UnitSize, 0, 16); 1605 else 1606 return false; 1607 } 1608 } 1609 1610 /** 1611 * Common function used to match vmrgew and vmrgow shuffles 1612 * 1613 * The indexOffset determines whether to look for even or odd words in 1614 * the shuffle mask. This is based on the of the endianness of the target 1615 * machine. 1616 * - Little Endian: 1617 * - Use offset of 0 to check for odd elements 1618 * - Use offset of 4 to check for even elements 1619 * - Big Endian: 1620 * - Use offset of 0 to check for even elements 1621 * - Use offset of 4 to check for odd elements 1622 * A detailed description of the vector element ordering for little endian and 1623 * big endian can be found at 1624 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1625 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1626 * compiler differences mean to you 1627 * 1628 * The mask to the shuffle vector instruction specifies the indices of the 1629 * elements from the two input vectors to place in the result. The elements are 1630 * numbered in array-access order, starting with the first vector. These vectors 1631 * are always of type v16i8, thus each vector will contain 16 elements of size 1632 * 8. More info on the shuffle vector can be found in the 1633 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1634 * Language Reference. 1635 * 1636 * The RHSStartValue indicates whether the same input vectors are used (unary) 1637 * or two different input vectors are used, based on the following: 1638 * - If the instruction uses the same vector for both inputs, the range of the 1639 * indices will be 0 to 15. In this case, the RHSStart value passed should 1640 * be 0. 1641 * - If the instruction has two different vectors then the range of the 1642 * indices will be 0 to 31. In this case, the RHSStart value passed should 1643 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1644 * to 31 specify elements in the second vector). 1645 * 1646 * \param[in] N The shuffle vector SD Node to analyze 1647 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1648 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1649 * vector to the shuffle_vector instruction 1650 * \return true iff this shuffle vector represents an even or odd word merge 1651 */ 1652 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1653 unsigned RHSStartValue) { 1654 if (N->getValueType(0) != MVT::v16i8) 1655 return false; 1656 1657 for (unsigned i = 0; i < 2; ++i) 1658 for (unsigned j = 0; j < 4; ++j) 1659 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1660 i*RHSStartValue+j+IndexOffset) || 1661 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1662 i*RHSStartValue+j+IndexOffset+8)) 1663 return false; 1664 return true; 1665 } 1666 1667 /** 1668 * Determine if the specified shuffle mask is suitable for the vmrgew or 1669 * vmrgow instructions. 1670 * 1671 * \param[in] N The shuffle vector SD Node to analyze 1672 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1673 * \param[in] ShuffleKind Identify the type of merge: 1674 * - 0 = big-endian merge with two different inputs; 1675 * - 1 = either-endian merge with two identical inputs; 1676 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1677 * little-endian merges). 1678 * \param[in] DAG The current SelectionDAG 1679 * \return true iff this shuffle mask 1680 */ 1681 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1682 unsigned ShuffleKind, SelectionDAG &DAG) { 1683 if (DAG.getDataLayout().isLittleEndian()) { 1684 unsigned indexOffset = CheckEven ? 4 : 0; 1685 if (ShuffleKind == 1) // Unary 1686 return isVMerge(N, indexOffset, 0); 1687 else if (ShuffleKind == 2) // swapped 1688 return isVMerge(N, indexOffset, 16); 1689 else 1690 return false; 1691 } 1692 else { 1693 unsigned indexOffset = CheckEven ? 0 : 4; 1694 if (ShuffleKind == 1) // Unary 1695 return isVMerge(N, indexOffset, 0); 1696 else if (ShuffleKind == 0) // Normal 1697 return isVMerge(N, indexOffset, 16); 1698 else 1699 return false; 1700 } 1701 return false; 1702 } 1703 1704 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1705 /// amount, otherwise return -1. 1706 /// The ShuffleKind distinguishes between big-endian operations with two 1707 /// different inputs (0), either-endian operations with two identical inputs 1708 /// (1), and little-endian operations with two different inputs (2). For the 1709 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1710 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1711 SelectionDAG &DAG) { 1712 if (N->getValueType(0) != MVT::v16i8) 1713 return -1; 1714 1715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1716 1717 // Find the first non-undef value in the shuffle mask. 1718 unsigned i; 1719 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1720 /*search*/; 1721 1722 if (i == 16) return -1; // all undef. 1723 1724 // Otherwise, check to see if the rest of the elements are consecutively 1725 // numbered from this value. 1726 unsigned ShiftAmt = SVOp->getMaskElt(i); 1727 if (ShiftAmt < i) return -1; 1728 1729 ShiftAmt -= i; 1730 bool isLE = DAG.getDataLayout().isLittleEndian(); 1731 1732 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1733 // Check the rest of the elements to see if they are consecutive. 1734 for (++i; i != 16; ++i) 1735 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1736 return -1; 1737 } else if (ShuffleKind == 1) { 1738 // Check the rest of the elements to see if they are consecutive. 1739 for (++i; i != 16; ++i) 1740 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1741 return -1; 1742 } else 1743 return -1; 1744 1745 if (isLE) 1746 ShiftAmt = 16 - ShiftAmt; 1747 1748 return ShiftAmt; 1749 } 1750 1751 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1752 /// specifies a splat of a single element that is suitable for input to 1753 /// VSPLTB/VSPLTH/VSPLTW. 1754 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1755 assert(N->getValueType(0) == MVT::v16i8 && 1756 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1757 1758 // The consecutive indices need to specify an element, not part of two 1759 // different elements. So abandon ship early if this isn't the case. 1760 if (N->getMaskElt(0) % EltSize != 0) 1761 return false; 1762 1763 // This is a splat operation if each element of the permute is the same, and 1764 // if the value doesn't reference the second vector. 1765 unsigned ElementBase = N->getMaskElt(0); 1766 1767 // FIXME: Handle UNDEF elements too! 1768 if (ElementBase >= 16) 1769 return false; 1770 1771 // Check that the indices are consecutive, in the case of a multi-byte element 1772 // splatted with a v16i8 mask. 1773 for (unsigned i = 1; i != EltSize; ++i) 1774 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1775 return false; 1776 1777 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1778 if (N->getMaskElt(i) < 0) continue; 1779 for (unsigned j = 0; j != EltSize; ++j) 1780 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1781 return false; 1782 } 1783 return true; 1784 } 1785 1786 /// Check that the mask is shuffling N byte elements. Within each N byte 1787 /// element of the mask, the indices could be either in increasing or 1788 /// decreasing order as long as they are consecutive. 1789 /// \param[in] N the shuffle vector SD Node to analyze 1790 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1791 /// Word/DoubleWord/QuadWord). 1792 /// \param[in] StepLen the delta indices number among the N byte element, if 1793 /// the mask is in increasing/decreasing order then it is 1/-1. 1794 /// \return true iff the mask is shuffling N byte elements. 1795 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1796 int StepLen) { 1797 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1798 "Unexpected element width."); 1799 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1800 1801 unsigned NumOfElem = 16 / Width; 1802 unsigned MaskVal[16]; // Width is never greater than 16 1803 for (unsigned i = 0; i < NumOfElem; ++i) { 1804 MaskVal[0] = N->getMaskElt(i * Width); 1805 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1806 return false; 1807 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1808 return false; 1809 } 1810 1811 for (unsigned int j = 1; j < Width; ++j) { 1812 MaskVal[j] = N->getMaskElt(i * Width + j); 1813 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1814 return false; 1815 } 1816 } 1817 } 1818 1819 return true; 1820 } 1821 1822 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1823 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1824 if (!isNByteElemShuffleMask(N, 4, 1)) 1825 return false; 1826 1827 // Now we look at mask elements 0,4,8,12 1828 unsigned M0 = N->getMaskElt(0) / 4; 1829 unsigned M1 = N->getMaskElt(4) / 4; 1830 unsigned M2 = N->getMaskElt(8) / 4; 1831 unsigned M3 = N->getMaskElt(12) / 4; 1832 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1833 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1834 1835 // Below, let H and L be arbitrary elements of the shuffle mask 1836 // where H is in the range [4,7] and L is in the range [0,3]. 1837 // H, 1, 2, 3 or L, 5, 6, 7 1838 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1839 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1840 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1841 InsertAtByte = IsLE ? 12 : 0; 1842 Swap = M0 < 4; 1843 return true; 1844 } 1845 // 0, H, 2, 3 or 4, L, 6, 7 1846 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1847 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1848 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1849 InsertAtByte = IsLE ? 8 : 4; 1850 Swap = M1 < 4; 1851 return true; 1852 } 1853 // 0, 1, H, 3 or 4, 5, L, 7 1854 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1855 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1856 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1857 InsertAtByte = IsLE ? 4 : 8; 1858 Swap = M2 < 4; 1859 return true; 1860 } 1861 // 0, 1, 2, H or 4, 5, 6, L 1862 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1863 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1864 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1865 InsertAtByte = IsLE ? 0 : 12; 1866 Swap = M3 < 4; 1867 return true; 1868 } 1869 1870 // If both vector operands for the shuffle are the same vector, the mask will 1871 // contain only elements from the first one and the second one will be undef. 1872 if (N->getOperand(1).isUndef()) { 1873 ShiftElts = 0; 1874 Swap = true; 1875 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1876 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1877 InsertAtByte = IsLE ? 12 : 0; 1878 return true; 1879 } 1880 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1881 InsertAtByte = IsLE ? 8 : 4; 1882 return true; 1883 } 1884 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1885 InsertAtByte = IsLE ? 4 : 8; 1886 return true; 1887 } 1888 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1889 InsertAtByte = IsLE ? 0 : 12; 1890 return true; 1891 } 1892 } 1893 1894 return false; 1895 } 1896 1897 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1898 bool &Swap, bool IsLE) { 1899 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1900 // Ensure each byte index of the word is consecutive. 1901 if (!isNByteElemShuffleMask(N, 4, 1)) 1902 return false; 1903 1904 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1905 unsigned M0 = N->getMaskElt(0) / 4; 1906 unsigned M1 = N->getMaskElt(4) / 4; 1907 unsigned M2 = N->getMaskElt(8) / 4; 1908 unsigned M3 = N->getMaskElt(12) / 4; 1909 1910 // If both vector operands for the shuffle are the same vector, the mask will 1911 // contain only elements from the first one and the second one will be undef. 1912 if (N->getOperand(1).isUndef()) { 1913 assert(M0 < 4 && "Indexing into an undef vector?"); 1914 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1915 return false; 1916 1917 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1918 Swap = false; 1919 return true; 1920 } 1921 1922 // Ensure each word index of the ShuffleVector Mask is consecutive. 1923 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1924 return false; 1925 1926 if (IsLE) { 1927 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1928 // Input vectors don't need to be swapped if the leading element 1929 // of the result is one of the 3 left elements of the second vector 1930 // (or if there is no shift to be done at all). 1931 Swap = false; 1932 ShiftElts = (8 - M0) % 8; 1933 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1934 // Input vectors need to be swapped if the leading element 1935 // of the result is one of the 3 left elements of the first vector 1936 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1937 Swap = true; 1938 ShiftElts = (4 - M0) % 4; 1939 } 1940 1941 return true; 1942 } else { // BE 1943 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1944 // Input vectors don't need to be swapped if the leading element 1945 // of the result is one of the 4 elements of the first vector. 1946 Swap = false; 1947 ShiftElts = M0; 1948 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1949 // Input vectors need to be swapped if the leading element 1950 // of the result is one of the 4 elements of the right vector. 1951 Swap = true; 1952 ShiftElts = M0 - 4; 1953 } 1954 1955 return true; 1956 } 1957 } 1958 1959 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1960 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1961 1962 if (!isNByteElemShuffleMask(N, Width, -1)) 1963 return false; 1964 1965 for (int i = 0; i < 16; i += Width) 1966 if (N->getMaskElt(i) != i + Width - 1) 1967 return false; 1968 1969 return true; 1970 } 1971 1972 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1973 return isXXBRShuffleMaskHelper(N, 2); 1974 } 1975 1976 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1977 return isXXBRShuffleMaskHelper(N, 4); 1978 } 1979 1980 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1981 return isXXBRShuffleMaskHelper(N, 8); 1982 } 1983 1984 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1985 return isXXBRShuffleMaskHelper(N, 16); 1986 } 1987 1988 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1989 /// if the inputs to the instruction should be swapped and set \p DM to the 1990 /// value for the immediate. 1991 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1992 /// AND element 0 of the result comes from the first input (LE) or second input 1993 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1994 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1995 /// mask. 1996 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1997 bool &Swap, bool IsLE) { 1998 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1999 2000 // Ensure each byte index of the double word is consecutive. 2001 if (!isNByteElemShuffleMask(N, 8, 1)) 2002 return false; 2003 2004 unsigned M0 = N->getMaskElt(0) / 8; 2005 unsigned M1 = N->getMaskElt(8) / 8; 2006 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2007 2008 // If both vector operands for the shuffle are the same vector, the mask will 2009 // contain only elements from the first one and the second one will be undef. 2010 if (N->getOperand(1).isUndef()) { 2011 if ((M0 | M1) < 2) { 2012 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2013 Swap = false; 2014 return true; 2015 } else 2016 return false; 2017 } 2018 2019 if (IsLE) { 2020 if (M0 > 1 && M1 < 2) { 2021 Swap = false; 2022 } else if (M0 < 2 && M1 > 1) { 2023 M0 = (M0 + 2) % 4; 2024 M1 = (M1 + 2) % 4; 2025 Swap = true; 2026 } else 2027 return false; 2028 2029 // Note: if control flow comes here that means Swap is already set above 2030 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2031 return true; 2032 } else { // BE 2033 if (M0 < 2 && M1 > 1) { 2034 Swap = false; 2035 } else if (M0 > 1 && M1 < 2) { 2036 M0 = (M0 + 2) % 4; 2037 M1 = (M1 + 2) % 4; 2038 Swap = true; 2039 } else 2040 return false; 2041 2042 // Note: if control flow comes here that means Swap is already set above 2043 DM = (M0 << 1) + (M1 & 1); 2044 return true; 2045 } 2046 } 2047 2048 2049 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2050 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2051 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2052 SelectionDAG &DAG) { 2053 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2054 assert(isSplatShuffleMask(SVOp, EltSize)); 2055 if (DAG.getDataLayout().isLittleEndian()) 2056 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2057 else 2058 return SVOp->getMaskElt(0) / EltSize; 2059 } 2060 2061 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2062 /// by using a vspltis[bhw] instruction of the specified element size, return 2063 /// the constant being splatted. The ByteSize field indicates the number of 2064 /// bytes of each element [124] -> [bhw]. 2065 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2066 SDValue OpVal(nullptr, 0); 2067 2068 // If ByteSize of the splat is bigger than the element size of the 2069 // build_vector, then we have a case where we are checking for a splat where 2070 // multiple elements of the buildvector are folded together into a single 2071 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2072 unsigned EltSize = 16/N->getNumOperands(); 2073 if (EltSize < ByteSize) { 2074 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2075 SDValue UniquedVals[4]; 2076 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2077 2078 // See if all of the elements in the buildvector agree across. 2079 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2080 if (N->getOperand(i).isUndef()) continue; 2081 // If the element isn't a constant, bail fully out. 2082 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2083 2084 if (!UniquedVals[i&(Multiple-1)].getNode()) 2085 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2086 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2087 return SDValue(); // no match. 2088 } 2089 2090 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2091 // either constant or undef values that are identical for each chunk. See 2092 // if these chunks can form into a larger vspltis*. 2093 2094 // Check to see if all of the leading entries are either 0 or -1. If 2095 // neither, then this won't fit into the immediate field. 2096 bool LeadingZero = true; 2097 bool LeadingOnes = true; 2098 for (unsigned i = 0; i != Multiple-1; ++i) { 2099 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2100 2101 LeadingZero &= isNullConstant(UniquedVals[i]); 2102 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2103 } 2104 // Finally, check the least significant entry. 2105 if (LeadingZero) { 2106 if (!UniquedVals[Multiple-1].getNode()) 2107 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2108 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2109 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2110 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2111 } 2112 if (LeadingOnes) { 2113 if (!UniquedVals[Multiple-1].getNode()) 2114 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2115 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2116 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2117 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2118 } 2119 2120 return SDValue(); 2121 } 2122 2123 // Check to see if this buildvec has a single non-undef value in its elements. 2124 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2125 if (N->getOperand(i).isUndef()) continue; 2126 if (!OpVal.getNode()) 2127 OpVal = N->getOperand(i); 2128 else if (OpVal != N->getOperand(i)) 2129 return SDValue(); 2130 } 2131 2132 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2133 2134 unsigned ValSizeInBytes = EltSize; 2135 uint64_t Value = 0; 2136 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2137 Value = CN->getZExtValue(); 2138 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2139 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2140 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2141 } 2142 2143 // If the splat value is larger than the element value, then we can never do 2144 // this splat. The only case that we could fit the replicated bits into our 2145 // immediate field for would be zero, and we prefer to use vxor for it. 2146 if (ValSizeInBytes < ByteSize) return SDValue(); 2147 2148 // If the element value is larger than the splat value, check if it consists 2149 // of a repeated bit pattern of size ByteSize. 2150 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2151 return SDValue(); 2152 2153 // Properly sign extend the value. 2154 int MaskVal = SignExtend32(Value, ByteSize * 8); 2155 2156 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2157 if (MaskVal == 0) return SDValue(); 2158 2159 // Finally, if this value fits in a 5 bit sext field, return it 2160 if (SignExtend32<5>(MaskVal) == MaskVal) 2161 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2162 return SDValue(); 2163 } 2164 2165 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2166 /// amount, otherwise return -1. 2167 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2168 EVT VT = N->getValueType(0); 2169 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2170 return -1; 2171 2172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2173 2174 // Find the first non-undef value in the shuffle mask. 2175 unsigned i; 2176 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2177 /*search*/; 2178 2179 if (i == 4) return -1; // all undef. 2180 2181 // Otherwise, check to see if the rest of the elements are consecutively 2182 // numbered from this value. 2183 unsigned ShiftAmt = SVOp->getMaskElt(i); 2184 if (ShiftAmt < i) return -1; 2185 ShiftAmt -= i; 2186 2187 // Check the rest of the elements to see if they are consecutive. 2188 for (++i; i != 4; ++i) 2189 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2190 return -1; 2191 2192 return ShiftAmt; 2193 } 2194 2195 //===----------------------------------------------------------------------===// 2196 // Addressing Mode Selection 2197 //===----------------------------------------------------------------------===// 2198 2199 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2200 /// or 64-bit immediate, and if the value can be accurately represented as a 2201 /// sign extension from a 16-bit value. If so, this returns true and the 2202 /// immediate. 2203 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2204 if (!isa<ConstantSDNode>(N)) 2205 return false; 2206 2207 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2208 if (N->getValueType(0) == MVT::i32) 2209 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2210 else 2211 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2212 } 2213 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2214 return isIntS16Immediate(Op.getNode(), Imm); 2215 } 2216 2217 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2218 /// can be represented as an indexed [r+r] operation. Returns false if it 2219 /// can be more efficiently represented with [r+imm]. 2220 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2221 SDValue &Index, 2222 SelectionDAG &DAG) const { 2223 int16_t imm = 0; 2224 if (N.getOpcode() == ISD::ADD) { 2225 if (isIntS16Immediate(N.getOperand(1), imm)) 2226 return false; // r+i 2227 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2228 return false; // r+i 2229 2230 Base = N.getOperand(0); 2231 Index = N.getOperand(1); 2232 return true; 2233 } else if (N.getOpcode() == ISD::OR) { 2234 if (isIntS16Immediate(N.getOperand(1), imm)) 2235 return false; // r+i can fold it if we can. 2236 2237 // If this is an or of disjoint bitfields, we can codegen this as an add 2238 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2239 // disjoint. 2240 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2241 2242 if (LHSKnown.Zero.getBoolValue()) { 2243 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2244 // If all of the bits are known zero on the LHS or RHS, the add won't 2245 // carry. 2246 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2247 Base = N.getOperand(0); 2248 Index = N.getOperand(1); 2249 return true; 2250 } 2251 } 2252 } 2253 2254 return false; 2255 } 2256 2257 // If we happen to be doing an i64 load or store into a stack slot that has 2258 // less than a 4-byte alignment, then the frame-index elimination may need to 2259 // use an indexed load or store instruction (because the offset may not be a 2260 // multiple of 4). The extra register needed to hold the offset comes from the 2261 // register scavenger, and it is possible that the scavenger will need to use 2262 // an emergency spill slot. As a result, we need to make sure that a spill slot 2263 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2264 // stack slot. 2265 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2266 // FIXME: This does not handle the LWA case. 2267 if (VT != MVT::i64) 2268 return; 2269 2270 // NOTE: We'll exclude negative FIs here, which come from argument 2271 // lowering, because there are no known test cases triggering this problem 2272 // using packed structures (or similar). We can remove this exclusion if 2273 // we find such a test case. The reason why this is so test-case driven is 2274 // because this entire 'fixup' is only to prevent crashes (from the 2275 // register scavenger) on not-really-valid inputs. For example, if we have: 2276 // %a = alloca i1 2277 // %b = bitcast i1* %a to i64* 2278 // store i64* a, i64 b 2279 // then the store should really be marked as 'align 1', but is not. If it 2280 // were marked as 'align 1' then the indexed form would have been 2281 // instruction-selected initially, and the problem this 'fixup' is preventing 2282 // won't happen regardless. 2283 if (FrameIdx < 0) 2284 return; 2285 2286 MachineFunction &MF = DAG.getMachineFunction(); 2287 MachineFrameInfo &MFI = MF.getFrameInfo(); 2288 2289 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2290 if (Align >= 4) 2291 return; 2292 2293 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2294 FuncInfo->setHasNonRISpills(); 2295 } 2296 2297 /// Returns true if the address N can be represented by a base register plus 2298 /// a signed 16-bit displacement [r+imm], and if it is not better 2299 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2300 /// displacements that are multiples of that value. 2301 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2302 SDValue &Base, 2303 SelectionDAG &DAG, 2304 unsigned Alignment) const { 2305 // FIXME dl should come from parent load or store, not from address 2306 SDLoc dl(N); 2307 // If this can be more profitably realized as r+r, fail. 2308 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2309 return false; 2310 2311 if (N.getOpcode() == ISD::ADD) { 2312 int16_t imm = 0; 2313 if (isIntS16Immediate(N.getOperand(1), imm) && 2314 (!Alignment || (imm % Alignment) == 0)) { 2315 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2316 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2317 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2318 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2319 } else { 2320 Base = N.getOperand(0); 2321 } 2322 return true; // [r+i] 2323 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2324 // Match LOAD (ADD (X, Lo(G))). 2325 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2326 && "Cannot handle constant offsets yet!"); 2327 Disp = N.getOperand(1).getOperand(0); // The global address. 2328 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2329 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2330 Disp.getOpcode() == ISD::TargetConstantPool || 2331 Disp.getOpcode() == ISD::TargetJumpTable); 2332 Base = N.getOperand(0); 2333 return true; // [&g+r] 2334 } 2335 } else if (N.getOpcode() == ISD::OR) { 2336 int16_t imm = 0; 2337 if (isIntS16Immediate(N.getOperand(1), imm) && 2338 (!Alignment || (imm % Alignment) == 0)) { 2339 // If this is an or of disjoint bitfields, we can codegen this as an add 2340 // (for better address arithmetic) if the LHS and RHS of the OR are 2341 // provably disjoint. 2342 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2343 2344 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2345 // If all of the bits are known zero on the LHS or RHS, the add won't 2346 // carry. 2347 if (FrameIndexSDNode *FI = 2348 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2349 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2350 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2351 } else { 2352 Base = N.getOperand(0); 2353 } 2354 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2355 return true; 2356 } 2357 } 2358 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2359 // Loading from a constant address. 2360 2361 // If this address fits entirely in a 16-bit sext immediate field, codegen 2362 // this as "d, 0" 2363 int16_t Imm; 2364 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2365 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2366 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2367 CN->getValueType(0)); 2368 return true; 2369 } 2370 2371 // Handle 32-bit sext immediates with LIS + addr mode. 2372 if ((CN->getValueType(0) == MVT::i32 || 2373 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2374 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2375 int Addr = (int)CN->getZExtValue(); 2376 2377 // Otherwise, break this down into an LIS + disp. 2378 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2379 2380 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2381 MVT::i32); 2382 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2383 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2384 return true; 2385 } 2386 } 2387 2388 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2389 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2390 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2391 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2392 } else 2393 Base = N; 2394 return true; // [r+0] 2395 } 2396 2397 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2398 /// represented as an indexed [r+r] operation. 2399 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2400 SDValue &Index, 2401 SelectionDAG &DAG) const { 2402 // Check to see if we can easily represent this as an [r+r] address. This 2403 // will fail if it thinks that the address is more profitably represented as 2404 // reg+imm, e.g. where imm = 0. 2405 if (SelectAddressRegReg(N, Base, Index, DAG)) 2406 return true; 2407 2408 // If the address is the result of an add, we will utilize the fact that the 2409 // address calculation includes an implicit add. However, we can reduce 2410 // register pressure if we do not materialize a constant just for use as the 2411 // index register. We only get rid of the add if it is not an add of a 2412 // value and a 16-bit signed constant and both have a single use. 2413 int16_t imm = 0; 2414 if (N.getOpcode() == ISD::ADD && 2415 (!isIntS16Immediate(N.getOperand(1), imm) || 2416 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2417 Base = N.getOperand(0); 2418 Index = N.getOperand(1); 2419 return true; 2420 } 2421 2422 // Otherwise, do it the hard way, using R0 as the base register. 2423 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2424 N.getValueType()); 2425 Index = N; 2426 return true; 2427 } 2428 2429 /// Returns true if we should use a direct load into vector instruction 2430 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2431 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2432 2433 // If there are any other uses other than scalar to vector, then we should 2434 // keep it as a scalar load -> direct move pattern to prevent multiple 2435 // loads. 2436 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2437 if (!LD) 2438 return false; 2439 2440 EVT MemVT = LD->getMemoryVT(); 2441 if (!MemVT.isSimple()) 2442 return false; 2443 switch(MemVT.getSimpleVT().SimpleTy) { 2444 case MVT::i64: 2445 break; 2446 case MVT::i32: 2447 if (!ST.hasP8Vector()) 2448 return false; 2449 break; 2450 case MVT::i16: 2451 case MVT::i8: 2452 if (!ST.hasP9Vector()) 2453 return false; 2454 break; 2455 default: 2456 return false; 2457 } 2458 2459 SDValue LoadedVal(N, 0); 2460 if (!LoadedVal.hasOneUse()) 2461 return false; 2462 2463 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2464 UI != UE; ++UI) 2465 if (UI.getUse().get().getResNo() == 0 && 2466 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2467 return false; 2468 2469 return true; 2470 } 2471 2472 /// getPreIndexedAddressParts - returns true by value, base pointer and 2473 /// offset pointer and addressing mode by reference if the node's address 2474 /// can be legally represented as pre-indexed load / store address. 2475 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2476 SDValue &Offset, 2477 ISD::MemIndexedMode &AM, 2478 SelectionDAG &DAG) const { 2479 if (DisablePPCPreinc) return false; 2480 2481 bool isLoad = true; 2482 SDValue Ptr; 2483 EVT VT; 2484 unsigned Alignment; 2485 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2486 Ptr = LD->getBasePtr(); 2487 VT = LD->getMemoryVT(); 2488 Alignment = LD->getAlignment(); 2489 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2490 Ptr = ST->getBasePtr(); 2491 VT = ST->getMemoryVT(); 2492 Alignment = ST->getAlignment(); 2493 isLoad = false; 2494 } else 2495 return false; 2496 2497 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2498 // instructions because we can fold these into a more efficient instruction 2499 // instead, (such as LXSD). 2500 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2501 return false; 2502 } 2503 2504 // PowerPC doesn't have preinc load/store instructions for vectors (except 2505 // for QPX, which does have preinc r+r forms). 2506 if (VT.isVector()) { 2507 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2508 return false; 2509 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2510 AM = ISD::PRE_INC; 2511 return true; 2512 } 2513 } 2514 2515 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2516 // Common code will reject creating a pre-inc form if the base pointer 2517 // is a frame index, or if N is a store and the base pointer is either 2518 // the same as or a predecessor of the value being stored. Check for 2519 // those situations here, and try with swapped Base/Offset instead. 2520 bool Swap = false; 2521 2522 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2523 Swap = true; 2524 else if (!isLoad) { 2525 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2526 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2527 Swap = true; 2528 } 2529 2530 if (Swap) 2531 std::swap(Base, Offset); 2532 2533 AM = ISD::PRE_INC; 2534 return true; 2535 } 2536 2537 // LDU/STU can only handle immediates that are a multiple of 4. 2538 if (VT != MVT::i64) { 2539 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2540 return false; 2541 } else { 2542 // LDU/STU need an address with at least 4-byte alignment. 2543 if (Alignment < 4) 2544 return false; 2545 2546 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2547 return false; 2548 } 2549 2550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2551 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2552 // sext i32 to i64 when addr mode is r+i. 2553 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2554 LD->getExtensionType() == ISD::SEXTLOAD && 2555 isa<ConstantSDNode>(Offset)) 2556 return false; 2557 } 2558 2559 AM = ISD::PRE_INC; 2560 return true; 2561 } 2562 2563 //===----------------------------------------------------------------------===// 2564 // LowerOperation implementation 2565 //===----------------------------------------------------------------------===// 2566 2567 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2568 /// and LoOpFlags to the target MO flags. 2569 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2570 unsigned &HiOpFlags, unsigned &LoOpFlags, 2571 const GlobalValue *GV = nullptr) { 2572 HiOpFlags = PPCII::MO_HA; 2573 LoOpFlags = PPCII::MO_LO; 2574 2575 // Don't use the pic base if not in PIC relocation model. 2576 if (IsPIC) { 2577 HiOpFlags |= PPCII::MO_PIC_FLAG; 2578 LoOpFlags |= PPCII::MO_PIC_FLAG; 2579 } 2580 2581 // If this is a reference to a global value that requires a non-lazy-ptr, make 2582 // sure that instruction lowering adds it. 2583 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2584 HiOpFlags |= PPCII::MO_NLP_FLAG; 2585 LoOpFlags |= PPCII::MO_NLP_FLAG; 2586 2587 if (GV->hasHiddenVisibility()) { 2588 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2589 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2590 } 2591 } 2592 } 2593 2594 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2595 SelectionDAG &DAG) { 2596 SDLoc DL(HiPart); 2597 EVT PtrVT = HiPart.getValueType(); 2598 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2599 2600 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2601 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2602 2603 // With PIC, the first instruction is actually "GR+hi(&G)". 2604 if (isPIC) 2605 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2606 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2607 2608 // Generate non-pic code that has direct accesses to the constant pool. 2609 // The address of the global is just (hi(&g)+lo(&g)). 2610 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2611 } 2612 2613 static void setUsesTOCBasePtr(MachineFunction &MF) { 2614 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2615 FuncInfo->setUsesTOCBasePtr(); 2616 } 2617 2618 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2619 setUsesTOCBasePtr(DAG.getMachineFunction()); 2620 } 2621 2622 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2623 SDValue GA) { 2624 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2625 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2626 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2627 2628 SDValue Ops[] = { GA, Reg }; 2629 return DAG.getMemIntrinsicNode( 2630 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2631 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2632 MachineMemOperand::MOLoad); 2633 } 2634 2635 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2636 SelectionDAG &DAG) const { 2637 EVT PtrVT = Op.getValueType(); 2638 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2639 const Constant *C = CP->getConstVal(); 2640 2641 // 64-bit SVR4 ABI code is always position-independent. 2642 // The actual address of the GlobalValue is stored in the TOC. 2643 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2644 setUsesTOCBasePtr(DAG); 2645 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2646 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2647 } 2648 2649 unsigned MOHiFlag, MOLoFlag; 2650 bool IsPIC = isPositionIndependent(); 2651 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2652 2653 if (IsPIC && Subtarget.isSVR4ABI()) { 2654 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2655 PPCII::MO_PIC_FLAG); 2656 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2657 } 2658 2659 SDValue CPIHi = 2660 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2661 SDValue CPILo = 2662 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2663 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2664 } 2665 2666 // For 64-bit PowerPC, prefer the more compact relative encodings. 2667 // This trades 32 bits per jump table entry for one or two instructions 2668 // on the jump site. 2669 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2670 if (isJumpTableRelative()) 2671 return MachineJumpTableInfo::EK_LabelDifference32; 2672 2673 return TargetLowering::getJumpTableEncoding(); 2674 } 2675 2676 bool PPCTargetLowering::isJumpTableRelative() const { 2677 if (Subtarget.isPPC64()) 2678 return true; 2679 return TargetLowering::isJumpTableRelative(); 2680 } 2681 2682 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2683 SelectionDAG &DAG) const { 2684 if (!Subtarget.isPPC64()) 2685 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2686 2687 switch (getTargetMachine().getCodeModel()) { 2688 case CodeModel::Small: 2689 case CodeModel::Medium: 2690 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2691 default: 2692 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2693 getPointerTy(DAG.getDataLayout())); 2694 } 2695 } 2696 2697 const MCExpr * 2698 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2699 unsigned JTI, 2700 MCContext &Ctx) const { 2701 if (!Subtarget.isPPC64()) 2702 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2703 2704 switch (getTargetMachine().getCodeModel()) { 2705 case CodeModel::Small: 2706 case CodeModel::Medium: 2707 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2708 default: 2709 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2710 } 2711 } 2712 2713 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2714 EVT PtrVT = Op.getValueType(); 2715 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2716 2717 // 64-bit SVR4 ABI code is always position-independent. 2718 // The actual address of the GlobalValue is stored in the TOC. 2719 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2720 setUsesTOCBasePtr(DAG); 2721 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2722 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2723 } 2724 2725 unsigned MOHiFlag, MOLoFlag; 2726 bool IsPIC = isPositionIndependent(); 2727 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2728 2729 if (IsPIC && Subtarget.isSVR4ABI()) { 2730 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2731 PPCII::MO_PIC_FLAG); 2732 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2733 } 2734 2735 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2736 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2737 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2738 } 2739 2740 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2741 SelectionDAG &DAG) const { 2742 EVT PtrVT = Op.getValueType(); 2743 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2744 const BlockAddress *BA = BASDN->getBlockAddress(); 2745 2746 // 64-bit SVR4 ABI code is always position-independent. 2747 // The actual BlockAddress is stored in the TOC. 2748 if (Subtarget.isSVR4ABI() && 2749 (Subtarget.isPPC64() || isPositionIndependent())) { 2750 if (Subtarget.isPPC64()) 2751 setUsesTOCBasePtr(DAG); 2752 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2753 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2754 } 2755 2756 unsigned MOHiFlag, MOLoFlag; 2757 bool IsPIC = isPositionIndependent(); 2758 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2759 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2760 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2761 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2762 } 2763 2764 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2765 SelectionDAG &DAG) const { 2766 // FIXME: TLS addresses currently use medium model code sequences, 2767 // which is the most useful form. Eventually support for small and 2768 // large models could be added if users need it, at the cost of 2769 // additional complexity. 2770 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2771 if (DAG.getTarget().useEmulatedTLS()) 2772 return LowerToTLSEmulatedModel(GA, DAG); 2773 2774 SDLoc dl(GA); 2775 const GlobalValue *GV = GA->getGlobal(); 2776 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2777 bool is64bit = Subtarget.isPPC64(); 2778 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2779 PICLevel::Level picLevel = M->getPICLevel(); 2780 2781 const TargetMachine &TM = getTargetMachine(); 2782 TLSModel::Model Model = TM.getTLSModel(GV); 2783 2784 if (Model == TLSModel::LocalExec) { 2785 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2786 PPCII::MO_TPREL_HA); 2787 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2788 PPCII::MO_TPREL_LO); 2789 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2790 : DAG.getRegister(PPC::R2, MVT::i32); 2791 2792 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2793 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2794 } 2795 2796 if (Model == TLSModel::InitialExec) { 2797 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2798 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2799 PPCII::MO_TLS); 2800 SDValue GOTPtr; 2801 if (is64bit) { 2802 setUsesTOCBasePtr(DAG); 2803 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2804 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2805 PtrVT, GOTReg, TGA); 2806 } else { 2807 if (!TM.isPositionIndependent()) 2808 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2809 else if (picLevel == PICLevel::SmallPIC) 2810 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2811 else 2812 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2813 } 2814 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2815 PtrVT, TGA, GOTPtr); 2816 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2817 } 2818 2819 if (Model == TLSModel::GeneralDynamic) { 2820 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2821 SDValue GOTPtr; 2822 if (is64bit) { 2823 setUsesTOCBasePtr(DAG); 2824 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2825 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2826 GOTReg, TGA); 2827 } else { 2828 if (picLevel == PICLevel::SmallPIC) 2829 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2830 else 2831 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2832 } 2833 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2834 GOTPtr, TGA, TGA); 2835 } 2836 2837 if (Model == TLSModel::LocalDynamic) { 2838 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2839 SDValue GOTPtr; 2840 if (is64bit) { 2841 setUsesTOCBasePtr(DAG); 2842 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2843 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2844 GOTReg, TGA); 2845 } else { 2846 if (picLevel == PICLevel::SmallPIC) 2847 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2848 else 2849 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2850 } 2851 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2852 PtrVT, GOTPtr, TGA, TGA); 2853 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2854 PtrVT, TLSAddr, TGA); 2855 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2856 } 2857 2858 llvm_unreachable("Unknown TLS model!"); 2859 } 2860 2861 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2862 SelectionDAG &DAG) const { 2863 EVT PtrVT = Op.getValueType(); 2864 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2865 SDLoc DL(GSDN); 2866 const GlobalValue *GV = GSDN->getGlobal(); 2867 2868 // 64-bit SVR4 ABI code is always position-independent. 2869 // The actual address of the GlobalValue is stored in the TOC. 2870 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2871 setUsesTOCBasePtr(DAG); 2872 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2873 return getTOCEntry(DAG, DL, true, GA); 2874 } 2875 2876 unsigned MOHiFlag, MOLoFlag; 2877 bool IsPIC = isPositionIndependent(); 2878 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2879 2880 if (IsPIC && Subtarget.isSVR4ABI()) { 2881 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2882 GSDN->getOffset(), 2883 PPCII::MO_PIC_FLAG); 2884 return getTOCEntry(DAG, DL, false, GA); 2885 } 2886 2887 SDValue GAHi = 2888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2889 SDValue GALo = 2890 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2891 2892 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2893 2894 // If the global reference is actually to a non-lazy-pointer, we have to do an 2895 // extra load to get the address of the global. 2896 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2897 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2898 return Ptr; 2899 } 2900 2901 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2902 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2903 SDLoc dl(Op); 2904 2905 if (Op.getValueType() == MVT::v2i64) { 2906 // When the operands themselves are v2i64 values, we need to do something 2907 // special because VSX has no underlying comparison operations for these. 2908 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2909 // Equality can be handled by casting to the legal type for Altivec 2910 // comparisons, everything else needs to be expanded. 2911 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2912 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2913 DAG.getSetCC(dl, MVT::v4i32, 2914 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2915 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2916 CC)); 2917 } 2918 2919 return SDValue(); 2920 } 2921 2922 // We handle most of these in the usual way. 2923 return Op; 2924 } 2925 2926 // If we're comparing for equality to zero, expose the fact that this is 2927 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2928 // fold the new nodes. 2929 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2930 return V; 2931 2932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2933 // Leave comparisons against 0 and -1 alone for now, since they're usually 2934 // optimized. FIXME: revisit this when we can custom lower all setcc 2935 // optimizations. 2936 if (C->isAllOnesValue() || C->isNullValue()) 2937 return SDValue(); 2938 } 2939 2940 // If we have an integer seteq/setne, turn it into a compare against zero 2941 // by xor'ing the rhs with the lhs, which is faster than setting a 2942 // condition register, reading it back out, and masking the correct bit. The 2943 // normal approach here uses sub to do this instead of xor. Using xor exposes 2944 // the result to other bit-twiddling opportunities. 2945 EVT LHSVT = Op.getOperand(0).getValueType(); 2946 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2947 EVT VT = Op.getValueType(); 2948 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2949 Op.getOperand(1)); 2950 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2951 } 2952 return SDValue(); 2953 } 2954 2955 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2956 SDNode *Node = Op.getNode(); 2957 EVT VT = Node->getValueType(0); 2958 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2959 SDValue InChain = Node->getOperand(0); 2960 SDValue VAListPtr = Node->getOperand(1); 2961 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2962 SDLoc dl(Node); 2963 2964 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2965 2966 // gpr_index 2967 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2968 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2969 InChain = GprIndex.getValue(1); 2970 2971 if (VT == MVT::i64) { 2972 // Check if GprIndex is even 2973 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2974 DAG.getConstant(1, dl, MVT::i32)); 2975 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2976 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2977 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2978 DAG.getConstant(1, dl, MVT::i32)); 2979 // Align GprIndex to be even if it isn't 2980 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2981 GprIndex); 2982 } 2983 2984 // fpr index is 1 byte after gpr 2985 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2986 DAG.getConstant(1, dl, MVT::i32)); 2987 2988 // fpr 2989 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2990 FprPtr, MachinePointerInfo(SV), MVT::i8); 2991 InChain = FprIndex.getValue(1); 2992 2993 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2994 DAG.getConstant(8, dl, MVT::i32)); 2995 2996 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2997 DAG.getConstant(4, dl, MVT::i32)); 2998 2999 // areas 3000 SDValue OverflowArea = 3001 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3002 InChain = OverflowArea.getValue(1); 3003 3004 SDValue RegSaveArea = 3005 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3006 InChain = RegSaveArea.getValue(1); 3007 3008 // select overflow_area if index > 8 3009 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3010 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3011 3012 // adjustment constant gpr_index * 4/8 3013 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3014 VT.isInteger() ? GprIndex : FprIndex, 3015 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3016 MVT::i32)); 3017 3018 // OurReg = RegSaveArea + RegConstant 3019 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3020 RegConstant); 3021 3022 // Floating types are 32 bytes into RegSaveArea 3023 if (VT.isFloatingPoint()) 3024 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3025 DAG.getConstant(32, dl, MVT::i32)); 3026 3027 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3028 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3029 VT.isInteger() ? GprIndex : FprIndex, 3030 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3031 MVT::i32)); 3032 3033 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3034 VT.isInteger() ? VAListPtr : FprPtr, 3035 MachinePointerInfo(SV), MVT::i8); 3036 3037 // determine if we should load from reg_save_area or overflow_area 3038 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3039 3040 // increase overflow_area by 4/8 if gpr/fpr > 8 3041 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3042 DAG.getConstant(VT.isInteger() ? 4 : 8, 3043 dl, MVT::i32)); 3044 3045 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3046 OverflowAreaPlusN); 3047 3048 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3049 MachinePointerInfo(), MVT::i32); 3050 3051 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3052 } 3053 3054 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3055 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3056 3057 // We have to copy the entire va_list struct: 3058 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3059 return DAG.getMemcpy(Op.getOperand(0), Op, 3060 Op.getOperand(1), Op.getOperand(2), 3061 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3062 false, MachinePointerInfo(), MachinePointerInfo()); 3063 } 3064 3065 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3066 SelectionDAG &DAG) const { 3067 return Op.getOperand(0); 3068 } 3069 3070 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3071 SelectionDAG &DAG) const { 3072 SDValue Chain = Op.getOperand(0); 3073 SDValue Trmp = Op.getOperand(1); // trampoline 3074 SDValue FPtr = Op.getOperand(2); // nested function 3075 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3076 SDLoc dl(Op); 3077 3078 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3079 bool isPPC64 = (PtrVT == MVT::i64); 3080 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3081 3082 TargetLowering::ArgListTy Args; 3083 TargetLowering::ArgListEntry Entry; 3084 3085 Entry.Ty = IntPtrTy; 3086 Entry.Node = Trmp; Args.push_back(Entry); 3087 3088 // TrampSize == (isPPC64 ? 48 : 40); 3089 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3090 isPPC64 ? MVT::i64 : MVT::i32); 3091 Args.push_back(Entry); 3092 3093 Entry.Node = FPtr; Args.push_back(Entry); 3094 Entry.Node = Nest; Args.push_back(Entry); 3095 3096 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3097 TargetLowering::CallLoweringInfo CLI(DAG); 3098 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3099 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3100 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3101 3102 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3103 return CallResult.second; 3104 } 3105 3106 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3107 MachineFunction &MF = DAG.getMachineFunction(); 3108 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3109 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3110 3111 SDLoc dl(Op); 3112 3113 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3114 // vastart just stores the address of the VarArgsFrameIndex slot into the 3115 // memory location argument. 3116 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3117 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3118 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3119 MachinePointerInfo(SV)); 3120 } 3121 3122 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3123 // We suppose the given va_list is already allocated. 3124 // 3125 // typedef struct { 3126 // char gpr; /* index into the array of 8 GPRs 3127 // * stored in the register save area 3128 // * gpr=0 corresponds to r3, 3129 // * gpr=1 to r4, etc. 3130 // */ 3131 // char fpr; /* index into the array of 8 FPRs 3132 // * stored in the register save area 3133 // * fpr=0 corresponds to f1, 3134 // * fpr=1 to f2, etc. 3135 // */ 3136 // char *overflow_arg_area; 3137 // /* location on stack that holds 3138 // * the next overflow argument 3139 // */ 3140 // char *reg_save_area; 3141 // /* where r3:r10 and f1:f8 (if saved) 3142 // * are stored 3143 // */ 3144 // } va_list[1]; 3145 3146 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3147 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3148 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3149 PtrVT); 3150 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3151 PtrVT); 3152 3153 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3154 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3155 3156 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3157 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3158 3159 uint64_t FPROffset = 1; 3160 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3161 3162 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3163 3164 // Store first byte : number of int regs 3165 SDValue firstStore = 3166 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3167 MachinePointerInfo(SV), MVT::i8); 3168 uint64_t nextOffset = FPROffset; 3169 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3170 ConstFPROffset); 3171 3172 // Store second byte : number of float regs 3173 SDValue secondStore = 3174 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3175 MachinePointerInfo(SV, nextOffset), MVT::i8); 3176 nextOffset += StackOffset; 3177 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3178 3179 // Store second word : arguments given on stack 3180 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3181 MachinePointerInfo(SV, nextOffset)); 3182 nextOffset += FrameOffset; 3183 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3184 3185 // Store third word : arguments given in registers 3186 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3187 MachinePointerInfo(SV, nextOffset)); 3188 } 3189 3190 /// FPR - The set of FP registers that should be allocated for arguments, 3191 /// on Darwin. 3192 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3193 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3194 PPC::F11, PPC::F12, PPC::F13}; 3195 3196 /// QFPR - The set of QPX registers that should be allocated for arguments. 3197 static const MCPhysReg QFPR[] = { 3198 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3199 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3200 3201 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3202 /// the stack. 3203 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3204 unsigned PtrByteSize) { 3205 unsigned ArgSize = ArgVT.getStoreSize(); 3206 if (Flags.isByVal()) 3207 ArgSize = Flags.getByValSize(); 3208 3209 // Round up to multiples of the pointer size, except for array members, 3210 // which are always packed. 3211 if (!Flags.isInConsecutiveRegs()) 3212 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3213 3214 return ArgSize; 3215 } 3216 3217 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3218 /// on the stack. 3219 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3220 ISD::ArgFlagsTy Flags, 3221 unsigned PtrByteSize) { 3222 unsigned Align = PtrByteSize; 3223 3224 // Altivec parameters are padded to a 16 byte boundary. 3225 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3226 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3227 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3228 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3229 Align = 16; 3230 // QPX vector types stored in double-precision are padded to a 32 byte 3231 // boundary. 3232 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3233 Align = 32; 3234 3235 // ByVal parameters are aligned as requested. 3236 if (Flags.isByVal()) { 3237 unsigned BVAlign = Flags.getByValAlign(); 3238 if (BVAlign > PtrByteSize) { 3239 if (BVAlign % PtrByteSize != 0) 3240 llvm_unreachable( 3241 "ByVal alignment is not a multiple of the pointer size"); 3242 3243 Align = BVAlign; 3244 } 3245 } 3246 3247 // Array members are always packed to their original alignment. 3248 if (Flags.isInConsecutiveRegs()) { 3249 // If the array member was split into multiple registers, the first 3250 // needs to be aligned to the size of the full type. (Except for 3251 // ppcf128, which is only aligned as its f64 components.) 3252 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3253 Align = OrigVT.getStoreSize(); 3254 else 3255 Align = ArgVT.getStoreSize(); 3256 } 3257 3258 return Align; 3259 } 3260 3261 /// CalculateStackSlotUsed - Return whether this argument will use its 3262 /// stack slot (instead of being passed in registers). ArgOffset, 3263 /// AvailableFPRs, and AvailableVRs must hold the current argument 3264 /// position, and will be updated to account for this argument. 3265 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3266 ISD::ArgFlagsTy Flags, 3267 unsigned PtrByteSize, 3268 unsigned LinkageSize, 3269 unsigned ParamAreaSize, 3270 unsigned &ArgOffset, 3271 unsigned &AvailableFPRs, 3272 unsigned &AvailableVRs, bool HasQPX) { 3273 bool UseMemory = false; 3274 3275 // Respect alignment of argument on the stack. 3276 unsigned Align = 3277 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3278 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3279 // If there's no space left in the argument save area, we must 3280 // use memory (this check also catches zero-sized arguments). 3281 if (ArgOffset >= LinkageSize + ParamAreaSize) 3282 UseMemory = true; 3283 3284 // Allocate argument on the stack. 3285 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3286 if (Flags.isInConsecutiveRegsLast()) 3287 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3288 // If we overran the argument save area, we must use memory 3289 // (this check catches arguments passed partially in memory) 3290 if (ArgOffset > LinkageSize + ParamAreaSize) 3291 UseMemory = true; 3292 3293 // However, if the argument is actually passed in an FPR or a VR, 3294 // we don't use memory after all. 3295 if (!Flags.isByVal()) { 3296 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3297 // QPX registers overlap with the scalar FP registers. 3298 (HasQPX && (ArgVT == MVT::v4f32 || 3299 ArgVT == MVT::v4f64 || 3300 ArgVT == MVT::v4i1))) 3301 if (AvailableFPRs > 0) { 3302 --AvailableFPRs; 3303 return false; 3304 } 3305 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3306 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3307 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3308 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3309 if (AvailableVRs > 0) { 3310 --AvailableVRs; 3311 return false; 3312 } 3313 } 3314 3315 return UseMemory; 3316 } 3317 3318 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3319 /// ensure minimum alignment required for target. 3320 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3321 unsigned NumBytes) { 3322 unsigned TargetAlign = Lowering->getStackAlignment(); 3323 unsigned AlignMask = TargetAlign - 1; 3324 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3325 return NumBytes; 3326 } 3327 3328 SDValue PPCTargetLowering::LowerFormalArguments( 3329 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3330 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3331 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3332 if (Subtarget.isSVR4ABI()) { 3333 if (Subtarget.isPPC64()) 3334 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3335 dl, DAG, InVals); 3336 else 3337 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3338 dl, DAG, InVals); 3339 } else { 3340 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3341 dl, DAG, InVals); 3342 } 3343 } 3344 3345 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3346 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3347 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3348 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3349 3350 // 32-bit SVR4 ABI Stack Frame Layout: 3351 // +-----------------------------------+ 3352 // +--> | Back chain | 3353 // | +-----------------------------------+ 3354 // | | Floating-point register save area | 3355 // | +-----------------------------------+ 3356 // | | General register save area | 3357 // | +-----------------------------------+ 3358 // | | CR save word | 3359 // | +-----------------------------------+ 3360 // | | VRSAVE save word | 3361 // | +-----------------------------------+ 3362 // | | Alignment padding | 3363 // | +-----------------------------------+ 3364 // | | Vector register save area | 3365 // | +-----------------------------------+ 3366 // | | Local variable space | 3367 // | +-----------------------------------+ 3368 // | | Parameter list area | 3369 // | +-----------------------------------+ 3370 // | | LR save word | 3371 // | +-----------------------------------+ 3372 // SP--> +--- | Back chain | 3373 // +-----------------------------------+ 3374 // 3375 // Specifications: 3376 // System V Application Binary Interface PowerPC Processor Supplement 3377 // AltiVec Technology Programming Interface Manual 3378 3379 MachineFunction &MF = DAG.getMachineFunction(); 3380 MachineFrameInfo &MFI = MF.getFrameInfo(); 3381 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3382 3383 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3384 // Potential tail calls could cause overwriting of argument stack slots. 3385 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3386 (CallConv == CallingConv::Fast)); 3387 unsigned PtrByteSize = 4; 3388 3389 // Assign locations to all of the incoming arguments. 3390 SmallVector<CCValAssign, 16> ArgLocs; 3391 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3392 *DAG.getContext()); 3393 3394 // Reserve space for the linkage area on the stack. 3395 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3396 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3397 if (useSoftFloat() || hasSPE()) 3398 CCInfo.PreAnalyzeFormalArguments(Ins); 3399 3400 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3401 CCInfo.clearWasPPCF128(); 3402 3403 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3404 CCValAssign &VA = ArgLocs[i]; 3405 3406 // Arguments stored in registers. 3407 if (VA.isRegLoc()) { 3408 const TargetRegisterClass *RC; 3409 EVT ValVT = VA.getValVT(); 3410 3411 switch (ValVT.getSimpleVT().SimpleTy) { 3412 default: 3413 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3414 case MVT::i1: 3415 case MVT::i32: 3416 RC = &PPC::GPRCRegClass; 3417 break; 3418 case MVT::f32: 3419 if (Subtarget.hasP8Vector()) 3420 RC = &PPC::VSSRCRegClass; 3421 else if (Subtarget.hasSPE()) 3422 RC = &PPC::SPE4RCRegClass; 3423 else 3424 RC = &PPC::F4RCRegClass; 3425 break; 3426 case MVT::f64: 3427 if (Subtarget.hasVSX()) 3428 RC = &PPC::VSFRCRegClass; 3429 else if (Subtarget.hasSPE()) 3430 RC = &PPC::SPERCRegClass; 3431 else 3432 RC = &PPC::F8RCRegClass; 3433 break; 3434 case MVT::v16i8: 3435 case MVT::v8i16: 3436 case MVT::v4i32: 3437 RC = &PPC::VRRCRegClass; 3438 break; 3439 case MVT::v4f32: 3440 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3441 break; 3442 case MVT::v2f64: 3443 case MVT::v2i64: 3444 RC = &PPC::VRRCRegClass; 3445 break; 3446 case MVT::v4f64: 3447 RC = &PPC::QFRCRegClass; 3448 break; 3449 case MVT::v4i1: 3450 RC = &PPC::QBRCRegClass; 3451 break; 3452 } 3453 3454 // Transform the arguments stored in physical registers into virtual ones. 3455 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3456 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3457 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3458 3459 if (ValVT == MVT::i1) 3460 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3461 3462 InVals.push_back(ArgValue); 3463 } else { 3464 // Argument stored in memory. 3465 assert(VA.isMemLoc()); 3466 3467 // Get the extended size of the argument type in stack 3468 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3469 // Get the actual size of the argument type 3470 unsigned ObjSize = VA.getValVT().getStoreSize(); 3471 unsigned ArgOffset = VA.getLocMemOffset(); 3472 // Stack objects in PPC32 are right justified. 3473 ArgOffset += ArgSize - ObjSize; 3474 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3475 3476 // Create load nodes to retrieve arguments from the stack. 3477 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3478 InVals.push_back( 3479 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3480 } 3481 } 3482 3483 // Assign locations to all of the incoming aggregate by value arguments. 3484 // Aggregates passed by value are stored in the local variable space of the 3485 // caller's stack frame, right above the parameter list area. 3486 SmallVector<CCValAssign, 16> ByValArgLocs; 3487 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3488 ByValArgLocs, *DAG.getContext()); 3489 3490 // Reserve stack space for the allocations in CCInfo. 3491 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3492 3493 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3494 3495 // Area that is at least reserved in the caller of this function. 3496 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3497 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3498 3499 // Set the size that is at least reserved in caller of this function. Tail 3500 // call optimized function's reserved stack space needs to be aligned so that 3501 // taking the difference between two stack areas will result in an aligned 3502 // stack. 3503 MinReservedArea = 3504 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3505 FuncInfo->setMinReservedArea(MinReservedArea); 3506 3507 SmallVector<SDValue, 8> MemOps; 3508 3509 // If the function takes variable number of arguments, make a frame index for 3510 // the start of the first vararg value... for expansion of llvm.va_start. 3511 if (isVarArg) { 3512 static const MCPhysReg GPArgRegs[] = { 3513 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3514 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3515 }; 3516 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3517 3518 static const MCPhysReg FPArgRegs[] = { 3519 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3520 PPC::F8 3521 }; 3522 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3523 3524 if (useSoftFloat() || hasSPE()) 3525 NumFPArgRegs = 0; 3526 3527 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3528 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3529 3530 // Make room for NumGPArgRegs and NumFPArgRegs. 3531 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3532 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3533 3534 FuncInfo->setVarArgsStackOffset( 3535 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3536 CCInfo.getNextStackOffset(), true)); 3537 3538 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3539 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3540 3541 // The fixed integer arguments of a variadic function are stored to the 3542 // VarArgsFrameIndex on the stack so that they may be loaded by 3543 // dereferencing the result of va_next. 3544 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3545 // Get an existing live-in vreg, or add a new one. 3546 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3547 if (!VReg) 3548 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3549 3550 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3551 SDValue Store = 3552 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3553 MemOps.push_back(Store); 3554 // Increment the address by four for the next argument to store 3555 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3556 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3557 } 3558 3559 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3560 // is set. 3561 // The double arguments are stored to the VarArgsFrameIndex 3562 // on the stack. 3563 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3564 // Get an existing live-in vreg, or add a new one. 3565 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3566 if (!VReg) 3567 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3568 3569 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3570 SDValue Store = 3571 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3572 MemOps.push_back(Store); 3573 // Increment the address by eight for the next argument to store 3574 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3575 PtrVT); 3576 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3577 } 3578 } 3579 3580 if (!MemOps.empty()) 3581 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3582 3583 return Chain; 3584 } 3585 3586 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3587 // value to MVT::i64 and then truncate to the correct register size. 3588 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3589 EVT ObjectVT, SelectionDAG &DAG, 3590 SDValue ArgVal, 3591 const SDLoc &dl) const { 3592 if (Flags.isSExt()) 3593 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3594 DAG.getValueType(ObjectVT)); 3595 else if (Flags.isZExt()) 3596 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3597 DAG.getValueType(ObjectVT)); 3598 3599 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3600 } 3601 3602 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3603 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3604 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3605 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3606 // TODO: add description of PPC stack frame format, or at least some docs. 3607 // 3608 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3609 bool isLittleEndian = Subtarget.isLittleEndian(); 3610 MachineFunction &MF = DAG.getMachineFunction(); 3611 MachineFrameInfo &MFI = MF.getFrameInfo(); 3612 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3613 3614 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3615 "fastcc not supported on varargs functions"); 3616 3617 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3618 // Potential tail calls could cause overwriting of argument stack slots. 3619 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3620 (CallConv == CallingConv::Fast)); 3621 unsigned PtrByteSize = 8; 3622 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3623 3624 static const MCPhysReg GPR[] = { 3625 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3626 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3627 }; 3628 static const MCPhysReg VR[] = { 3629 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3630 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3631 }; 3632 3633 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3634 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3635 const unsigned Num_VR_Regs = array_lengthof(VR); 3636 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3637 3638 // Do a first pass over the arguments to determine whether the ABI 3639 // guarantees that our caller has allocated the parameter save area 3640 // on its stack frame. In the ELFv1 ABI, this is always the case; 3641 // in the ELFv2 ABI, it is true if this is a vararg function or if 3642 // any parameter is located in a stack slot. 3643 3644 bool HasParameterArea = !isELFv2ABI || isVarArg; 3645 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3646 unsigned NumBytes = LinkageSize; 3647 unsigned AvailableFPRs = Num_FPR_Regs; 3648 unsigned AvailableVRs = Num_VR_Regs; 3649 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3650 if (Ins[i].Flags.isNest()) 3651 continue; 3652 3653 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3654 PtrByteSize, LinkageSize, ParamAreaSize, 3655 NumBytes, AvailableFPRs, AvailableVRs, 3656 Subtarget.hasQPX())) 3657 HasParameterArea = true; 3658 } 3659 3660 // Add DAG nodes to load the arguments or copy them out of registers. On 3661 // entry to a function on PPC, the arguments start after the linkage area, 3662 // although the first ones are often in registers. 3663 3664 unsigned ArgOffset = LinkageSize; 3665 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3666 unsigned &QFPR_idx = FPR_idx; 3667 SmallVector<SDValue, 8> MemOps; 3668 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3669 unsigned CurArgIdx = 0; 3670 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3671 SDValue ArgVal; 3672 bool needsLoad = false; 3673 EVT ObjectVT = Ins[ArgNo].VT; 3674 EVT OrigVT = Ins[ArgNo].ArgVT; 3675 unsigned ObjSize = ObjectVT.getStoreSize(); 3676 unsigned ArgSize = ObjSize; 3677 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3678 if (Ins[ArgNo].isOrigArg()) { 3679 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3680 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3681 } 3682 // We re-align the argument offset for each argument, except when using the 3683 // fast calling convention, when we need to make sure we do that only when 3684 // we'll actually use a stack slot. 3685 unsigned CurArgOffset, Align; 3686 auto ComputeArgOffset = [&]() { 3687 /* Respect alignment of argument on the stack. */ 3688 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3689 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3690 CurArgOffset = ArgOffset; 3691 }; 3692 3693 if (CallConv != CallingConv::Fast) { 3694 ComputeArgOffset(); 3695 3696 /* Compute GPR index associated with argument offset. */ 3697 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3698 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3699 } 3700 3701 // FIXME the codegen can be much improved in some cases. 3702 // We do not have to keep everything in memory. 3703 if (Flags.isByVal()) { 3704 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3705 3706 if (CallConv == CallingConv::Fast) 3707 ComputeArgOffset(); 3708 3709 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3710 ObjSize = Flags.getByValSize(); 3711 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3712 // Empty aggregate parameters do not take up registers. Examples: 3713 // struct { } a; 3714 // union { } b; 3715 // int c[0]; 3716 // etc. However, we have to provide a place-holder in InVals, so 3717 // pretend we have an 8-byte item at the current address for that 3718 // purpose. 3719 if (!ObjSize) { 3720 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3721 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3722 InVals.push_back(FIN); 3723 continue; 3724 } 3725 3726 // Create a stack object covering all stack doublewords occupied 3727 // by the argument. If the argument is (fully or partially) on 3728 // the stack, or if the argument is fully in registers but the 3729 // caller has allocated the parameter save anyway, we can refer 3730 // directly to the caller's stack frame. Otherwise, create a 3731 // local copy in our own frame. 3732 int FI; 3733 if (HasParameterArea || 3734 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3735 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3736 else 3737 FI = MFI.CreateStackObject(ArgSize, Align, false); 3738 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3739 3740 // Handle aggregates smaller than 8 bytes. 3741 if (ObjSize < PtrByteSize) { 3742 // The value of the object is its address, which differs from the 3743 // address of the enclosing doubleword on big-endian systems. 3744 SDValue Arg = FIN; 3745 if (!isLittleEndian) { 3746 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3747 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3748 } 3749 InVals.push_back(Arg); 3750 3751 if (GPR_idx != Num_GPR_Regs) { 3752 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3753 FuncInfo->addLiveInAttr(VReg, Flags); 3754 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3755 SDValue Store; 3756 3757 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3758 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3759 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3760 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3761 MachinePointerInfo(&*FuncArg), ObjType); 3762 } else { 3763 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3764 // store the whole register as-is to the parameter save area 3765 // slot. 3766 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3767 MachinePointerInfo(&*FuncArg)); 3768 } 3769 3770 MemOps.push_back(Store); 3771 } 3772 // Whether we copied from a register or not, advance the offset 3773 // into the parameter save area by a full doubleword. 3774 ArgOffset += PtrByteSize; 3775 continue; 3776 } 3777 3778 // The value of the object is its address, which is the address of 3779 // its first stack doubleword. 3780 InVals.push_back(FIN); 3781 3782 // Store whatever pieces of the object are in registers to memory. 3783 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3784 if (GPR_idx == Num_GPR_Regs) 3785 break; 3786 3787 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3788 FuncInfo->addLiveInAttr(VReg, Flags); 3789 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3790 SDValue Addr = FIN; 3791 if (j) { 3792 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3793 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3794 } 3795 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3796 MachinePointerInfo(&*FuncArg, j)); 3797 MemOps.push_back(Store); 3798 ++GPR_idx; 3799 } 3800 ArgOffset += ArgSize; 3801 continue; 3802 } 3803 3804 switch (ObjectVT.getSimpleVT().SimpleTy) { 3805 default: llvm_unreachable("Unhandled argument type!"); 3806 case MVT::i1: 3807 case MVT::i32: 3808 case MVT::i64: 3809 if (Flags.isNest()) { 3810 // The 'nest' parameter, if any, is passed in R11. 3811 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3812 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3813 3814 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3815 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3816 3817 break; 3818 } 3819 3820 // These can be scalar arguments or elements of an integer array type 3821 // passed directly. Clang may use those instead of "byval" aggregate 3822 // types to avoid forcing arguments to memory unnecessarily. 3823 if (GPR_idx != Num_GPR_Regs) { 3824 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3825 FuncInfo->addLiveInAttr(VReg, Flags); 3826 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3827 3828 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3829 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3830 // value to MVT::i64 and then truncate to the correct register size. 3831 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3832 } else { 3833 if (CallConv == CallingConv::Fast) 3834 ComputeArgOffset(); 3835 3836 needsLoad = true; 3837 ArgSize = PtrByteSize; 3838 } 3839 if (CallConv != CallingConv::Fast || needsLoad) 3840 ArgOffset += 8; 3841 break; 3842 3843 case MVT::f32: 3844 case MVT::f64: 3845 // These can be scalar arguments or elements of a float array type 3846 // passed directly. The latter are used to implement ELFv2 homogenous 3847 // float aggregates. 3848 if (FPR_idx != Num_FPR_Regs) { 3849 unsigned VReg; 3850 3851 if (ObjectVT == MVT::f32) 3852 VReg = MF.addLiveIn(FPR[FPR_idx], 3853 Subtarget.hasP8Vector() 3854 ? &PPC::VSSRCRegClass 3855 : &PPC::F4RCRegClass); 3856 else 3857 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3858 ? &PPC::VSFRCRegClass 3859 : &PPC::F8RCRegClass); 3860 3861 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3862 ++FPR_idx; 3863 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3864 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3865 // once we support fp <-> gpr moves. 3866 3867 // This can only ever happen in the presence of f32 array types, 3868 // since otherwise we never run out of FPRs before running out 3869 // of GPRs. 3870 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3871 FuncInfo->addLiveInAttr(VReg, Flags); 3872 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3873 3874 if (ObjectVT == MVT::f32) { 3875 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3876 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3877 DAG.getConstant(32, dl, MVT::i32)); 3878 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3879 } 3880 3881 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3882 } else { 3883 if (CallConv == CallingConv::Fast) 3884 ComputeArgOffset(); 3885 3886 needsLoad = true; 3887 } 3888 3889 // When passing an array of floats, the array occupies consecutive 3890 // space in the argument area; only round up to the next doubleword 3891 // at the end of the array. Otherwise, each float takes 8 bytes. 3892 if (CallConv != CallingConv::Fast || needsLoad) { 3893 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3894 ArgOffset += ArgSize; 3895 if (Flags.isInConsecutiveRegsLast()) 3896 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3897 } 3898 break; 3899 case MVT::v4f32: 3900 case MVT::v4i32: 3901 case MVT::v8i16: 3902 case MVT::v16i8: 3903 case MVT::v2f64: 3904 case MVT::v2i64: 3905 case MVT::v1i128: 3906 case MVT::f128: 3907 if (!Subtarget.hasQPX()) { 3908 // These can be scalar arguments or elements of a vector array type 3909 // passed directly. The latter are used to implement ELFv2 homogenous 3910 // vector aggregates. 3911 if (VR_idx != Num_VR_Regs) { 3912 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3913 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3914 ++VR_idx; 3915 } else { 3916 if (CallConv == CallingConv::Fast) 3917 ComputeArgOffset(); 3918 needsLoad = true; 3919 } 3920 if (CallConv != CallingConv::Fast || needsLoad) 3921 ArgOffset += 16; 3922 break; 3923 } // not QPX 3924 3925 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3926 "Invalid QPX parameter type"); 3927 LLVM_FALLTHROUGH; 3928 3929 case MVT::v4f64: 3930 case MVT::v4i1: 3931 // QPX vectors are treated like their scalar floating-point subregisters 3932 // (except that they're larger). 3933 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3934 if (QFPR_idx != Num_QFPR_Regs) { 3935 const TargetRegisterClass *RC; 3936 switch (ObjectVT.getSimpleVT().SimpleTy) { 3937 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3938 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3939 default: RC = &PPC::QBRCRegClass; break; 3940 } 3941 3942 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3943 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3944 ++QFPR_idx; 3945 } else { 3946 if (CallConv == CallingConv::Fast) 3947 ComputeArgOffset(); 3948 needsLoad = true; 3949 } 3950 if (CallConv != CallingConv::Fast || needsLoad) 3951 ArgOffset += Sz; 3952 break; 3953 } 3954 3955 // We need to load the argument to a virtual register if we determined 3956 // above that we ran out of physical registers of the appropriate type. 3957 if (needsLoad) { 3958 if (ObjSize < ArgSize && !isLittleEndian) 3959 CurArgOffset += ArgSize - ObjSize; 3960 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3961 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3962 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3963 } 3964 3965 InVals.push_back(ArgVal); 3966 } 3967 3968 // Area that is at least reserved in the caller of this function. 3969 unsigned MinReservedArea; 3970 if (HasParameterArea) 3971 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3972 else 3973 MinReservedArea = LinkageSize; 3974 3975 // Set the size that is at least reserved in caller of this function. Tail 3976 // call optimized functions' reserved stack space needs to be aligned so that 3977 // taking the difference between two stack areas will result in an aligned 3978 // stack. 3979 MinReservedArea = 3980 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3981 FuncInfo->setMinReservedArea(MinReservedArea); 3982 3983 // If the function takes variable number of arguments, make a frame index for 3984 // the start of the first vararg value... for expansion of llvm.va_start. 3985 if (isVarArg) { 3986 int Depth = ArgOffset; 3987 3988 FuncInfo->setVarArgsFrameIndex( 3989 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3990 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3991 3992 // If this function is vararg, store any remaining integer argument regs 3993 // to their spots on the stack so that they may be loaded by dereferencing 3994 // the result of va_next. 3995 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3996 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3997 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3998 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3999 SDValue Store = 4000 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4001 MemOps.push_back(Store); 4002 // Increment the address by four for the next argument to store 4003 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4004 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4005 } 4006 } 4007 4008 if (!MemOps.empty()) 4009 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4010 4011 return Chain; 4012 } 4013 4014 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4015 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4016 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4017 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4018 // TODO: add description of PPC stack frame format, or at least some docs. 4019 // 4020 MachineFunction &MF = DAG.getMachineFunction(); 4021 MachineFrameInfo &MFI = MF.getFrameInfo(); 4022 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4023 4024 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4025 bool isPPC64 = PtrVT == MVT::i64; 4026 // Potential tail calls could cause overwriting of argument stack slots. 4027 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4028 (CallConv == CallingConv::Fast)); 4029 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4030 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4031 unsigned ArgOffset = LinkageSize; 4032 // Area that is at least reserved in caller of this function. 4033 unsigned MinReservedArea = ArgOffset; 4034 4035 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4036 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4037 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4038 }; 4039 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4040 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4041 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4042 }; 4043 static const MCPhysReg VR[] = { 4044 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4045 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4046 }; 4047 4048 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4049 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4050 const unsigned Num_VR_Regs = array_lengthof( VR); 4051 4052 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4053 4054 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4055 4056 // In 32-bit non-varargs functions, the stack space for vectors is after the 4057 // stack space for non-vectors. We do not use this space unless we have 4058 // too many vectors to fit in registers, something that only occurs in 4059 // constructed examples:), but we have to walk the arglist to figure 4060 // that out...for the pathological case, compute VecArgOffset as the 4061 // start of the vector parameter area. Computing VecArgOffset is the 4062 // entire point of the following loop. 4063 unsigned VecArgOffset = ArgOffset; 4064 if (!isVarArg && !isPPC64) { 4065 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4066 ++ArgNo) { 4067 EVT ObjectVT = Ins[ArgNo].VT; 4068 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4069 4070 if (Flags.isByVal()) { 4071 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4072 unsigned ObjSize = Flags.getByValSize(); 4073 unsigned ArgSize = 4074 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4075 VecArgOffset += ArgSize; 4076 continue; 4077 } 4078 4079 switch(ObjectVT.getSimpleVT().SimpleTy) { 4080 default: llvm_unreachable("Unhandled argument type!"); 4081 case MVT::i1: 4082 case MVT::i32: 4083 case MVT::f32: 4084 VecArgOffset += 4; 4085 break; 4086 case MVT::i64: // PPC64 4087 case MVT::f64: 4088 // FIXME: We are guaranteed to be !isPPC64 at this point. 4089 // Does MVT::i64 apply? 4090 VecArgOffset += 8; 4091 break; 4092 case MVT::v4f32: 4093 case MVT::v4i32: 4094 case MVT::v8i16: 4095 case MVT::v16i8: 4096 // Nothing to do, we're only looking at Nonvector args here. 4097 break; 4098 } 4099 } 4100 } 4101 // We've found where the vector parameter area in memory is. Skip the 4102 // first 12 parameters; these don't use that memory. 4103 VecArgOffset = ((VecArgOffset+15)/16)*16; 4104 VecArgOffset += 12*16; 4105 4106 // Add DAG nodes to load the arguments or copy them out of registers. On 4107 // entry to a function on PPC, the arguments start after the linkage area, 4108 // although the first ones are often in registers. 4109 4110 SmallVector<SDValue, 8> MemOps; 4111 unsigned nAltivecParamsAtEnd = 0; 4112 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4113 unsigned CurArgIdx = 0; 4114 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4115 SDValue ArgVal; 4116 bool needsLoad = false; 4117 EVT ObjectVT = Ins[ArgNo].VT; 4118 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4119 unsigned ArgSize = ObjSize; 4120 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4121 if (Ins[ArgNo].isOrigArg()) { 4122 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4123 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4124 } 4125 unsigned CurArgOffset = ArgOffset; 4126 4127 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4128 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4129 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4130 if (isVarArg || isPPC64) { 4131 MinReservedArea = ((MinReservedArea+15)/16)*16; 4132 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4133 Flags, 4134 PtrByteSize); 4135 } else nAltivecParamsAtEnd++; 4136 } else 4137 // Calculate min reserved area. 4138 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4139 Flags, 4140 PtrByteSize); 4141 4142 // FIXME the codegen can be much improved in some cases. 4143 // We do not have to keep everything in memory. 4144 if (Flags.isByVal()) { 4145 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4146 4147 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4148 ObjSize = Flags.getByValSize(); 4149 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4150 // Objects of size 1 and 2 are right justified, everything else is 4151 // left justified. This means the memory address is adjusted forwards. 4152 if (ObjSize==1 || ObjSize==2) { 4153 CurArgOffset = CurArgOffset + (4 - ObjSize); 4154 } 4155 // The value of the object is its address. 4156 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4157 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4158 InVals.push_back(FIN); 4159 if (ObjSize==1 || ObjSize==2) { 4160 if (GPR_idx != Num_GPR_Regs) { 4161 unsigned VReg; 4162 if (isPPC64) 4163 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4164 else 4165 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4166 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4167 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4168 SDValue Store = 4169 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4170 MachinePointerInfo(&*FuncArg), ObjType); 4171 MemOps.push_back(Store); 4172 ++GPR_idx; 4173 } 4174 4175 ArgOffset += PtrByteSize; 4176 4177 continue; 4178 } 4179 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4180 // Store whatever pieces of the object are in registers 4181 // to memory. ArgOffset will be the address of the beginning 4182 // of the object. 4183 if (GPR_idx != Num_GPR_Regs) { 4184 unsigned VReg; 4185 if (isPPC64) 4186 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4187 else 4188 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4189 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4190 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4191 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4192 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4193 MachinePointerInfo(&*FuncArg, j)); 4194 MemOps.push_back(Store); 4195 ++GPR_idx; 4196 ArgOffset += PtrByteSize; 4197 } else { 4198 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4199 break; 4200 } 4201 } 4202 continue; 4203 } 4204 4205 switch (ObjectVT.getSimpleVT().SimpleTy) { 4206 default: llvm_unreachable("Unhandled argument type!"); 4207 case MVT::i1: 4208 case MVT::i32: 4209 if (!isPPC64) { 4210 if (GPR_idx != Num_GPR_Regs) { 4211 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4212 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4213 4214 if (ObjectVT == MVT::i1) 4215 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4216 4217 ++GPR_idx; 4218 } else { 4219 needsLoad = true; 4220 ArgSize = PtrByteSize; 4221 } 4222 // All int arguments reserve stack space in the Darwin ABI. 4223 ArgOffset += PtrByteSize; 4224 break; 4225 } 4226 LLVM_FALLTHROUGH; 4227 case MVT::i64: // PPC64 4228 if (GPR_idx != Num_GPR_Regs) { 4229 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4230 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4231 4232 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4233 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4234 // value to MVT::i64 and then truncate to the correct register size. 4235 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4236 4237 ++GPR_idx; 4238 } else { 4239 needsLoad = true; 4240 ArgSize = PtrByteSize; 4241 } 4242 // All int arguments reserve stack space in the Darwin ABI. 4243 ArgOffset += 8; 4244 break; 4245 4246 case MVT::f32: 4247 case MVT::f64: 4248 // Every 4 bytes of argument space consumes one of the GPRs available for 4249 // argument passing. 4250 if (GPR_idx != Num_GPR_Regs) { 4251 ++GPR_idx; 4252 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4253 ++GPR_idx; 4254 } 4255 if (FPR_idx != Num_FPR_Regs) { 4256 unsigned VReg; 4257 4258 if (ObjectVT == MVT::f32) 4259 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4260 else 4261 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4262 4263 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4264 ++FPR_idx; 4265 } else { 4266 needsLoad = true; 4267 } 4268 4269 // All FP arguments reserve stack space in the Darwin ABI. 4270 ArgOffset += isPPC64 ? 8 : ObjSize; 4271 break; 4272 case MVT::v4f32: 4273 case MVT::v4i32: 4274 case MVT::v8i16: 4275 case MVT::v16i8: 4276 // Note that vector arguments in registers don't reserve stack space, 4277 // except in varargs functions. 4278 if (VR_idx != Num_VR_Regs) { 4279 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4280 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4281 if (isVarArg) { 4282 while ((ArgOffset % 16) != 0) { 4283 ArgOffset += PtrByteSize; 4284 if (GPR_idx != Num_GPR_Regs) 4285 GPR_idx++; 4286 } 4287 ArgOffset += 16; 4288 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4289 } 4290 ++VR_idx; 4291 } else { 4292 if (!isVarArg && !isPPC64) { 4293 // Vectors go after all the nonvectors. 4294 CurArgOffset = VecArgOffset; 4295 VecArgOffset += 16; 4296 } else { 4297 // Vectors are aligned. 4298 ArgOffset = ((ArgOffset+15)/16)*16; 4299 CurArgOffset = ArgOffset; 4300 ArgOffset += 16; 4301 } 4302 needsLoad = true; 4303 } 4304 break; 4305 } 4306 4307 // We need to load the argument to a virtual register if we determined above 4308 // that we ran out of physical registers of the appropriate type. 4309 if (needsLoad) { 4310 int FI = MFI.CreateFixedObject(ObjSize, 4311 CurArgOffset + (ArgSize - ObjSize), 4312 isImmutable); 4313 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4314 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4315 } 4316 4317 InVals.push_back(ArgVal); 4318 } 4319 4320 // Allow for Altivec parameters at the end, if needed. 4321 if (nAltivecParamsAtEnd) { 4322 MinReservedArea = ((MinReservedArea+15)/16)*16; 4323 MinReservedArea += 16*nAltivecParamsAtEnd; 4324 } 4325 4326 // Area that is at least reserved in the caller of this function. 4327 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4328 4329 // Set the size that is at least reserved in caller of this function. Tail 4330 // call optimized functions' reserved stack space needs to be aligned so that 4331 // taking the difference between two stack areas will result in an aligned 4332 // stack. 4333 MinReservedArea = 4334 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4335 FuncInfo->setMinReservedArea(MinReservedArea); 4336 4337 // If the function takes variable number of arguments, make a frame index for 4338 // the start of the first vararg value... for expansion of llvm.va_start. 4339 if (isVarArg) { 4340 int Depth = ArgOffset; 4341 4342 FuncInfo->setVarArgsFrameIndex( 4343 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4344 Depth, true)); 4345 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4346 4347 // If this function is vararg, store any remaining integer argument regs 4348 // to their spots on the stack so that they may be loaded by dereferencing 4349 // the result of va_next. 4350 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4351 unsigned VReg; 4352 4353 if (isPPC64) 4354 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4355 else 4356 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4357 4358 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4359 SDValue Store = 4360 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4361 MemOps.push_back(Store); 4362 // Increment the address by four for the next argument to store 4363 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4364 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4365 } 4366 } 4367 4368 if (!MemOps.empty()) 4369 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4370 4371 return Chain; 4372 } 4373 4374 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4375 /// adjusted to accommodate the arguments for the tailcall. 4376 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4377 unsigned ParamSize) { 4378 4379 if (!isTailCall) return 0; 4380 4381 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4382 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4383 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4384 // Remember only if the new adjustment is bigger. 4385 if (SPDiff < FI->getTailCallSPDelta()) 4386 FI->setTailCallSPDelta(SPDiff); 4387 4388 return SPDiff; 4389 } 4390 4391 static bool isFunctionGlobalAddress(SDValue Callee); 4392 4393 static bool 4394 callsShareTOCBase(const Function *Caller, SDValue Callee, 4395 const TargetMachine &TM) { 4396 // If !G, Callee can be an external symbol. 4397 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4398 if (!G) 4399 return false; 4400 4401 // The medium and large code models are expected to provide a sufficiently 4402 // large TOC to provide all data addressing needs of a module with a 4403 // single TOC. Since each module will be addressed with a single TOC then we 4404 // only need to check that caller and callee don't cross dso boundaries. 4405 if (CodeModel::Medium == TM.getCodeModel() || 4406 CodeModel::Large == TM.getCodeModel()) 4407 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4408 4409 // Otherwise we need to ensure callee and caller are in the same section, 4410 // since the linker may allocate multiple TOCs, and we don't know which 4411 // sections will belong to the same TOC base. 4412 4413 const GlobalValue *GV = G->getGlobal(); 4414 if (!GV->isStrongDefinitionForLinker()) 4415 return false; 4416 4417 // Any explicitly-specified sections and section prefixes must also match. 4418 // Also, if we're using -ffunction-sections, then each function is always in 4419 // a different section (the same is true for COMDAT functions). 4420 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4421 GV->getSection() != Caller->getSection()) 4422 return false; 4423 if (const auto *F = dyn_cast<Function>(GV)) { 4424 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4425 return false; 4426 } 4427 4428 // If the callee might be interposed, then we can't assume the ultimate call 4429 // target will be in the same section. Even in cases where we can assume that 4430 // interposition won't happen, in any case where the linker might insert a 4431 // stub to allow for interposition, we must generate code as though 4432 // interposition might occur. To understand why this matters, consider a 4433 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4434 // in the same section, but a is in a different module (i.e. has a different 4435 // TOC base pointer). If the linker allows for interposition between b and c, 4436 // then it will generate a stub for the call edge between b and c which will 4437 // save the TOC pointer into the designated stack slot allocated by b. If we 4438 // return true here, and therefore allow a tail call between b and c, that 4439 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4440 // pointer into the stack slot allocated by a (where the a -> b stub saved 4441 // a's TOC base pointer). If we're not considering a tail call, but rather, 4442 // whether a nop is needed after the call instruction in b, because the linker 4443 // will insert a stub, it might complain about a missing nop if we omit it 4444 // (although many don't complain in this case). 4445 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4446 return false; 4447 4448 return true; 4449 } 4450 4451 static bool 4452 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4453 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4454 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4455 4456 const unsigned PtrByteSize = 8; 4457 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4458 4459 static const MCPhysReg GPR[] = { 4460 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4461 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4462 }; 4463 static const MCPhysReg VR[] = { 4464 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4465 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4466 }; 4467 4468 const unsigned NumGPRs = array_lengthof(GPR); 4469 const unsigned NumFPRs = 13; 4470 const unsigned NumVRs = array_lengthof(VR); 4471 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4472 4473 unsigned NumBytes = LinkageSize; 4474 unsigned AvailableFPRs = NumFPRs; 4475 unsigned AvailableVRs = NumVRs; 4476 4477 for (const ISD::OutputArg& Param : Outs) { 4478 if (Param.Flags.isNest()) continue; 4479 4480 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4481 PtrByteSize, LinkageSize, ParamAreaSize, 4482 NumBytes, AvailableFPRs, AvailableVRs, 4483 Subtarget.hasQPX())) 4484 return true; 4485 } 4486 return false; 4487 } 4488 4489 static bool 4490 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4491 if (CS.arg_size() != CallerFn->arg_size()) 4492 return false; 4493 4494 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4495 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4496 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4497 4498 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4499 const Value* CalleeArg = *CalleeArgIter; 4500 const Value* CallerArg = &(*CallerArgIter); 4501 if (CalleeArg == CallerArg) 4502 continue; 4503 4504 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4505 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4506 // } 4507 // 1st argument of callee is undef and has the same type as caller. 4508 if (CalleeArg->getType() == CallerArg->getType() && 4509 isa<UndefValue>(CalleeArg)) 4510 continue; 4511 4512 return false; 4513 } 4514 4515 return true; 4516 } 4517 4518 // Returns true if TCO is possible between the callers and callees 4519 // calling conventions. 4520 static bool 4521 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4522 CallingConv::ID CalleeCC) { 4523 // Tail calls are possible with fastcc and ccc. 4524 auto isTailCallableCC = [] (CallingConv::ID CC){ 4525 return CC == CallingConv::C || CC == CallingConv::Fast; 4526 }; 4527 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4528 return false; 4529 4530 // We can safely tail call both fastcc and ccc callees from a c calling 4531 // convention caller. If the caller is fastcc, we may have less stack space 4532 // than a non-fastcc caller with the same signature so disable tail-calls in 4533 // that case. 4534 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4535 } 4536 4537 bool 4538 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4539 SDValue Callee, 4540 CallingConv::ID CalleeCC, 4541 ImmutableCallSite CS, 4542 bool isVarArg, 4543 const SmallVectorImpl<ISD::OutputArg> &Outs, 4544 const SmallVectorImpl<ISD::InputArg> &Ins, 4545 SelectionDAG& DAG) const { 4546 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4547 4548 if (DisableSCO && !TailCallOpt) return false; 4549 4550 // Variadic argument functions are not supported. 4551 if (isVarArg) return false; 4552 4553 auto &Caller = DAG.getMachineFunction().getFunction(); 4554 // Check that the calling conventions are compatible for tco. 4555 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4556 return false; 4557 4558 // Caller contains any byval parameter is not supported. 4559 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4560 return false; 4561 4562 // Callee contains any byval parameter is not supported, too. 4563 // Note: This is a quick work around, because in some cases, e.g. 4564 // caller's stack size > callee's stack size, we are still able to apply 4565 // sibling call optimization. For example, gcc is able to do SCO for caller1 4566 // in the following example, but not for caller2. 4567 // struct test { 4568 // long int a; 4569 // char ary[56]; 4570 // } gTest; 4571 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4572 // b->a = v.a; 4573 // return 0; 4574 // } 4575 // void caller1(struct test a, struct test c, struct test *b) { 4576 // callee(gTest, b); } 4577 // void caller2(struct test *b) { callee(gTest, b); } 4578 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4579 return false; 4580 4581 // If callee and caller use different calling conventions, we cannot pass 4582 // parameters on stack since offsets for the parameter area may be different. 4583 if (Caller.getCallingConv() != CalleeCC && 4584 needStackSlotPassParameters(Subtarget, Outs)) 4585 return false; 4586 4587 // No TCO/SCO on indirect call because Caller have to restore its TOC 4588 if (!isFunctionGlobalAddress(Callee) && 4589 !isa<ExternalSymbolSDNode>(Callee)) 4590 return false; 4591 4592 // If the caller and callee potentially have different TOC bases then we 4593 // cannot tail call since we need to restore the TOC pointer after the call. 4594 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4595 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4596 return false; 4597 4598 // TCO allows altering callee ABI, so we don't have to check further. 4599 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4600 return true; 4601 4602 if (DisableSCO) return false; 4603 4604 // If callee use the same argument list that caller is using, then we can 4605 // apply SCO on this case. If it is not, then we need to check if callee needs 4606 // stack for passing arguments. 4607 if (!hasSameArgumentList(&Caller, CS) && 4608 needStackSlotPassParameters(Subtarget, Outs)) { 4609 return false; 4610 } 4611 4612 return true; 4613 } 4614 4615 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4616 /// for tail call optimization. Targets which want to do tail call 4617 /// optimization should implement this function. 4618 bool 4619 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4620 CallingConv::ID CalleeCC, 4621 bool isVarArg, 4622 const SmallVectorImpl<ISD::InputArg> &Ins, 4623 SelectionDAG& DAG) const { 4624 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4625 return false; 4626 4627 // Variable argument functions are not supported. 4628 if (isVarArg) 4629 return false; 4630 4631 MachineFunction &MF = DAG.getMachineFunction(); 4632 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4633 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4634 // Functions containing by val parameters are not supported. 4635 for (unsigned i = 0; i != Ins.size(); i++) { 4636 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4637 if (Flags.isByVal()) return false; 4638 } 4639 4640 // Non-PIC/GOT tail calls are supported. 4641 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4642 return true; 4643 4644 // At the moment we can only do local tail calls (in same module, hidden 4645 // or protected) if we are generating PIC. 4646 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4647 return G->getGlobal()->hasHiddenVisibility() 4648 || G->getGlobal()->hasProtectedVisibility(); 4649 } 4650 4651 return false; 4652 } 4653 4654 /// isCallCompatibleAddress - Return the immediate to use if the specified 4655 /// 32-bit value is representable in the immediate field of a BxA instruction. 4656 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4657 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4658 if (!C) return nullptr; 4659 4660 int Addr = C->getZExtValue(); 4661 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4662 SignExtend32<26>(Addr) != Addr) 4663 return nullptr; // Top 6 bits have to be sext of immediate. 4664 4665 return DAG 4666 .getConstant( 4667 (int)C->getZExtValue() >> 2, SDLoc(Op), 4668 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4669 .getNode(); 4670 } 4671 4672 namespace { 4673 4674 struct TailCallArgumentInfo { 4675 SDValue Arg; 4676 SDValue FrameIdxOp; 4677 int FrameIdx = 0; 4678 4679 TailCallArgumentInfo() = default; 4680 }; 4681 4682 } // end anonymous namespace 4683 4684 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4685 static void StoreTailCallArgumentsToStackSlot( 4686 SelectionDAG &DAG, SDValue Chain, 4687 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4688 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4689 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4690 SDValue Arg = TailCallArgs[i].Arg; 4691 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4692 int FI = TailCallArgs[i].FrameIdx; 4693 // Store relative to framepointer. 4694 MemOpChains.push_back(DAG.getStore( 4695 Chain, dl, Arg, FIN, 4696 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4697 } 4698 } 4699 4700 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4701 /// the appropriate stack slot for the tail call optimized function call. 4702 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4703 SDValue OldRetAddr, SDValue OldFP, 4704 int SPDiff, const SDLoc &dl) { 4705 if (SPDiff) { 4706 // Calculate the new stack slot for the return address. 4707 MachineFunction &MF = DAG.getMachineFunction(); 4708 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4709 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4710 bool isPPC64 = Subtarget.isPPC64(); 4711 int SlotSize = isPPC64 ? 8 : 4; 4712 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4713 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4714 NewRetAddrLoc, true); 4715 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4716 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4717 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4718 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4719 4720 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4721 // slot as the FP is never overwritten. 4722 if (Subtarget.isDarwinABI()) { 4723 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4724 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4725 true); 4726 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4727 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4728 MachinePointerInfo::getFixedStack( 4729 DAG.getMachineFunction(), NewFPIdx)); 4730 } 4731 } 4732 return Chain; 4733 } 4734 4735 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4736 /// the position of the argument. 4737 static void 4738 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4739 SDValue Arg, int SPDiff, unsigned ArgOffset, 4740 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4741 int Offset = ArgOffset + SPDiff; 4742 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4743 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4744 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4745 SDValue FIN = DAG.getFrameIndex(FI, VT); 4746 TailCallArgumentInfo Info; 4747 Info.Arg = Arg; 4748 Info.FrameIdxOp = FIN; 4749 Info.FrameIdx = FI; 4750 TailCallArguments.push_back(Info); 4751 } 4752 4753 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4754 /// stack slot. Returns the chain as result and the loaded frame pointers in 4755 /// LROpOut/FPOpout. Used when tail calling. 4756 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4757 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4758 SDValue &FPOpOut, const SDLoc &dl) const { 4759 if (SPDiff) { 4760 // Load the LR and FP stack slot for later adjusting. 4761 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4762 LROpOut = getReturnAddrFrameIndex(DAG); 4763 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4764 Chain = SDValue(LROpOut.getNode(), 1); 4765 4766 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4767 // slot as the FP is never overwritten. 4768 if (Subtarget.isDarwinABI()) { 4769 FPOpOut = getFramePointerFrameIndex(DAG); 4770 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4771 Chain = SDValue(FPOpOut.getNode(), 1); 4772 } 4773 } 4774 return Chain; 4775 } 4776 4777 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4778 /// by "Src" to address "Dst" of size "Size". Alignment information is 4779 /// specified by the specific parameter attribute. The copy will be passed as 4780 /// a byval function parameter. 4781 /// Sometimes what we are copying is the end of a larger object, the part that 4782 /// does not fit in registers. 4783 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4784 SDValue Chain, ISD::ArgFlagsTy Flags, 4785 SelectionDAG &DAG, const SDLoc &dl) { 4786 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4787 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4788 false, false, false, MachinePointerInfo(), 4789 MachinePointerInfo()); 4790 } 4791 4792 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4793 /// tail calls. 4794 static void LowerMemOpCallTo( 4795 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4796 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4797 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4798 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4799 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4800 if (!isTailCall) { 4801 if (isVector) { 4802 SDValue StackPtr; 4803 if (isPPC64) 4804 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4805 else 4806 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4807 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4808 DAG.getConstant(ArgOffset, dl, PtrVT)); 4809 } 4810 MemOpChains.push_back( 4811 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4812 // Calculate and remember argument location. 4813 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4814 TailCallArguments); 4815 } 4816 4817 static void 4818 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4819 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4820 SDValue FPOp, 4821 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4822 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4823 // might overwrite each other in case of tail call optimization. 4824 SmallVector<SDValue, 8> MemOpChains2; 4825 // Do not flag preceding copytoreg stuff together with the following stuff. 4826 InFlag = SDValue(); 4827 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4828 MemOpChains2, dl); 4829 if (!MemOpChains2.empty()) 4830 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4831 4832 // Store the return address to the appropriate stack slot. 4833 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4834 4835 // Emit callseq_end just before tailcall node. 4836 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4837 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4838 InFlag = Chain.getValue(1); 4839 } 4840 4841 // Is this global address that of a function that can be called by name? (as 4842 // opposed to something that must hold a descriptor for an indirect call). 4843 static bool isFunctionGlobalAddress(SDValue Callee) { 4844 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4845 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4846 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4847 return false; 4848 4849 return G->getGlobal()->getValueType()->isFunctionTy(); 4850 } 4851 4852 return false; 4853 } 4854 4855 static unsigned 4856 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4857 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4858 bool isPatchPoint, bool hasNest, 4859 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4860 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4861 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4862 bool isPPC64 = Subtarget.isPPC64(); 4863 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4864 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4865 4866 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4867 NodeTys.push_back(MVT::Other); // Returns a chain 4868 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4869 4870 unsigned CallOpc = PPCISD::CALL; 4871 4872 bool needIndirectCall = true; 4873 if (!isSVR4ABI || !isPPC64) 4874 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4875 // If this is an absolute destination address, use the munged value. 4876 Callee = SDValue(Dest, 0); 4877 needIndirectCall = false; 4878 } 4879 4880 // PC-relative references to external symbols should go through $stub, unless 4881 // we're building with the leopard linker or later, which automatically 4882 // synthesizes these stubs. 4883 const TargetMachine &TM = DAG.getTarget(); 4884 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4885 const GlobalValue *GV = nullptr; 4886 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4887 GV = G->getGlobal(); 4888 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4889 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4890 4891 if (isFunctionGlobalAddress(Callee)) { 4892 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4893 // A call to a TLS address is actually an indirect call to a 4894 // thread-specific pointer. 4895 unsigned OpFlags = 0; 4896 if (UsePlt) 4897 OpFlags = PPCII::MO_PLT; 4898 4899 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4900 // every direct call is) turn it into a TargetGlobalAddress / 4901 // TargetExternalSymbol node so that legalize doesn't hack it. 4902 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4903 Callee.getValueType(), 0, OpFlags); 4904 needIndirectCall = false; 4905 } 4906 4907 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4908 unsigned char OpFlags = 0; 4909 4910 if (UsePlt) 4911 OpFlags = PPCII::MO_PLT; 4912 4913 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4914 OpFlags); 4915 needIndirectCall = false; 4916 } 4917 4918 if (isPatchPoint) { 4919 // We'll form an invalid direct call when lowering a patchpoint; the full 4920 // sequence for an indirect call is complicated, and many of the 4921 // instructions introduced might have side effects (and, thus, can't be 4922 // removed later). The call itself will be removed as soon as the 4923 // argument/return lowering is complete, so the fact that it has the wrong 4924 // kind of operands should not really matter. 4925 needIndirectCall = false; 4926 } 4927 4928 if (needIndirectCall) { 4929 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4930 // to do the call, we can't use PPCISD::CALL. 4931 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4932 4933 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4934 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4935 // entry point, but to the function descriptor (the function entry point 4936 // address is part of the function descriptor though). 4937 // The function descriptor is a three doubleword structure with the 4938 // following fields: function entry point, TOC base address and 4939 // environment pointer. 4940 // Thus for a call through a function pointer, the following actions need 4941 // to be performed: 4942 // 1. Save the TOC of the caller in the TOC save area of its stack 4943 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4944 // 2. Load the address of the function entry point from the function 4945 // descriptor. 4946 // 3. Load the TOC of the callee from the function descriptor into r2. 4947 // 4. Load the environment pointer from the function descriptor into 4948 // r11. 4949 // 5. Branch to the function entry point address. 4950 // 6. On return of the callee, the TOC of the caller needs to be 4951 // restored (this is done in FinishCall()). 4952 // 4953 // The loads are scheduled at the beginning of the call sequence, and the 4954 // register copies are flagged together to ensure that no other 4955 // operations can be scheduled in between. E.g. without flagging the 4956 // copies together, a TOC access in the caller could be scheduled between 4957 // the assignment of the callee TOC and the branch to the callee, which 4958 // results in the TOC access going through the TOC of the callee instead 4959 // of going through the TOC of the caller, which leads to incorrect code. 4960 4961 // Load the address of the function entry point from the function 4962 // descriptor. 4963 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4964 if (LDChain.getValueType() == MVT::Glue) 4965 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4966 4967 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4968 ? (MachineMemOperand::MODereferenceable | 4969 MachineMemOperand::MOInvariant) 4970 : MachineMemOperand::MONone; 4971 4972 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4973 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4974 /* Alignment = */ 8, MMOFlags); 4975 4976 // Load environment pointer into r11. 4977 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4978 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4979 SDValue LoadEnvPtr = 4980 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4981 /* Alignment = */ 8, MMOFlags); 4982 4983 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4984 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4985 SDValue TOCPtr = 4986 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4987 /* Alignment = */ 8, MMOFlags); 4988 4989 setUsesTOCBasePtr(DAG); 4990 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4991 InFlag); 4992 Chain = TOCVal.getValue(0); 4993 InFlag = TOCVal.getValue(1); 4994 4995 // If the function call has an explicit 'nest' parameter, it takes the 4996 // place of the environment pointer. 4997 if (!hasNest) { 4998 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4999 InFlag); 5000 5001 Chain = EnvVal.getValue(0); 5002 InFlag = EnvVal.getValue(1); 5003 } 5004 5005 MTCTROps[0] = Chain; 5006 MTCTROps[1] = LoadFuncPtr; 5007 MTCTROps[2] = InFlag; 5008 } 5009 5010 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5011 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5012 InFlag = Chain.getValue(1); 5013 5014 NodeTys.clear(); 5015 NodeTys.push_back(MVT::Other); 5016 NodeTys.push_back(MVT::Glue); 5017 Ops.push_back(Chain); 5018 CallOpc = PPCISD::BCTRL; 5019 Callee.setNode(nullptr); 5020 // Add use of X11 (holding environment pointer) 5021 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5022 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5023 // Add CTR register as callee so a bctr can be emitted later. 5024 if (isTailCall) 5025 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5026 } 5027 5028 // If this is a direct call, pass the chain and the callee. 5029 if (Callee.getNode()) { 5030 Ops.push_back(Chain); 5031 Ops.push_back(Callee); 5032 } 5033 // If this is a tail call add stack pointer delta. 5034 if (isTailCall) 5035 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5036 5037 // Add argument registers to the end of the list so that they are known live 5038 // into the call. 5039 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5040 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5041 RegsToPass[i].second.getValueType())); 5042 5043 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5044 // into the call. 5045 // We do need to reserve X2 to appease the verifier for the PATCHPOINT. 5046 if (isSVR4ABI && isPPC64) { 5047 setUsesTOCBasePtr(DAG); 5048 5049 // We cannot add X2 as an operand here for PATCHPOINT, because there is no 5050 // way to mark dependencies as implicit here. We will add the X2 dependency 5051 // in EmitInstrWithCustomInserter. 5052 if (!isPatchPoint) 5053 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5054 } 5055 5056 return CallOpc; 5057 } 5058 5059 SDValue PPCTargetLowering::LowerCallResult( 5060 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5061 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5062 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5063 SmallVector<CCValAssign, 16> RVLocs; 5064 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5065 *DAG.getContext()); 5066 5067 CCRetInfo.AnalyzeCallResult( 5068 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5069 ? RetCC_PPC_Cold 5070 : RetCC_PPC); 5071 5072 // Copy all of the result registers out of their specified physreg. 5073 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5074 CCValAssign &VA = RVLocs[i]; 5075 assert(VA.isRegLoc() && "Can only return in registers!"); 5076 5077 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5078 VA.getLocReg(), VA.getLocVT(), InFlag); 5079 Chain = Val.getValue(1); 5080 InFlag = Val.getValue(2); 5081 5082 switch (VA.getLocInfo()) { 5083 default: llvm_unreachable("Unknown loc info!"); 5084 case CCValAssign::Full: break; 5085 case CCValAssign::AExt: 5086 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5087 break; 5088 case CCValAssign::ZExt: 5089 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5090 DAG.getValueType(VA.getValVT())); 5091 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5092 break; 5093 case CCValAssign::SExt: 5094 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5095 DAG.getValueType(VA.getValVT())); 5096 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5097 break; 5098 } 5099 5100 InVals.push_back(Val); 5101 } 5102 5103 return Chain; 5104 } 5105 5106 SDValue PPCTargetLowering::FinishCall( 5107 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5108 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5109 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5110 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5111 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5112 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5113 std::vector<EVT> NodeTys; 5114 SmallVector<SDValue, 8> Ops; 5115 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5116 SPDiff, isTailCall, isPatchPoint, hasNest, 5117 RegsToPass, Ops, NodeTys, CS, Subtarget); 5118 5119 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5120 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5121 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5122 5123 // When performing tail call optimization the callee pops its arguments off 5124 // the stack. Account for this here so these bytes can be pushed back on in 5125 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5126 int BytesCalleePops = 5127 (CallConv == CallingConv::Fast && 5128 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5129 5130 // Add a register mask operand representing the call-preserved registers. 5131 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5132 const uint32_t *Mask = 5133 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5134 assert(Mask && "Missing call preserved mask for calling convention"); 5135 Ops.push_back(DAG.getRegisterMask(Mask)); 5136 5137 if (InFlag.getNode()) 5138 Ops.push_back(InFlag); 5139 5140 // Emit tail call. 5141 if (isTailCall) { 5142 assert(((Callee.getOpcode() == ISD::Register && 5143 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5144 Callee.getOpcode() == ISD::TargetExternalSymbol || 5145 Callee.getOpcode() == ISD::TargetGlobalAddress || 5146 isa<ConstantSDNode>(Callee)) && 5147 "Expecting an global address, external symbol, absolute value or register"); 5148 5149 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5150 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5151 } 5152 5153 // Add a NOP immediately after the branch instruction when using the 64-bit 5154 // SVR4 ABI. At link time, if caller and callee are in a different module and 5155 // thus have a different TOC, the call will be replaced with a call to a stub 5156 // function which saves the current TOC, loads the TOC of the callee and 5157 // branches to the callee. The NOP will be replaced with a load instruction 5158 // which restores the TOC of the caller from the TOC save slot of the current 5159 // stack frame. If caller and callee belong to the same module (and have the 5160 // same TOC), the NOP will remain unchanged. 5161 5162 MachineFunction &MF = DAG.getMachineFunction(); 5163 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5164 !isPatchPoint) { 5165 if (CallOpc == PPCISD::BCTRL) { 5166 // This is a call through a function pointer. 5167 // Restore the caller TOC from the save area into R2. 5168 // See PrepareCall() for more information about calls through function 5169 // pointers in the 64-bit SVR4 ABI. 5170 // We are using a target-specific load with r2 hard coded, because the 5171 // result of a target-independent load would never go directly into r2, 5172 // since r2 is a reserved register (which prevents the register allocator 5173 // from allocating it), resulting in an additional register being 5174 // allocated and an unnecessary move instruction being generated. 5175 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5176 5177 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5178 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5179 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5180 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5181 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5182 5183 // The address needs to go after the chain input but before the flag (or 5184 // any other variadic arguments). 5185 Ops.insert(std::next(Ops.begin()), AddTOC); 5186 } else if (CallOpc == PPCISD::CALL && 5187 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5188 // Otherwise insert NOP for non-local calls. 5189 CallOpc = PPCISD::CALL_NOP; 5190 } 5191 } 5192 5193 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5194 InFlag = Chain.getValue(1); 5195 5196 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5197 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5198 InFlag, dl); 5199 if (!Ins.empty()) 5200 InFlag = Chain.getValue(1); 5201 5202 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5203 Ins, dl, DAG, InVals); 5204 } 5205 5206 SDValue 5207 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5208 SmallVectorImpl<SDValue> &InVals) const { 5209 SelectionDAG &DAG = CLI.DAG; 5210 SDLoc &dl = CLI.DL; 5211 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5212 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5213 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5214 SDValue Chain = CLI.Chain; 5215 SDValue Callee = CLI.Callee; 5216 bool &isTailCall = CLI.IsTailCall; 5217 CallingConv::ID CallConv = CLI.CallConv; 5218 bool isVarArg = CLI.IsVarArg; 5219 bool isPatchPoint = CLI.IsPatchPoint; 5220 ImmutableCallSite CS = CLI.CS; 5221 5222 if (isTailCall) { 5223 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5224 isTailCall = false; 5225 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5226 isTailCall = 5227 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5228 isVarArg, Outs, Ins, DAG); 5229 else 5230 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5231 Ins, DAG); 5232 if (isTailCall) { 5233 ++NumTailCalls; 5234 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5235 ++NumSiblingCalls; 5236 5237 assert(isa<GlobalAddressSDNode>(Callee) && 5238 "Callee should be an llvm::Function object."); 5239 LLVM_DEBUG( 5240 const GlobalValue *GV = 5241 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5242 const unsigned Width = 5243 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5244 dbgs() << "TCO caller: " 5245 << left_justify(DAG.getMachineFunction().getName(), Width) 5246 << ", callee linkage: " << GV->getVisibility() << ", " 5247 << GV->getLinkage() << "\n"); 5248 } 5249 } 5250 5251 if (!isTailCall && CS && CS.isMustTailCall()) 5252 report_fatal_error("failed to perform tail call elimination on a call " 5253 "site marked musttail"); 5254 5255 // When long calls (i.e. indirect calls) are always used, calls are always 5256 // made via function pointer. If we have a function name, first translate it 5257 // into a pointer. 5258 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5259 !isTailCall) 5260 Callee = LowerGlobalAddress(Callee, DAG); 5261 5262 if (Subtarget.isSVR4ABI()) { 5263 if (Subtarget.isPPC64()) 5264 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5265 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5266 dl, DAG, InVals, CS); 5267 else 5268 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5269 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5270 dl, DAG, InVals, CS); 5271 } 5272 5273 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5274 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5275 dl, DAG, InVals, CS); 5276 } 5277 5278 SDValue PPCTargetLowering::LowerCall_32SVR4( 5279 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5280 bool isTailCall, bool isPatchPoint, 5281 const SmallVectorImpl<ISD::OutputArg> &Outs, 5282 const SmallVectorImpl<SDValue> &OutVals, 5283 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5284 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5285 ImmutableCallSite CS) const { 5286 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5287 // of the 32-bit SVR4 ABI stack frame layout. 5288 5289 assert((CallConv == CallingConv::C || 5290 CallConv == CallingConv::Cold || 5291 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5292 5293 unsigned PtrByteSize = 4; 5294 5295 MachineFunction &MF = DAG.getMachineFunction(); 5296 5297 // Mark this function as potentially containing a function that contains a 5298 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5299 // and restoring the callers stack pointer in this functions epilog. This is 5300 // done because by tail calling the called function might overwrite the value 5301 // in this function's (MF) stack pointer stack slot 0(SP). 5302 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5303 CallConv == CallingConv::Fast) 5304 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5305 5306 // Count how many bytes are to be pushed on the stack, including the linkage 5307 // area, parameter list area and the part of the local variable space which 5308 // contains copies of aggregates which are passed by value. 5309 5310 // Assign locations to all of the outgoing arguments. 5311 SmallVector<CCValAssign, 16> ArgLocs; 5312 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5313 5314 // Reserve space for the linkage area on the stack. 5315 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5316 PtrByteSize); 5317 if (useSoftFloat()) 5318 CCInfo.PreAnalyzeCallOperands(Outs); 5319 5320 if (isVarArg) { 5321 // Handle fixed and variable vector arguments differently. 5322 // Fixed vector arguments go into registers as long as registers are 5323 // available. Variable vector arguments always go into memory. 5324 unsigned NumArgs = Outs.size(); 5325 5326 for (unsigned i = 0; i != NumArgs; ++i) { 5327 MVT ArgVT = Outs[i].VT; 5328 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5329 bool Result; 5330 5331 if (Outs[i].IsFixed) { 5332 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5333 CCInfo); 5334 } else { 5335 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5336 ArgFlags, CCInfo); 5337 } 5338 5339 if (Result) { 5340 #ifndef NDEBUG 5341 errs() << "Call operand #" << i << " has unhandled type " 5342 << EVT(ArgVT).getEVTString() << "\n"; 5343 #endif 5344 llvm_unreachable(nullptr); 5345 } 5346 } 5347 } else { 5348 // All arguments are treated the same. 5349 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5350 } 5351 CCInfo.clearWasPPCF128(); 5352 5353 // Assign locations to all of the outgoing aggregate by value arguments. 5354 SmallVector<CCValAssign, 16> ByValArgLocs; 5355 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5356 5357 // Reserve stack space for the allocations in CCInfo. 5358 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5359 5360 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5361 5362 // Size of the linkage area, parameter list area and the part of the local 5363 // space variable where copies of aggregates which are passed by value are 5364 // stored. 5365 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5366 5367 // Calculate by how many bytes the stack has to be adjusted in case of tail 5368 // call optimization. 5369 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5370 5371 // Adjust the stack pointer for the new arguments... 5372 // These operations are automatically eliminated by the prolog/epilog pass 5373 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5374 SDValue CallSeqStart = Chain; 5375 5376 // Load the return address and frame pointer so it can be moved somewhere else 5377 // later. 5378 SDValue LROp, FPOp; 5379 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5380 5381 // Set up a copy of the stack pointer for use loading and storing any 5382 // arguments that may not fit in the registers available for argument 5383 // passing. 5384 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5385 5386 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5387 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5388 SmallVector<SDValue, 8> MemOpChains; 5389 5390 bool seenFloatArg = false; 5391 // Walk the register/memloc assignments, inserting copies/loads. 5392 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5393 i != e; 5394 ++i) { 5395 CCValAssign &VA = ArgLocs[i]; 5396 SDValue Arg = OutVals[i]; 5397 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5398 5399 if (Flags.isByVal()) { 5400 // Argument is an aggregate which is passed by value, thus we need to 5401 // create a copy of it in the local variable space of the current stack 5402 // frame (which is the stack frame of the caller) and pass the address of 5403 // this copy to the callee. 5404 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5405 CCValAssign &ByValVA = ByValArgLocs[j++]; 5406 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5407 5408 // Memory reserved in the local variable space of the callers stack frame. 5409 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5410 5411 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5412 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5413 StackPtr, PtrOff); 5414 5415 // Create a copy of the argument in the local area of the current 5416 // stack frame. 5417 SDValue MemcpyCall = 5418 CreateCopyOfByValArgument(Arg, PtrOff, 5419 CallSeqStart.getNode()->getOperand(0), 5420 Flags, DAG, dl); 5421 5422 // This must go outside the CALLSEQ_START..END. 5423 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5424 SDLoc(MemcpyCall)); 5425 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5426 NewCallSeqStart.getNode()); 5427 Chain = CallSeqStart = NewCallSeqStart; 5428 5429 // Pass the address of the aggregate copy on the stack either in a 5430 // physical register or in the parameter list area of the current stack 5431 // frame to the callee. 5432 Arg = PtrOff; 5433 } 5434 5435 // When useCRBits() is true, there can be i1 arguments. 5436 // It is because getRegisterType(MVT::i1) => MVT::i1, 5437 // and for other integer types getRegisterType() => MVT::i32. 5438 // Extend i1 and ensure callee will get i32. 5439 if (Arg.getValueType() == MVT::i1) 5440 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5441 dl, MVT::i32, Arg); 5442 5443 if (VA.isRegLoc()) { 5444 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5445 // Put argument in a physical register. 5446 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5447 } else { 5448 // Put argument in the parameter list area of the current stack frame. 5449 assert(VA.isMemLoc()); 5450 unsigned LocMemOffset = VA.getLocMemOffset(); 5451 5452 if (!isTailCall) { 5453 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5454 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5455 StackPtr, PtrOff); 5456 5457 MemOpChains.push_back( 5458 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5459 } else { 5460 // Calculate and remember argument location. 5461 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5462 TailCallArguments); 5463 } 5464 } 5465 } 5466 5467 if (!MemOpChains.empty()) 5468 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5469 5470 // Build a sequence of copy-to-reg nodes chained together with token chain 5471 // and flag operands which copy the outgoing args into the appropriate regs. 5472 SDValue InFlag; 5473 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5474 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5475 RegsToPass[i].second, InFlag); 5476 InFlag = Chain.getValue(1); 5477 } 5478 5479 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5480 // registers. 5481 if (isVarArg) { 5482 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5483 SDValue Ops[] = { Chain, InFlag }; 5484 5485 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5486 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5487 5488 InFlag = Chain.getValue(1); 5489 } 5490 5491 if (isTailCall) 5492 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5493 TailCallArguments); 5494 5495 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5496 /* unused except on PPC64 ELFv1 */ false, DAG, 5497 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5498 NumBytes, Ins, InVals, CS); 5499 } 5500 5501 // Copy an argument into memory, being careful to do this outside the 5502 // call sequence for the call to which the argument belongs. 5503 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5504 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5505 SelectionDAG &DAG, const SDLoc &dl) const { 5506 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5507 CallSeqStart.getNode()->getOperand(0), 5508 Flags, DAG, dl); 5509 // The MEMCPY must go outside the CALLSEQ_START..END. 5510 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5511 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5512 SDLoc(MemcpyCall)); 5513 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5514 NewCallSeqStart.getNode()); 5515 return NewCallSeqStart; 5516 } 5517 5518 SDValue PPCTargetLowering::LowerCall_64SVR4( 5519 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5520 bool isTailCall, bool isPatchPoint, 5521 const SmallVectorImpl<ISD::OutputArg> &Outs, 5522 const SmallVectorImpl<SDValue> &OutVals, 5523 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5524 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5525 ImmutableCallSite CS) const { 5526 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5527 bool isLittleEndian = Subtarget.isLittleEndian(); 5528 unsigned NumOps = Outs.size(); 5529 bool hasNest = false; 5530 bool IsSibCall = false; 5531 5532 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5533 unsigned PtrByteSize = 8; 5534 5535 MachineFunction &MF = DAG.getMachineFunction(); 5536 5537 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5538 IsSibCall = true; 5539 5540 // Mark this function as potentially containing a function that contains a 5541 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5542 // and restoring the callers stack pointer in this functions epilog. This is 5543 // done because by tail calling the called function might overwrite the value 5544 // in this function's (MF) stack pointer stack slot 0(SP). 5545 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5546 CallConv == CallingConv::Fast) 5547 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5548 5549 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5550 "fastcc not supported on varargs functions"); 5551 5552 // Count how many bytes are to be pushed on the stack, including the linkage 5553 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5554 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5555 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5556 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5557 unsigned NumBytes = LinkageSize; 5558 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5559 unsigned &QFPR_idx = FPR_idx; 5560 5561 static const MCPhysReg GPR[] = { 5562 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5563 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5564 }; 5565 static const MCPhysReg VR[] = { 5566 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5567 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5568 }; 5569 5570 const unsigned NumGPRs = array_lengthof(GPR); 5571 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5572 const unsigned NumVRs = array_lengthof(VR); 5573 const unsigned NumQFPRs = NumFPRs; 5574 5575 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5576 // can be passed to the callee in registers. 5577 // For the fast calling convention, there is another check below. 5578 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5579 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5580 if (!HasParameterArea) { 5581 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5582 unsigned AvailableFPRs = NumFPRs; 5583 unsigned AvailableVRs = NumVRs; 5584 unsigned NumBytesTmp = NumBytes; 5585 for (unsigned i = 0; i != NumOps; ++i) { 5586 if (Outs[i].Flags.isNest()) continue; 5587 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5588 PtrByteSize, LinkageSize, ParamAreaSize, 5589 NumBytesTmp, AvailableFPRs, AvailableVRs, 5590 Subtarget.hasQPX())) 5591 HasParameterArea = true; 5592 } 5593 } 5594 5595 // When using the fast calling convention, we don't provide backing for 5596 // arguments that will be in registers. 5597 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5598 5599 // Avoid allocating parameter area for fastcc functions if all the arguments 5600 // can be passed in the registers. 5601 if (CallConv == CallingConv::Fast) 5602 HasParameterArea = false; 5603 5604 // Add up all the space actually used. 5605 for (unsigned i = 0; i != NumOps; ++i) { 5606 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5607 EVT ArgVT = Outs[i].VT; 5608 EVT OrigVT = Outs[i].ArgVT; 5609 5610 if (Flags.isNest()) 5611 continue; 5612 5613 if (CallConv == CallingConv::Fast) { 5614 if (Flags.isByVal()) { 5615 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5616 if (NumGPRsUsed > NumGPRs) 5617 HasParameterArea = true; 5618 } else { 5619 switch (ArgVT.getSimpleVT().SimpleTy) { 5620 default: llvm_unreachable("Unexpected ValueType for argument!"); 5621 case MVT::i1: 5622 case MVT::i32: 5623 case MVT::i64: 5624 if (++NumGPRsUsed <= NumGPRs) 5625 continue; 5626 break; 5627 case MVT::v4i32: 5628 case MVT::v8i16: 5629 case MVT::v16i8: 5630 case MVT::v2f64: 5631 case MVT::v2i64: 5632 case MVT::v1i128: 5633 case MVT::f128: 5634 if (++NumVRsUsed <= NumVRs) 5635 continue; 5636 break; 5637 case MVT::v4f32: 5638 // When using QPX, this is handled like a FP register, otherwise, it 5639 // is an Altivec register. 5640 if (Subtarget.hasQPX()) { 5641 if (++NumFPRsUsed <= NumFPRs) 5642 continue; 5643 } else { 5644 if (++NumVRsUsed <= NumVRs) 5645 continue; 5646 } 5647 break; 5648 case MVT::f32: 5649 case MVT::f64: 5650 case MVT::v4f64: // QPX 5651 case MVT::v4i1: // QPX 5652 if (++NumFPRsUsed <= NumFPRs) 5653 continue; 5654 break; 5655 } 5656 HasParameterArea = true; 5657 } 5658 } 5659 5660 /* Respect alignment of argument on the stack. */ 5661 unsigned Align = 5662 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5663 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5664 5665 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5666 if (Flags.isInConsecutiveRegsLast()) 5667 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5668 } 5669 5670 unsigned NumBytesActuallyUsed = NumBytes; 5671 5672 // In the old ELFv1 ABI, 5673 // the prolog code of the callee may store up to 8 GPR argument registers to 5674 // the stack, allowing va_start to index over them in memory if its varargs. 5675 // Because we cannot tell if this is needed on the caller side, we have to 5676 // conservatively assume that it is needed. As such, make sure we have at 5677 // least enough stack space for the caller to store the 8 GPRs. 5678 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5679 // really requires memory operands, e.g. a vararg function. 5680 if (HasParameterArea) 5681 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5682 else 5683 NumBytes = LinkageSize; 5684 5685 // Tail call needs the stack to be aligned. 5686 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5687 CallConv == CallingConv::Fast) 5688 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5689 5690 int SPDiff = 0; 5691 5692 // Calculate by how many bytes the stack has to be adjusted in case of tail 5693 // call optimization. 5694 if (!IsSibCall) 5695 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5696 5697 // To protect arguments on the stack from being clobbered in a tail call, 5698 // force all the loads to happen before doing any other lowering. 5699 if (isTailCall) 5700 Chain = DAG.getStackArgumentTokenFactor(Chain); 5701 5702 // Adjust the stack pointer for the new arguments... 5703 // These operations are automatically eliminated by the prolog/epilog pass 5704 if (!IsSibCall) 5705 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5706 SDValue CallSeqStart = Chain; 5707 5708 // Load the return address and frame pointer so it can be move somewhere else 5709 // later. 5710 SDValue LROp, FPOp; 5711 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5712 5713 // Set up a copy of the stack pointer for use loading and storing any 5714 // arguments that may not fit in the registers available for argument 5715 // passing. 5716 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5717 5718 // Figure out which arguments are going to go in registers, and which in 5719 // memory. Also, if this is a vararg function, floating point operations 5720 // must be stored to our stack, and loaded into integer regs as well, if 5721 // any integer regs are available for argument passing. 5722 unsigned ArgOffset = LinkageSize; 5723 5724 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5725 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5726 5727 SmallVector<SDValue, 8> MemOpChains; 5728 for (unsigned i = 0; i != NumOps; ++i) { 5729 SDValue Arg = OutVals[i]; 5730 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5731 EVT ArgVT = Outs[i].VT; 5732 EVT OrigVT = Outs[i].ArgVT; 5733 5734 // PtrOff will be used to store the current argument to the stack if a 5735 // register cannot be found for it. 5736 SDValue PtrOff; 5737 5738 // We re-align the argument offset for each argument, except when using the 5739 // fast calling convention, when we need to make sure we do that only when 5740 // we'll actually use a stack slot. 5741 auto ComputePtrOff = [&]() { 5742 /* Respect alignment of argument on the stack. */ 5743 unsigned Align = 5744 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5745 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5746 5747 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5748 5749 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5750 }; 5751 5752 if (CallConv != CallingConv::Fast) { 5753 ComputePtrOff(); 5754 5755 /* Compute GPR index associated with argument offset. */ 5756 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5757 GPR_idx = std::min(GPR_idx, NumGPRs); 5758 } 5759 5760 // Promote integers to 64-bit values. 5761 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5762 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5763 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5764 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5765 } 5766 5767 // FIXME memcpy is used way more than necessary. Correctness first. 5768 // Note: "by value" is code for passing a structure by value, not 5769 // basic types. 5770 if (Flags.isByVal()) { 5771 // Note: Size includes alignment padding, so 5772 // struct x { short a; char b; } 5773 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5774 // These are the proper values we need for right-justifying the 5775 // aggregate in a parameter register. 5776 unsigned Size = Flags.getByValSize(); 5777 5778 // An empty aggregate parameter takes up no storage and no 5779 // registers. 5780 if (Size == 0) 5781 continue; 5782 5783 if (CallConv == CallingConv::Fast) 5784 ComputePtrOff(); 5785 5786 // All aggregates smaller than 8 bytes must be passed right-justified. 5787 if (Size==1 || Size==2 || Size==4) { 5788 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5789 if (GPR_idx != NumGPRs) { 5790 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5791 MachinePointerInfo(), VT); 5792 MemOpChains.push_back(Load.getValue(1)); 5793 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5794 5795 ArgOffset += PtrByteSize; 5796 continue; 5797 } 5798 } 5799 5800 if (GPR_idx == NumGPRs && Size < 8) { 5801 SDValue AddPtr = PtrOff; 5802 if (!isLittleEndian) { 5803 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5804 PtrOff.getValueType()); 5805 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5806 } 5807 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5808 CallSeqStart, 5809 Flags, DAG, dl); 5810 ArgOffset += PtrByteSize; 5811 continue; 5812 } 5813 // Copy entire object into memory. There are cases where gcc-generated 5814 // code assumes it is there, even if it could be put entirely into 5815 // registers. (This is not what the doc says.) 5816 5817 // FIXME: The above statement is likely due to a misunderstanding of the 5818 // documents. All arguments must be copied into the parameter area BY 5819 // THE CALLEE in the event that the callee takes the address of any 5820 // formal argument. That has not yet been implemented. However, it is 5821 // reasonable to use the stack area as a staging area for the register 5822 // load. 5823 5824 // Skip this for small aggregates, as we will use the same slot for a 5825 // right-justified copy, below. 5826 if (Size >= 8) 5827 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5828 CallSeqStart, 5829 Flags, DAG, dl); 5830 5831 // When a register is available, pass a small aggregate right-justified. 5832 if (Size < 8 && GPR_idx != NumGPRs) { 5833 // The easiest way to get this right-justified in a register 5834 // is to copy the structure into the rightmost portion of a 5835 // local variable slot, then load the whole slot into the 5836 // register. 5837 // FIXME: The memcpy seems to produce pretty awful code for 5838 // small aggregates, particularly for packed ones. 5839 // FIXME: It would be preferable to use the slot in the 5840 // parameter save area instead of a new local variable. 5841 SDValue AddPtr = PtrOff; 5842 if (!isLittleEndian) { 5843 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5844 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5845 } 5846 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5847 CallSeqStart, 5848 Flags, DAG, dl); 5849 5850 // Load the slot into the register. 5851 SDValue Load = 5852 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5853 MemOpChains.push_back(Load.getValue(1)); 5854 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5855 5856 // Done with this argument. 5857 ArgOffset += PtrByteSize; 5858 continue; 5859 } 5860 5861 // For aggregates larger than PtrByteSize, copy the pieces of the 5862 // object that fit into registers from the parameter save area. 5863 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5864 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5865 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5866 if (GPR_idx != NumGPRs) { 5867 SDValue Load = 5868 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5869 MemOpChains.push_back(Load.getValue(1)); 5870 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5871 ArgOffset += PtrByteSize; 5872 } else { 5873 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5874 break; 5875 } 5876 } 5877 continue; 5878 } 5879 5880 switch (Arg.getSimpleValueType().SimpleTy) { 5881 default: llvm_unreachable("Unexpected ValueType for argument!"); 5882 case MVT::i1: 5883 case MVT::i32: 5884 case MVT::i64: 5885 if (Flags.isNest()) { 5886 // The 'nest' parameter, if any, is passed in R11. 5887 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5888 hasNest = true; 5889 break; 5890 } 5891 5892 // These can be scalar arguments or elements of an integer array type 5893 // passed directly. Clang may use those instead of "byval" aggregate 5894 // types to avoid forcing arguments to memory unnecessarily. 5895 if (GPR_idx != NumGPRs) { 5896 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5897 } else { 5898 if (CallConv == CallingConv::Fast) 5899 ComputePtrOff(); 5900 5901 assert(HasParameterArea && 5902 "Parameter area must exist to pass an argument in memory."); 5903 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5904 true, isTailCall, false, MemOpChains, 5905 TailCallArguments, dl); 5906 if (CallConv == CallingConv::Fast) 5907 ArgOffset += PtrByteSize; 5908 } 5909 if (CallConv != CallingConv::Fast) 5910 ArgOffset += PtrByteSize; 5911 break; 5912 case MVT::f32: 5913 case MVT::f64: { 5914 // These can be scalar arguments or elements of a float array type 5915 // passed directly. The latter are used to implement ELFv2 homogenous 5916 // float aggregates. 5917 5918 // Named arguments go into FPRs first, and once they overflow, the 5919 // remaining arguments go into GPRs and then the parameter save area. 5920 // Unnamed arguments for vararg functions always go to GPRs and 5921 // then the parameter save area. For now, put all arguments to vararg 5922 // routines always in both locations (FPR *and* GPR or stack slot). 5923 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5924 bool NeededLoad = false; 5925 5926 // First load the argument into the next available FPR. 5927 if (FPR_idx != NumFPRs) 5928 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5929 5930 // Next, load the argument into GPR or stack slot if needed. 5931 if (!NeedGPROrStack) 5932 ; 5933 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5934 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5935 // once we support fp <-> gpr moves. 5936 5937 // In the non-vararg case, this can only ever happen in the 5938 // presence of f32 array types, since otherwise we never run 5939 // out of FPRs before running out of GPRs. 5940 SDValue ArgVal; 5941 5942 // Double values are always passed in a single GPR. 5943 if (Arg.getValueType() != MVT::f32) { 5944 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5945 5946 // Non-array float values are extended and passed in a GPR. 5947 } else if (!Flags.isInConsecutiveRegs()) { 5948 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5949 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5950 5951 // If we have an array of floats, we collect every odd element 5952 // together with its predecessor into one GPR. 5953 } else if (ArgOffset % PtrByteSize != 0) { 5954 SDValue Lo, Hi; 5955 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5956 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5957 if (!isLittleEndian) 5958 std::swap(Lo, Hi); 5959 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5960 5961 // The final element, if even, goes into the first half of a GPR. 5962 } else if (Flags.isInConsecutiveRegsLast()) { 5963 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5964 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5965 if (!isLittleEndian) 5966 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5967 DAG.getConstant(32, dl, MVT::i32)); 5968 5969 // Non-final even elements are skipped; they will be handled 5970 // together the with subsequent argument on the next go-around. 5971 } else 5972 ArgVal = SDValue(); 5973 5974 if (ArgVal.getNode()) 5975 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5976 } else { 5977 if (CallConv == CallingConv::Fast) 5978 ComputePtrOff(); 5979 5980 // Single-precision floating-point values are mapped to the 5981 // second (rightmost) word of the stack doubleword. 5982 if (Arg.getValueType() == MVT::f32 && 5983 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5984 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5985 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5986 } 5987 5988 assert(HasParameterArea && 5989 "Parameter area must exist to pass an argument in memory."); 5990 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5991 true, isTailCall, false, MemOpChains, 5992 TailCallArguments, dl); 5993 5994 NeededLoad = true; 5995 } 5996 // When passing an array of floats, the array occupies consecutive 5997 // space in the argument area; only round up to the next doubleword 5998 // at the end of the array. Otherwise, each float takes 8 bytes. 5999 if (CallConv != CallingConv::Fast || NeededLoad) { 6000 ArgOffset += (Arg.getValueType() == MVT::f32 && 6001 Flags.isInConsecutiveRegs()) ? 4 : 8; 6002 if (Flags.isInConsecutiveRegsLast()) 6003 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6004 } 6005 break; 6006 } 6007 case MVT::v4f32: 6008 case MVT::v4i32: 6009 case MVT::v8i16: 6010 case MVT::v16i8: 6011 case MVT::v2f64: 6012 case MVT::v2i64: 6013 case MVT::v1i128: 6014 case MVT::f128: 6015 if (!Subtarget.hasQPX()) { 6016 // These can be scalar arguments or elements of a vector array type 6017 // passed directly. The latter are used to implement ELFv2 homogenous 6018 // vector aggregates. 6019 6020 // For a varargs call, named arguments go into VRs or on the stack as 6021 // usual; unnamed arguments always go to the stack or the corresponding 6022 // GPRs when within range. For now, we always put the value in both 6023 // locations (or even all three). 6024 if (isVarArg) { 6025 assert(HasParameterArea && 6026 "Parameter area must exist if we have a varargs call."); 6027 // We could elide this store in the case where the object fits 6028 // entirely in R registers. Maybe later. 6029 SDValue Store = 6030 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6031 MemOpChains.push_back(Store); 6032 if (VR_idx != NumVRs) { 6033 SDValue Load = 6034 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6035 MemOpChains.push_back(Load.getValue(1)); 6036 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6037 } 6038 ArgOffset += 16; 6039 for (unsigned i=0; i<16; i+=PtrByteSize) { 6040 if (GPR_idx == NumGPRs) 6041 break; 6042 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6043 DAG.getConstant(i, dl, PtrVT)); 6044 SDValue Load = 6045 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6046 MemOpChains.push_back(Load.getValue(1)); 6047 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6048 } 6049 break; 6050 } 6051 6052 // Non-varargs Altivec params go into VRs or on the stack. 6053 if (VR_idx != NumVRs) { 6054 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6055 } else { 6056 if (CallConv == CallingConv::Fast) 6057 ComputePtrOff(); 6058 6059 assert(HasParameterArea && 6060 "Parameter area must exist to pass an argument in memory."); 6061 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6062 true, isTailCall, true, MemOpChains, 6063 TailCallArguments, dl); 6064 if (CallConv == CallingConv::Fast) 6065 ArgOffset += 16; 6066 } 6067 6068 if (CallConv != CallingConv::Fast) 6069 ArgOffset += 16; 6070 break; 6071 } // not QPX 6072 6073 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6074 "Invalid QPX parameter type"); 6075 6076 LLVM_FALLTHROUGH; 6077 case MVT::v4f64: 6078 case MVT::v4i1: { 6079 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6080 if (isVarArg) { 6081 assert(HasParameterArea && 6082 "Parameter area must exist if we have a varargs call."); 6083 // We could elide this store in the case where the object fits 6084 // entirely in R registers. Maybe later. 6085 SDValue Store = 6086 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6087 MemOpChains.push_back(Store); 6088 if (QFPR_idx != NumQFPRs) { 6089 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6090 PtrOff, MachinePointerInfo()); 6091 MemOpChains.push_back(Load.getValue(1)); 6092 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6093 } 6094 ArgOffset += (IsF32 ? 16 : 32); 6095 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6096 if (GPR_idx == NumGPRs) 6097 break; 6098 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6099 DAG.getConstant(i, dl, PtrVT)); 6100 SDValue Load = 6101 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6102 MemOpChains.push_back(Load.getValue(1)); 6103 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6104 } 6105 break; 6106 } 6107 6108 // Non-varargs QPX params go into registers or on the stack. 6109 if (QFPR_idx != NumQFPRs) { 6110 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6111 } else { 6112 if (CallConv == CallingConv::Fast) 6113 ComputePtrOff(); 6114 6115 assert(HasParameterArea && 6116 "Parameter area must exist to pass an argument in memory."); 6117 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6118 true, isTailCall, true, MemOpChains, 6119 TailCallArguments, dl); 6120 if (CallConv == CallingConv::Fast) 6121 ArgOffset += (IsF32 ? 16 : 32); 6122 } 6123 6124 if (CallConv != CallingConv::Fast) 6125 ArgOffset += (IsF32 ? 16 : 32); 6126 break; 6127 } 6128 } 6129 } 6130 6131 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6132 "mismatch in size of parameter area"); 6133 (void)NumBytesActuallyUsed; 6134 6135 if (!MemOpChains.empty()) 6136 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6137 6138 // Check if this is an indirect call (MTCTR/BCTRL). 6139 // See PrepareCall() for more information about calls through function 6140 // pointers in the 64-bit SVR4 ABI. 6141 if (!isTailCall && !isPatchPoint && 6142 !isFunctionGlobalAddress(Callee) && 6143 !isa<ExternalSymbolSDNode>(Callee)) { 6144 // Load r2 into a virtual register and store it to the TOC save area. 6145 setUsesTOCBasePtr(DAG); 6146 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6147 // TOC save area offset. 6148 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6149 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6150 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6151 Chain = DAG.getStore( 6152 Val.getValue(1), dl, Val, AddPtr, 6153 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6154 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6155 // This does not mean the MTCTR instruction must use R12; it's easier 6156 // to model this as an extra parameter, so do that. 6157 if (isELFv2ABI && !isPatchPoint) 6158 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6159 } 6160 6161 // Build a sequence of copy-to-reg nodes chained together with token chain 6162 // and flag operands which copy the outgoing args into the appropriate regs. 6163 SDValue InFlag; 6164 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6165 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6166 RegsToPass[i].second, InFlag); 6167 InFlag = Chain.getValue(1); 6168 } 6169 6170 if (isTailCall && !IsSibCall) 6171 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6172 TailCallArguments); 6173 6174 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6175 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6176 SPDiff, NumBytes, Ins, InVals, CS); 6177 } 6178 6179 SDValue PPCTargetLowering::LowerCall_Darwin( 6180 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6181 bool isTailCall, bool isPatchPoint, 6182 const SmallVectorImpl<ISD::OutputArg> &Outs, 6183 const SmallVectorImpl<SDValue> &OutVals, 6184 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6185 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6186 ImmutableCallSite CS) const { 6187 unsigned NumOps = Outs.size(); 6188 6189 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6190 bool isPPC64 = PtrVT == MVT::i64; 6191 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6192 6193 MachineFunction &MF = DAG.getMachineFunction(); 6194 6195 // Mark this function as potentially containing a function that contains a 6196 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6197 // and restoring the callers stack pointer in this functions epilog. This is 6198 // done because by tail calling the called function might overwrite the value 6199 // in this function's (MF) stack pointer stack slot 0(SP). 6200 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6201 CallConv == CallingConv::Fast) 6202 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6203 6204 // Count how many bytes are to be pushed on the stack, including the linkage 6205 // area, and parameter passing area. We start with 24/48 bytes, which is 6206 // prereserved space for [SP][CR][LR][3 x unused]. 6207 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6208 unsigned NumBytes = LinkageSize; 6209 6210 // Add up all the space actually used. 6211 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6212 // they all go in registers, but we must reserve stack space for them for 6213 // possible use by the caller. In varargs or 64-bit calls, parameters are 6214 // assigned stack space in order, with padding so Altivec parameters are 6215 // 16-byte aligned. 6216 unsigned nAltivecParamsAtEnd = 0; 6217 for (unsigned i = 0; i != NumOps; ++i) { 6218 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6219 EVT ArgVT = Outs[i].VT; 6220 // Varargs Altivec parameters are padded to a 16 byte boundary. 6221 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6222 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6223 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6224 if (!isVarArg && !isPPC64) { 6225 // Non-varargs Altivec parameters go after all the non-Altivec 6226 // parameters; handle those later so we know how much padding we need. 6227 nAltivecParamsAtEnd++; 6228 continue; 6229 } 6230 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6231 NumBytes = ((NumBytes+15)/16)*16; 6232 } 6233 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6234 } 6235 6236 // Allow for Altivec parameters at the end, if needed. 6237 if (nAltivecParamsAtEnd) { 6238 NumBytes = ((NumBytes+15)/16)*16; 6239 NumBytes += 16*nAltivecParamsAtEnd; 6240 } 6241 6242 // The prolog code of the callee may store up to 8 GPR argument registers to 6243 // the stack, allowing va_start to index over them in memory if its varargs. 6244 // Because we cannot tell if this is needed on the caller side, we have to 6245 // conservatively assume that it is needed. As such, make sure we have at 6246 // least enough stack space for the caller to store the 8 GPRs. 6247 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6248 6249 // Tail call needs the stack to be aligned. 6250 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6251 CallConv == CallingConv::Fast) 6252 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6253 6254 // Calculate by how many bytes the stack has to be adjusted in case of tail 6255 // call optimization. 6256 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6257 6258 // To protect arguments on the stack from being clobbered in a tail call, 6259 // force all the loads to happen before doing any other lowering. 6260 if (isTailCall) 6261 Chain = DAG.getStackArgumentTokenFactor(Chain); 6262 6263 // Adjust the stack pointer for the new arguments... 6264 // These operations are automatically eliminated by the prolog/epilog pass 6265 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6266 SDValue CallSeqStart = Chain; 6267 6268 // Load the return address and frame pointer so it can be move somewhere else 6269 // later. 6270 SDValue LROp, FPOp; 6271 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6272 6273 // Set up a copy of the stack pointer for use loading and storing any 6274 // arguments that may not fit in the registers available for argument 6275 // passing. 6276 SDValue StackPtr; 6277 if (isPPC64) 6278 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6279 else 6280 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6281 6282 // Figure out which arguments are going to go in registers, and which in 6283 // memory. Also, if this is a vararg function, floating point operations 6284 // must be stored to our stack, and loaded into integer regs as well, if 6285 // any integer regs are available for argument passing. 6286 unsigned ArgOffset = LinkageSize; 6287 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6288 6289 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6290 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6291 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6292 }; 6293 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6294 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6295 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6296 }; 6297 static const MCPhysReg VR[] = { 6298 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6299 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6300 }; 6301 const unsigned NumGPRs = array_lengthof(GPR_32); 6302 const unsigned NumFPRs = 13; 6303 const unsigned NumVRs = array_lengthof(VR); 6304 6305 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6306 6307 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6308 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6309 6310 SmallVector<SDValue, 8> MemOpChains; 6311 for (unsigned i = 0; i != NumOps; ++i) { 6312 SDValue Arg = OutVals[i]; 6313 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6314 6315 // PtrOff will be used to store the current argument to the stack if a 6316 // register cannot be found for it. 6317 SDValue PtrOff; 6318 6319 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6320 6321 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6322 6323 // On PPC64, promote integers to 64-bit values. 6324 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6325 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6326 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6327 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6328 } 6329 6330 // FIXME memcpy is used way more than necessary. Correctness first. 6331 // Note: "by value" is code for passing a structure by value, not 6332 // basic types. 6333 if (Flags.isByVal()) { 6334 unsigned Size = Flags.getByValSize(); 6335 // Very small objects are passed right-justified. Everything else is 6336 // passed left-justified. 6337 if (Size==1 || Size==2) { 6338 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6339 if (GPR_idx != NumGPRs) { 6340 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6341 MachinePointerInfo(), VT); 6342 MemOpChains.push_back(Load.getValue(1)); 6343 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6344 6345 ArgOffset += PtrByteSize; 6346 } else { 6347 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6348 PtrOff.getValueType()); 6349 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6350 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6351 CallSeqStart, 6352 Flags, DAG, dl); 6353 ArgOffset += PtrByteSize; 6354 } 6355 continue; 6356 } 6357 // Copy entire object into memory. There are cases where gcc-generated 6358 // code assumes it is there, even if it could be put entirely into 6359 // registers. (This is not what the doc says.) 6360 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6361 CallSeqStart, 6362 Flags, DAG, dl); 6363 6364 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6365 // copy the pieces of the object that fit into registers from the 6366 // parameter save area. 6367 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6368 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6369 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6370 if (GPR_idx != NumGPRs) { 6371 SDValue Load = 6372 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6373 MemOpChains.push_back(Load.getValue(1)); 6374 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6375 ArgOffset += PtrByteSize; 6376 } else { 6377 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6378 break; 6379 } 6380 } 6381 continue; 6382 } 6383 6384 switch (Arg.getSimpleValueType().SimpleTy) { 6385 default: llvm_unreachable("Unexpected ValueType for argument!"); 6386 case MVT::i1: 6387 case MVT::i32: 6388 case MVT::i64: 6389 if (GPR_idx != NumGPRs) { 6390 if (Arg.getValueType() == MVT::i1) 6391 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6392 6393 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6394 } else { 6395 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6396 isPPC64, isTailCall, false, MemOpChains, 6397 TailCallArguments, dl); 6398 } 6399 ArgOffset += PtrByteSize; 6400 break; 6401 case MVT::f32: 6402 case MVT::f64: 6403 if (FPR_idx != NumFPRs) { 6404 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6405 6406 if (isVarArg) { 6407 SDValue Store = 6408 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6409 MemOpChains.push_back(Store); 6410 6411 // Float varargs are always shadowed in available integer registers 6412 if (GPR_idx != NumGPRs) { 6413 SDValue Load = 6414 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6415 MemOpChains.push_back(Load.getValue(1)); 6416 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6417 } 6418 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6419 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6420 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6421 SDValue Load = 6422 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6423 MemOpChains.push_back(Load.getValue(1)); 6424 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6425 } 6426 } else { 6427 // If we have any FPRs remaining, we may also have GPRs remaining. 6428 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6429 // GPRs. 6430 if (GPR_idx != NumGPRs) 6431 ++GPR_idx; 6432 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6433 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6434 ++GPR_idx; 6435 } 6436 } else 6437 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6438 isPPC64, isTailCall, false, MemOpChains, 6439 TailCallArguments, dl); 6440 if (isPPC64) 6441 ArgOffset += 8; 6442 else 6443 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6444 break; 6445 case MVT::v4f32: 6446 case MVT::v4i32: 6447 case MVT::v8i16: 6448 case MVT::v16i8: 6449 if (isVarArg) { 6450 // These go aligned on the stack, or in the corresponding R registers 6451 // when within range. The Darwin PPC ABI doc claims they also go in 6452 // V registers; in fact gcc does this only for arguments that are 6453 // prototyped, not for those that match the ... We do it for all 6454 // arguments, seems to work. 6455 while (ArgOffset % 16 !=0) { 6456 ArgOffset += PtrByteSize; 6457 if (GPR_idx != NumGPRs) 6458 GPR_idx++; 6459 } 6460 // We could elide this store in the case where the object fits 6461 // entirely in R registers. Maybe later. 6462 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6463 DAG.getConstant(ArgOffset, dl, PtrVT)); 6464 SDValue Store = 6465 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6466 MemOpChains.push_back(Store); 6467 if (VR_idx != NumVRs) { 6468 SDValue Load = 6469 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6470 MemOpChains.push_back(Load.getValue(1)); 6471 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6472 } 6473 ArgOffset += 16; 6474 for (unsigned i=0; i<16; i+=PtrByteSize) { 6475 if (GPR_idx == NumGPRs) 6476 break; 6477 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6478 DAG.getConstant(i, dl, PtrVT)); 6479 SDValue Load = 6480 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6481 MemOpChains.push_back(Load.getValue(1)); 6482 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6483 } 6484 break; 6485 } 6486 6487 // Non-varargs Altivec params generally go in registers, but have 6488 // stack space allocated at the end. 6489 if (VR_idx != NumVRs) { 6490 // Doesn't have GPR space allocated. 6491 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6492 } else if (nAltivecParamsAtEnd==0) { 6493 // We are emitting Altivec params in order. 6494 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6495 isPPC64, isTailCall, true, MemOpChains, 6496 TailCallArguments, dl); 6497 ArgOffset += 16; 6498 } 6499 break; 6500 } 6501 } 6502 // If all Altivec parameters fit in registers, as they usually do, 6503 // they get stack space following the non-Altivec parameters. We 6504 // don't track this here because nobody below needs it. 6505 // If there are more Altivec parameters than fit in registers emit 6506 // the stores here. 6507 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6508 unsigned j = 0; 6509 // Offset is aligned; skip 1st 12 params which go in V registers. 6510 ArgOffset = ((ArgOffset+15)/16)*16; 6511 ArgOffset += 12*16; 6512 for (unsigned i = 0; i != NumOps; ++i) { 6513 SDValue Arg = OutVals[i]; 6514 EVT ArgType = Outs[i].VT; 6515 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6516 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6517 if (++j > NumVRs) { 6518 SDValue PtrOff; 6519 // We are emitting Altivec params in order. 6520 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6521 isPPC64, isTailCall, true, MemOpChains, 6522 TailCallArguments, dl); 6523 ArgOffset += 16; 6524 } 6525 } 6526 } 6527 } 6528 6529 if (!MemOpChains.empty()) 6530 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6531 6532 // On Darwin, R12 must contain the address of an indirect callee. This does 6533 // not mean the MTCTR instruction must use R12; it's easier to model this as 6534 // an extra parameter, so do that. 6535 if (!isTailCall && 6536 !isFunctionGlobalAddress(Callee) && 6537 !isa<ExternalSymbolSDNode>(Callee) && 6538 !isBLACompatibleAddress(Callee, DAG)) 6539 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6540 PPC::R12), Callee)); 6541 6542 // Build a sequence of copy-to-reg nodes chained together with token chain 6543 // and flag operands which copy the outgoing args into the appropriate regs. 6544 SDValue InFlag; 6545 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6546 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6547 RegsToPass[i].second, InFlag); 6548 InFlag = Chain.getValue(1); 6549 } 6550 6551 if (isTailCall) 6552 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6553 TailCallArguments); 6554 6555 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6556 /* unused except on PPC64 ELFv1 */ false, DAG, 6557 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6558 NumBytes, Ins, InVals, CS); 6559 } 6560 6561 bool 6562 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6563 MachineFunction &MF, bool isVarArg, 6564 const SmallVectorImpl<ISD::OutputArg> &Outs, 6565 LLVMContext &Context) const { 6566 SmallVector<CCValAssign, 16> RVLocs; 6567 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6568 return CCInfo.CheckReturn( 6569 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6570 ? RetCC_PPC_Cold 6571 : RetCC_PPC); 6572 } 6573 6574 SDValue 6575 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6576 bool isVarArg, 6577 const SmallVectorImpl<ISD::OutputArg> &Outs, 6578 const SmallVectorImpl<SDValue> &OutVals, 6579 const SDLoc &dl, SelectionDAG &DAG) const { 6580 SmallVector<CCValAssign, 16> RVLocs; 6581 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6582 *DAG.getContext()); 6583 CCInfo.AnalyzeReturn(Outs, 6584 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6585 ? RetCC_PPC_Cold 6586 : RetCC_PPC); 6587 6588 SDValue Flag; 6589 SmallVector<SDValue, 4> RetOps(1, Chain); 6590 6591 // Copy the result values into the output registers. 6592 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6593 CCValAssign &VA = RVLocs[i]; 6594 assert(VA.isRegLoc() && "Can only return in registers!"); 6595 6596 SDValue Arg = OutVals[i]; 6597 6598 switch (VA.getLocInfo()) { 6599 default: llvm_unreachable("Unknown loc info!"); 6600 case CCValAssign::Full: break; 6601 case CCValAssign::AExt: 6602 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6603 break; 6604 case CCValAssign::ZExt: 6605 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6606 break; 6607 case CCValAssign::SExt: 6608 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6609 break; 6610 } 6611 6612 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6613 Flag = Chain.getValue(1); 6614 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6615 } 6616 6617 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6618 const MCPhysReg *I = 6619 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6620 if (I) { 6621 for (; *I; ++I) { 6622 6623 if (PPC::G8RCRegClass.contains(*I)) 6624 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6625 else if (PPC::F8RCRegClass.contains(*I)) 6626 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6627 else if (PPC::CRRCRegClass.contains(*I)) 6628 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6629 else if (PPC::VRRCRegClass.contains(*I)) 6630 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6631 else 6632 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6633 } 6634 } 6635 6636 RetOps[0] = Chain; // Update chain. 6637 6638 // Add the flag if we have it. 6639 if (Flag.getNode()) 6640 RetOps.push_back(Flag); 6641 6642 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6643 } 6644 6645 SDValue 6646 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6647 SelectionDAG &DAG) const { 6648 SDLoc dl(Op); 6649 6650 // Get the correct type for integers. 6651 EVT IntVT = Op.getValueType(); 6652 6653 // Get the inputs. 6654 SDValue Chain = Op.getOperand(0); 6655 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6656 // Build a DYNAREAOFFSET node. 6657 SDValue Ops[2] = {Chain, FPSIdx}; 6658 SDVTList VTs = DAG.getVTList(IntVT); 6659 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6660 } 6661 6662 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6663 SelectionDAG &DAG) const { 6664 // When we pop the dynamic allocation we need to restore the SP link. 6665 SDLoc dl(Op); 6666 6667 // Get the correct type for pointers. 6668 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6669 6670 // Construct the stack pointer operand. 6671 bool isPPC64 = Subtarget.isPPC64(); 6672 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6673 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6674 6675 // Get the operands for the STACKRESTORE. 6676 SDValue Chain = Op.getOperand(0); 6677 SDValue SaveSP = Op.getOperand(1); 6678 6679 // Load the old link SP. 6680 SDValue LoadLinkSP = 6681 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6682 6683 // Restore the stack pointer. 6684 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6685 6686 // Store the old link SP. 6687 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6688 } 6689 6690 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6691 MachineFunction &MF = DAG.getMachineFunction(); 6692 bool isPPC64 = Subtarget.isPPC64(); 6693 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6694 6695 // Get current frame pointer save index. The users of this index will be 6696 // primarily DYNALLOC instructions. 6697 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6698 int RASI = FI->getReturnAddrSaveIndex(); 6699 6700 // If the frame pointer save index hasn't been defined yet. 6701 if (!RASI) { 6702 // Find out what the fix offset of the frame pointer save area. 6703 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6704 // Allocate the frame index for frame pointer save area. 6705 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6706 // Save the result. 6707 FI->setReturnAddrSaveIndex(RASI); 6708 } 6709 return DAG.getFrameIndex(RASI, PtrVT); 6710 } 6711 6712 SDValue 6713 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6714 MachineFunction &MF = DAG.getMachineFunction(); 6715 bool isPPC64 = Subtarget.isPPC64(); 6716 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6717 6718 // Get current frame pointer save index. The users of this index will be 6719 // primarily DYNALLOC instructions. 6720 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6721 int FPSI = FI->getFramePointerSaveIndex(); 6722 6723 // If the frame pointer save index hasn't been defined yet. 6724 if (!FPSI) { 6725 // Find out what the fix offset of the frame pointer save area. 6726 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6727 // Allocate the frame index for frame pointer save area. 6728 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6729 // Save the result. 6730 FI->setFramePointerSaveIndex(FPSI); 6731 } 6732 return DAG.getFrameIndex(FPSI, PtrVT); 6733 } 6734 6735 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6736 SelectionDAG &DAG) const { 6737 // Get the inputs. 6738 SDValue Chain = Op.getOperand(0); 6739 SDValue Size = Op.getOperand(1); 6740 SDLoc dl(Op); 6741 6742 // Get the correct type for pointers. 6743 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6744 // Negate the size. 6745 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6746 DAG.getConstant(0, dl, PtrVT), Size); 6747 // Construct a node for the frame pointer save index. 6748 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6749 // Build a DYNALLOC node. 6750 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6751 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6752 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6753 } 6754 6755 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6756 SelectionDAG &DAG) const { 6757 MachineFunction &MF = DAG.getMachineFunction(); 6758 6759 bool isPPC64 = Subtarget.isPPC64(); 6760 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6761 6762 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6763 return DAG.getFrameIndex(FI, PtrVT); 6764 } 6765 6766 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6767 SelectionDAG &DAG) const { 6768 SDLoc DL(Op); 6769 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6770 DAG.getVTList(MVT::i32, MVT::Other), 6771 Op.getOperand(0), Op.getOperand(1)); 6772 } 6773 6774 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6775 SelectionDAG &DAG) const { 6776 SDLoc DL(Op); 6777 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6778 Op.getOperand(0), Op.getOperand(1)); 6779 } 6780 6781 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6782 if (Op.getValueType().isVector()) 6783 return LowerVectorLoad(Op, DAG); 6784 6785 assert(Op.getValueType() == MVT::i1 && 6786 "Custom lowering only for i1 loads"); 6787 6788 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6789 6790 SDLoc dl(Op); 6791 LoadSDNode *LD = cast<LoadSDNode>(Op); 6792 6793 SDValue Chain = LD->getChain(); 6794 SDValue BasePtr = LD->getBasePtr(); 6795 MachineMemOperand *MMO = LD->getMemOperand(); 6796 6797 SDValue NewLD = 6798 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6799 BasePtr, MVT::i8, MMO); 6800 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6801 6802 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6803 return DAG.getMergeValues(Ops, dl); 6804 } 6805 6806 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6807 if (Op.getOperand(1).getValueType().isVector()) 6808 return LowerVectorStore(Op, DAG); 6809 6810 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6811 "Custom lowering only for i1 stores"); 6812 6813 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6814 6815 SDLoc dl(Op); 6816 StoreSDNode *ST = cast<StoreSDNode>(Op); 6817 6818 SDValue Chain = ST->getChain(); 6819 SDValue BasePtr = ST->getBasePtr(); 6820 SDValue Value = ST->getValue(); 6821 MachineMemOperand *MMO = ST->getMemOperand(); 6822 6823 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6824 Value); 6825 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6826 } 6827 6828 // FIXME: Remove this once the ANDI glue bug is fixed: 6829 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6830 assert(Op.getValueType() == MVT::i1 && 6831 "Custom lowering only for i1 results"); 6832 6833 SDLoc DL(Op); 6834 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6835 Op.getOperand(0)); 6836 } 6837 6838 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 6839 SelectionDAG &DAG) const { 6840 6841 // Implements a vector truncate that fits in a vector register as a shuffle. 6842 // We want to legalize vector truncates down to where the source fits in 6843 // a vector register (and target is therefore smaller than vector register 6844 // size). At that point legalization will try to custom lower the sub-legal 6845 // result and get here - where we can contain the truncate as a single target 6846 // operation. 6847 6848 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 6849 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 6850 // 6851 // We will implement it for big-endian ordering as this (where x denotes 6852 // undefined): 6853 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 6854 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 6855 // 6856 // The same operation in little-endian ordering will be: 6857 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 6858 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 6859 6860 assert(Op.getValueType().isVector() && "Vector type expected."); 6861 6862 SDLoc DL(Op); 6863 SDValue N1 = Op.getOperand(0); 6864 unsigned SrcSize = N1.getValueType().getSizeInBits(); 6865 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 6866 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 6867 6868 EVT TrgVT = Op.getValueType(); 6869 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 6870 EVT EltVT = TrgVT.getVectorElementType(); 6871 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 6872 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 6873 6874 // First list the elements we want to keep. 6875 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 6876 SmallVector<int, 16> ShuffV; 6877 if (Subtarget.isLittleEndian()) 6878 for (unsigned i = 0; i < TrgNumElts; ++i) 6879 ShuffV.push_back(i * SizeMult); 6880 else 6881 for (unsigned i = 1; i <= TrgNumElts; ++i) 6882 ShuffV.push_back(i * SizeMult - 1); 6883 6884 // Populate the remaining elements with undefs. 6885 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 6886 // ShuffV.push_back(i + WideNumElts); 6887 ShuffV.push_back(WideNumElts + 1); 6888 6889 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 6890 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 6891 } 6892 6893 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6894 /// possible. 6895 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6896 // Not FP? Not a fsel. 6897 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6898 !Op.getOperand(2).getValueType().isFloatingPoint()) 6899 return Op; 6900 6901 // We might be able to do better than this under some circumstances, but in 6902 // general, fsel-based lowering of select is a finite-math-only optimization. 6903 // For more information, see section F.3 of the 2.06 ISA specification. 6904 if (!DAG.getTarget().Options.NoInfsFPMath || 6905 !DAG.getTarget().Options.NoNaNsFPMath) 6906 return Op; 6907 // TODO: Propagate flags from the select rather than global settings. 6908 SDNodeFlags Flags; 6909 Flags.setNoInfs(true); 6910 Flags.setNoNaNs(true); 6911 6912 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6913 6914 EVT ResVT = Op.getValueType(); 6915 EVT CmpVT = Op.getOperand(0).getValueType(); 6916 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6917 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6918 SDLoc dl(Op); 6919 6920 // If the RHS of the comparison is a 0.0, we don't need to do the 6921 // subtraction at all. 6922 SDValue Sel1; 6923 if (isFloatingPointZero(RHS)) 6924 switch (CC) { 6925 default: break; // SETUO etc aren't handled by fsel. 6926 case ISD::SETNE: 6927 std::swap(TV, FV); 6928 LLVM_FALLTHROUGH; 6929 case ISD::SETEQ: 6930 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6931 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6932 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6933 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6934 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6935 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6936 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6937 case ISD::SETULT: 6938 case ISD::SETLT: 6939 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6940 LLVM_FALLTHROUGH; 6941 case ISD::SETOGE: 6942 case ISD::SETGE: 6943 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6944 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6945 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6946 case ISD::SETUGT: 6947 case ISD::SETGT: 6948 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6949 LLVM_FALLTHROUGH; 6950 case ISD::SETOLE: 6951 case ISD::SETLE: 6952 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6953 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6954 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6955 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6956 } 6957 6958 SDValue Cmp; 6959 switch (CC) { 6960 default: break; // SETUO etc aren't handled by fsel. 6961 case ISD::SETNE: 6962 std::swap(TV, FV); 6963 LLVM_FALLTHROUGH; 6964 case ISD::SETEQ: 6965 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6966 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6967 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6968 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6969 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6970 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6971 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6972 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6973 case ISD::SETULT: 6974 case ISD::SETLT: 6975 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6976 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6977 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6978 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6979 case ISD::SETOGE: 6980 case ISD::SETGE: 6981 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6982 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6983 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6984 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6985 case ISD::SETUGT: 6986 case ISD::SETGT: 6987 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6988 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6989 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6990 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6991 case ISD::SETOLE: 6992 case ISD::SETLE: 6993 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6994 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6995 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6996 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6997 } 6998 return Op; 6999 } 7000 7001 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7002 SelectionDAG &DAG, 7003 const SDLoc &dl) const { 7004 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7005 SDValue Src = Op.getOperand(0); 7006 if (Src.getValueType() == MVT::f32) 7007 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7008 7009 SDValue Tmp; 7010 switch (Op.getSimpleValueType().SimpleTy) { 7011 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7012 case MVT::i32: 7013 Tmp = DAG.getNode( 7014 Op.getOpcode() == ISD::FP_TO_SINT 7015 ? PPCISD::FCTIWZ 7016 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7017 dl, MVT::f64, Src); 7018 break; 7019 case MVT::i64: 7020 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7021 "i64 FP_TO_UINT is supported only with FPCVT"); 7022 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7023 PPCISD::FCTIDUZ, 7024 dl, MVT::f64, Src); 7025 break; 7026 } 7027 7028 // Convert the FP value to an int value through memory. 7029 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7030 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7031 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7032 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7033 MachinePointerInfo MPI = 7034 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7035 7036 // Emit a store to the stack slot. 7037 SDValue Chain; 7038 if (i32Stack) { 7039 MachineFunction &MF = DAG.getMachineFunction(); 7040 MachineMemOperand *MMO = 7041 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7042 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7043 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7044 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7045 } else 7046 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7047 7048 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7049 // add in a bias on big endian. 7050 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7051 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7052 DAG.getConstant(4, dl, FIPtr.getValueType())); 7053 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7054 } 7055 7056 RLI.Chain = Chain; 7057 RLI.Ptr = FIPtr; 7058 RLI.MPI = MPI; 7059 } 7060 7061 /// Custom lowers floating point to integer conversions to use 7062 /// the direct move instructions available in ISA 2.07 to avoid the 7063 /// need for load/store combinations. 7064 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7065 SelectionDAG &DAG, 7066 const SDLoc &dl) const { 7067 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7068 SDValue Src = Op.getOperand(0); 7069 7070 if (Src.getValueType() == MVT::f32) 7071 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7072 7073 SDValue Tmp; 7074 switch (Op.getSimpleValueType().SimpleTy) { 7075 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7076 case MVT::i32: 7077 Tmp = DAG.getNode( 7078 Op.getOpcode() == ISD::FP_TO_SINT 7079 ? PPCISD::FCTIWZ 7080 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7081 dl, MVT::f64, Src); 7082 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7083 break; 7084 case MVT::i64: 7085 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7086 "i64 FP_TO_UINT is supported only with FPCVT"); 7087 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7088 PPCISD::FCTIDUZ, 7089 dl, MVT::f64, Src); 7090 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7091 break; 7092 } 7093 return Tmp; 7094 } 7095 7096 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7097 const SDLoc &dl) const { 7098 7099 // FP to INT conversions are legal for f128. 7100 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7101 return Op; 7102 7103 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7104 // PPC (the libcall is not available). 7105 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7106 if (Op.getValueType() == MVT::i32) { 7107 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7108 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7109 MVT::f64, Op.getOperand(0), 7110 DAG.getIntPtrConstant(0, dl)); 7111 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7112 MVT::f64, Op.getOperand(0), 7113 DAG.getIntPtrConstant(1, dl)); 7114 7115 // Add the two halves of the long double in round-to-zero mode. 7116 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7117 7118 // Now use a smaller FP_TO_SINT. 7119 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7120 } 7121 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7122 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7123 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7124 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7125 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7126 // FIXME: generated code sucks. 7127 // TODO: Are there fast-math-flags to propagate to this FSUB? 7128 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7129 Op.getOperand(0), Tmp); 7130 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7131 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7132 DAG.getConstant(0x80000000, dl, MVT::i32)); 7133 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7134 Op.getOperand(0)); 7135 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7136 ISD::SETGE); 7137 } 7138 } 7139 7140 return SDValue(); 7141 } 7142 7143 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7144 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7145 7146 ReuseLoadInfo RLI; 7147 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7148 7149 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7150 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7151 } 7152 7153 // We're trying to insert a regular store, S, and then a load, L. If the 7154 // incoming value, O, is a load, we might just be able to have our load use the 7155 // address used by O. However, we don't know if anything else will store to 7156 // that address before we can load from it. To prevent this situation, we need 7157 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7158 // the same chain operand as O, we create a token factor from the chain results 7159 // of O and L, and we replace all uses of O's chain result with that token 7160 // factor (see spliceIntoChain below for this last part). 7161 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7162 ReuseLoadInfo &RLI, 7163 SelectionDAG &DAG, 7164 ISD::LoadExtType ET) const { 7165 SDLoc dl(Op); 7166 if (ET == ISD::NON_EXTLOAD && 7167 (Op.getOpcode() == ISD::FP_TO_UINT || 7168 Op.getOpcode() == ISD::FP_TO_SINT) && 7169 isOperationLegalOrCustom(Op.getOpcode(), 7170 Op.getOperand(0).getValueType())) { 7171 7172 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7173 return true; 7174 } 7175 7176 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7177 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7178 LD->isNonTemporal()) 7179 return false; 7180 if (LD->getMemoryVT() != MemVT) 7181 return false; 7182 7183 RLI.Ptr = LD->getBasePtr(); 7184 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7185 assert(LD->getAddressingMode() == ISD::PRE_INC && 7186 "Non-pre-inc AM on PPC?"); 7187 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7188 LD->getOffset()); 7189 } 7190 7191 RLI.Chain = LD->getChain(); 7192 RLI.MPI = LD->getPointerInfo(); 7193 RLI.IsDereferenceable = LD->isDereferenceable(); 7194 RLI.IsInvariant = LD->isInvariant(); 7195 RLI.Alignment = LD->getAlignment(); 7196 RLI.AAInfo = LD->getAAInfo(); 7197 RLI.Ranges = LD->getRanges(); 7198 7199 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7200 return true; 7201 } 7202 7203 // Given the head of the old chain, ResChain, insert a token factor containing 7204 // it and NewResChain, and make users of ResChain now be users of that token 7205 // factor. 7206 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7207 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7208 SDValue NewResChain, 7209 SelectionDAG &DAG) const { 7210 if (!ResChain) 7211 return; 7212 7213 SDLoc dl(NewResChain); 7214 7215 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7216 NewResChain, DAG.getUNDEF(MVT::Other)); 7217 assert(TF.getNode() != NewResChain.getNode() && 7218 "A new TF really is required here"); 7219 7220 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7221 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7222 } 7223 7224 /// Analyze profitability of direct move 7225 /// prefer float load to int load plus direct move 7226 /// when there is no integer use of int load 7227 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7228 SDNode *Origin = Op.getOperand(0).getNode(); 7229 if (Origin->getOpcode() != ISD::LOAD) 7230 return true; 7231 7232 // If there is no LXSIBZX/LXSIHZX, like Power8, 7233 // prefer direct move if the memory size is 1 or 2 bytes. 7234 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7235 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7236 return true; 7237 7238 for (SDNode::use_iterator UI = Origin->use_begin(), 7239 UE = Origin->use_end(); 7240 UI != UE; ++UI) { 7241 7242 // Only look at the users of the loaded value. 7243 if (UI.getUse().get().getResNo() != 0) 7244 continue; 7245 7246 if (UI->getOpcode() != ISD::SINT_TO_FP && 7247 UI->getOpcode() != ISD::UINT_TO_FP) 7248 return true; 7249 } 7250 7251 return false; 7252 } 7253 7254 /// Custom lowers integer to floating point conversions to use 7255 /// the direct move instructions available in ISA 2.07 to avoid the 7256 /// need for load/store combinations. 7257 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7258 SelectionDAG &DAG, 7259 const SDLoc &dl) const { 7260 assert((Op.getValueType() == MVT::f32 || 7261 Op.getValueType() == MVT::f64) && 7262 "Invalid floating point type as target of conversion"); 7263 assert(Subtarget.hasFPCVT() && 7264 "Int to FP conversions with direct moves require FPCVT"); 7265 SDValue FP; 7266 SDValue Src = Op.getOperand(0); 7267 bool SinglePrec = Op.getValueType() == MVT::f32; 7268 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7269 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7270 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7271 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7272 7273 if (WordInt) { 7274 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7275 dl, MVT::f64, Src); 7276 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7277 } 7278 else { 7279 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7280 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7281 } 7282 7283 return FP; 7284 } 7285 7286 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7287 7288 EVT VecVT = Vec.getValueType(); 7289 assert(VecVT.isVector() && "Expected a vector type."); 7290 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7291 7292 EVT EltVT = VecVT.getVectorElementType(); 7293 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7294 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7295 7296 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7297 SmallVector<SDValue, 16> Ops(NumConcat); 7298 Ops[0] = Vec; 7299 SDValue UndefVec = DAG.getUNDEF(VecVT); 7300 for (unsigned i = 1; i < NumConcat; ++i) 7301 Ops[i] = UndefVec; 7302 7303 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7304 } 7305 7306 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7307 const SDLoc &dl) const { 7308 7309 unsigned Opc = Op.getOpcode(); 7310 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7311 "Unexpected conversion type"); 7312 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7313 "Supports conversions to v2f64/v4f32 only."); 7314 7315 bool SignedConv = Opc == ISD::SINT_TO_FP; 7316 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7317 7318 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7319 EVT WideVT = Wide.getValueType(); 7320 unsigned WideNumElts = WideVT.getVectorNumElements(); 7321 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7322 7323 SmallVector<int, 16> ShuffV; 7324 for (unsigned i = 0; i < WideNumElts; ++i) 7325 ShuffV.push_back(i + WideNumElts); 7326 7327 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7328 int SaveElts = FourEltRes ? 4 : 2; 7329 if (Subtarget.isLittleEndian()) 7330 for (int i = 0; i < SaveElts; i++) 7331 ShuffV[i * Stride] = i; 7332 else 7333 for (int i = 1; i <= SaveElts; i++) 7334 ShuffV[i * Stride - 1] = i - 1; 7335 7336 SDValue ShuffleSrc2 = 7337 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7338 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7339 unsigned ExtendOp = 7340 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7341 7342 SDValue Extend; 7343 if (!Subtarget.hasP9Altivec() && SignedConv) { 7344 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7345 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7346 DAG.getValueType(Op.getOperand(0).getValueType())); 7347 } else 7348 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7349 7350 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7351 } 7352 7353 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7354 SelectionDAG &DAG) const { 7355 SDLoc dl(Op); 7356 7357 EVT InVT = Op.getOperand(0).getValueType(); 7358 EVT OutVT = Op.getValueType(); 7359 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7360 isOperationCustom(Op.getOpcode(), InVT)) 7361 return LowerINT_TO_FPVector(Op, DAG, dl); 7362 7363 // Conversions to f128 are legal. 7364 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7365 return Op; 7366 7367 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7368 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7369 return SDValue(); 7370 7371 SDValue Value = Op.getOperand(0); 7372 // The values are now known to be -1 (false) or 1 (true). To convert this 7373 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7374 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7375 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7376 7377 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7378 7379 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7380 7381 if (Op.getValueType() != MVT::v4f64) 7382 Value = DAG.getNode(ISD::FP_ROUND, dl, 7383 Op.getValueType(), Value, 7384 DAG.getIntPtrConstant(1, dl)); 7385 return Value; 7386 } 7387 7388 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7389 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7390 return SDValue(); 7391 7392 if (Op.getOperand(0).getValueType() == MVT::i1) 7393 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7394 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7395 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7396 7397 // If we have direct moves, we can do all the conversion, skip the store/load 7398 // however, without FPCVT we can't do most conversions. 7399 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7400 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7401 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7402 7403 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7404 "UINT_TO_FP is supported only with FPCVT"); 7405 7406 // If we have FCFIDS, then use it when converting to single-precision. 7407 // Otherwise, convert to double-precision and then round. 7408 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7409 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7410 : PPCISD::FCFIDS) 7411 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7412 : PPCISD::FCFID); 7413 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7414 ? MVT::f32 7415 : MVT::f64; 7416 7417 if (Op.getOperand(0).getValueType() == MVT::i64) { 7418 SDValue SINT = Op.getOperand(0); 7419 // When converting to single-precision, we actually need to convert 7420 // to double-precision first and then round to single-precision. 7421 // To avoid double-rounding effects during that operation, we have 7422 // to prepare the input operand. Bits that might be truncated when 7423 // converting to double-precision are replaced by a bit that won't 7424 // be lost at this stage, but is below the single-precision rounding 7425 // position. 7426 // 7427 // However, if -enable-unsafe-fp-math is in effect, accept double 7428 // rounding to avoid the extra overhead. 7429 if (Op.getValueType() == MVT::f32 && 7430 !Subtarget.hasFPCVT() && 7431 !DAG.getTarget().Options.UnsafeFPMath) { 7432 7433 // Twiddle input to make sure the low 11 bits are zero. (If this 7434 // is the case, we are guaranteed the value will fit into the 53 bit 7435 // mantissa of an IEEE double-precision value without rounding.) 7436 // If any of those low 11 bits were not zero originally, make sure 7437 // bit 12 (value 2048) is set instead, so that the final rounding 7438 // to single-precision gets the correct result. 7439 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7440 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7441 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7442 Round, DAG.getConstant(2047, dl, MVT::i64)); 7443 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7444 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7445 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7446 7447 // However, we cannot use that value unconditionally: if the magnitude 7448 // of the input value is small, the bit-twiddling we did above might 7449 // end up visibly changing the output. Fortunately, in that case, we 7450 // don't need to twiddle bits since the original input will convert 7451 // exactly to double-precision floating-point already. Therefore, 7452 // construct a conditional to use the original value if the top 11 7453 // bits are all sign-bit copies, and use the rounded value computed 7454 // above otherwise. 7455 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7456 SINT, DAG.getConstant(53, dl, MVT::i32)); 7457 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7458 Cond, DAG.getConstant(1, dl, MVT::i64)); 7459 Cond = DAG.getSetCC(dl, MVT::i32, 7460 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7461 7462 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7463 } 7464 7465 ReuseLoadInfo RLI; 7466 SDValue Bits; 7467 7468 MachineFunction &MF = DAG.getMachineFunction(); 7469 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7470 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7471 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7472 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7473 } else if (Subtarget.hasLFIWAX() && 7474 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7475 MachineMemOperand *MMO = 7476 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7477 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7478 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7479 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7480 DAG.getVTList(MVT::f64, MVT::Other), 7481 Ops, MVT::i32, MMO); 7482 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7483 } else if (Subtarget.hasFPCVT() && 7484 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7485 MachineMemOperand *MMO = 7486 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7487 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7488 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7489 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7490 DAG.getVTList(MVT::f64, MVT::Other), 7491 Ops, MVT::i32, MMO); 7492 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7493 } else if (((Subtarget.hasLFIWAX() && 7494 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7495 (Subtarget.hasFPCVT() && 7496 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7497 SINT.getOperand(0).getValueType() == MVT::i32) { 7498 MachineFrameInfo &MFI = MF.getFrameInfo(); 7499 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7500 7501 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7502 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7503 7504 SDValue Store = 7505 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7506 MachinePointerInfo::getFixedStack( 7507 DAG.getMachineFunction(), FrameIdx)); 7508 7509 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7510 "Expected an i32 store"); 7511 7512 RLI.Ptr = FIdx; 7513 RLI.Chain = Store; 7514 RLI.MPI = 7515 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7516 RLI.Alignment = 4; 7517 7518 MachineMemOperand *MMO = 7519 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7520 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7521 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7522 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7523 PPCISD::LFIWZX : PPCISD::LFIWAX, 7524 dl, DAG.getVTList(MVT::f64, MVT::Other), 7525 Ops, MVT::i32, MMO); 7526 } else 7527 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7528 7529 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7530 7531 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7532 FP = DAG.getNode(ISD::FP_ROUND, dl, 7533 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7534 return FP; 7535 } 7536 7537 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7538 "Unhandled INT_TO_FP type in custom expander!"); 7539 // Since we only generate this in 64-bit mode, we can take advantage of 7540 // 64-bit registers. In particular, sign extend the input value into the 7541 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7542 // then lfd it and fcfid it. 7543 MachineFunction &MF = DAG.getMachineFunction(); 7544 MachineFrameInfo &MFI = MF.getFrameInfo(); 7545 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7546 7547 SDValue Ld; 7548 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7549 ReuseLoadInfo RLI; 7550 bool ReusingLoad; 7551 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7552 DAG))) { 7553 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7554 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7555 7556 SDValue Store = 7557 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7558 MachinePointerInfo::getFixedStack( 7559 DAG.getMachineFunction(), FrameIdx)); 7560 7561 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7562 "Expected an i32 store"); 7563 7564 RLI.Ptr = FIdx; 7565 RLI.Chain = Store; 7566 RLI.MPI = 7567 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7568 RLI.Alignment = 4; 7569 } 7570 7571 MachineMemOperand *MMO = 7572 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7573 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7574 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7575 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7576 PPCISD::LFIWZX : PPCISD::LFIWAX, 7577 dl, DAG.getVTList(MVT::f64, MVT::Other), 7578 Ops, MVT::i32, MMO); 7579 if (ReusingLoad) 7580 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7581 } else { 7582 assert(Subtarget.isPPC64() && 7583 "i32->FP without LFIWAX supported only on PPC64"); 7584 7585 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7586 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7587 7588 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7589 Op.getOperand(0)); 7590 7591 // STD the extended value into the stack slot. 7592 SDValue Store = DAG.getStore( 7593 DAG.getEntryNode(), dl, Ext64, FIdx, 7594 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7595 7596 // Load the value as a double. 7597 Ld = DAG.getLoad( 7598 MVT::f64, dl, Store, FIdx, 7599 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7600 } 7601 7602 // FCFID it and return it. 7603 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7604 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7605 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7606 DAG.getIntPtrConstant(0, dl)); 7607 return FP; 7608 } 7609 7610 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7611 SelectionDAG &DAG) const { 7612 SDLoc dl(Op); 7613 /* 7614 The rounding mode is in bits 30:31 of FPSR, and has the following 7615 settings: 7616 00 Round to nearest 7617 01 Round to 0 7618 10 Round to +inf 7619 11 Round to -inf 7620 7621 FLT_ROUNDS, on the other hand, expects the following: 7622 -1 Undefined 7623 0 Round to 0 7624 1 Round to nearest 7625 2 Round to +inf 7626 3 Round to -inf 7627 7628 To perform the conversion, we do: 7629 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7630 */ 7631 7632 MachineFunction &MF = DAG.getMachineFunction(); 7633 EVT VT = Op.getValueType(); 7634 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7635 7636 // Save FP Control Word to register 7637 EVT NodeTys[] = { 7638 MVT::f64, // return register 7639 MVT::Glue // unused in this context 7640 }; 7641 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7642 7643 // Save FP register to stack slot 7644 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7645 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7646 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7647 MachinePointerInfo()); 7648 7649 // Load FP Control Word from low 32 bits of stack slot. 7650 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7651 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7652 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7653 7654 // Transform as necessary 7655 SDValue CWD1 = 7656 DAG.getNode(ISD::AND, dl, MVT::i32, 7657 CWD, DAG.getConstant(3, dl, MVT::i32)); 7658 SDValue CWD2 = 7659 DAG.getNode(ISD::SRL, dl, MVT::i32, 7660 DAG.getNode(ISD::AND, dl, MVT::i32, 7661 DAG.getNode(ISD::XOR, dl, MVT::i32, 7662 CWD, DAG.getConstant(3, dl, MVT::i32)), 7663 DAG.getConstant(3, dl, MVT::i32)), 7664 DAG.getConstant(1, dl, MVT::i32)); 7665 7666 SDValue RetVal = 7667 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7668 7669 return DAG.getNode((VT.getSizeInBits() < 16 ? 7670 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7671 } 7672 7673 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7674 EVT VT = Op.getValueType(); 7675 unsigned BitWidth = VT.getSizeInBits(); 7676 SDLoc dl(Op); 7677 assert(Op.getNumOperands() == 3 && 7678 VT == Op.getOperand(1).getValueType() && 7679 "Unexpected SHL!"); 7680 7681 // Expand into a bunch of logical ops. Note that these ops 7682 // depend on the PPC behavior for oversized shift amounts. 7683 SDValue Lo = Op.getOperand(0); 7684 SDValue Hi = Op.getOperand(1); 7685 SDValue Amt = Op.getOperand(2); 7686 EVT AmtVT = Amt.getValueType(); 7687 7688 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7689 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7690 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7691 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7692 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7693 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7694 DAG.getConstant(-BitWidth, dl, AmtVT)); 7695 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7696 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7697 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7698 SDValue OutOps[] = { OutLo, OutHi }; 7699 return DAG.getMergeValues(OutOps, dl); 7700 } 7701 7702 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7703 EVT VT = Op.getValueType(); 7704 SDLoc dl(Op); 7705 unsigned BitWidth = VT.getSizeInBits(); 7706 assert(Op.getNumOperands() == 3 && 7707 VT == Op.getOperand(1).getValueType() && 7708 "Unexpected SRL!"); 7709 7710 // Expand into a bunch of logical ops. Note that these ops 7711 // depend on the PPC behavior for oversized shift amounts. 7712 SDValue Lo = Op.getOperand(0); 7713 SDValue Hi = Op.getOperand(1); 7714 SDValue Amt = Op.getOperand(2); 7715 EVT AmtVT = Amt.getValueType(); 7716 7717 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7718 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7719 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7720 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7721 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7722 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7723 DAG.getConstant(-BitWidth, dl, AmtVT)); 7724 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7725 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7726 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7727 SDValue OutOps[] = { OutLo, OutHi }; 7728 return DAG.getMergeValues(OutOps, dl); 7729 } 7730 7731 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7732 SDLoc dl(Op); 7733 EVT VT = Op.getValueType(); 7734 unsigned BitWidth = VT.getSizeInBits(); 7735 assert(Op.getNumOperands() == 3 && 7736 VT == Op.getOperand(1).getValueType() && 7737 "Unexpected SRA!"); 7738 7739 // Expand into a bunch of logical ops, followed by a select_cc. 7740 SDValue Lo = Op.getOperand(0); 7741 SDValue Hi = Op.getOperand(1); 7742 SDValue Amt = Op.getOperand(2); 7743 EVT AmtVT = Amt.getValueType(); 7744 7745 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7746 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7747 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7748 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7749 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7750 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7751 DAG.getConstant(-BitWidth, dl, AmtVT)); 7752 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7753 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7754 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7755 Tmp4, Tmp6, ISD::SETLE); 7756 SDValue OutOps[] = { OutLo, OutHi }; 7757 return DAG.getMergeValues(OutOps, dl); 7758 } 7759 7760 //===----------------------------------------------------------------------===// 7761 // Vector related lowering. 7762 // 7763 7764 /// BuildSplatI - Build a canonical splati of Val with an element size of 7765 /// SplatSize. Cast the result to VT. 7766 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7767 SelectionDAG &DAG, const SDLoc &dl) { 7768 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7769 7770 static const MVT VTys[] = { // canonical VT to use for each size. 7771 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7772 }; 7773 7774 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7775 7776 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7777 if (Val == -1) 7778 SplatSize = 1; 7779 7780 EVT CanonicalVT = VTys[SplatSize-1]; 7781 7782 // Build a canonical splat for this value. 7783 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7784 } 7785 7786 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7787 /// specified intrinsic ID. 7788 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7789 const SDLoc &dl, EVT DestVT = MVT::Other) { 7790 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7791 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7792 DAG.getConstant(IID, dl, MVT::i32), Op); 7793 } 7794 7795 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7796 /// specified intrinsic ID. 7797 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7798 SelectionDAG &DAG, const SDLoc &dl, 7799 EVT DestVT = MVT::Other) { 7800 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7801 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7802 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7803 } 7804 7805 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7806 /// specified intrinsic ID. 7807 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7808 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7809 EVT DestVT = MVT::Other) { 7810 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7811 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7812 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7813 } 7814 7815 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7816 /// amount. The result has the specified value type. 7817 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7818 SelectionDAG &DAG, const SDLoc &dl) { 7819 // Force LHS/RHS to be the right type. 7820 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7821 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7822 7823 int Ops[16]; 7824 for (unsigned i = 0; i != 16; ++i) 7825 Ops[i] = i + Amt; 7826 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7827 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7828 } 7829 7830 /// Do we have an efficient pattern in a .td file for this node? 7831 /// 7832 /// \param V - pointer to the BuildVectorSDNode being matched 7833 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7834 /// 7835 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7836 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7837 /// the opposite is true (expansion is beneficial) are: 7838 /// - The node builds a vector out of integers that are not 32 or 64-bits 7839 /// - The node builds a vector out of constants 7840 /// - The node is a "load-and-splat" 7841 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7842 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7843 bool HasDirectMove, 7844 bool HasP8Vector) { 7845 EVT VecVT = V->getValueType(0); 7846 bool RightType = VecVT == MVT::v2f64 || 7847 (HasP8Vector && VecVT == MVT::v4f32) || 7848 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7849 if (!RightType) 7850 return false; 7851 7852 bool IsSplat = true; 7853 bool IsLoad = false; 7854 SDValue Op0 = V->getOperand(0); 7855 7856 // This function is called in a block that confirms the node is not a constant 7857 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7858 // different constants. 7859 if (V->isConstant()) 7860 return false; 7861 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7862 if (V->getOperand(i).isUndef()) 7863 return false; 7864 // We want to expand nodes that represent load-and-splat even if the 7865 // loaded value is a floating point truncation or conversion to int. 7866 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7867 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7868 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7869 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7870 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7871 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7872 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7873 IsLoad = true; 7874 // If the operands are different or the input is not a load and has more 7875 // uses than just this BV node, then it isn't a splat. 7876 if (V->getOperand(i) != Op0 || 7877 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7878 IsSplat = false; 7879 } 7880 return !(IsSplat && IsLoad); 7881 } 7882 7883 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7884 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7885 7886 SDLoc dl(Op); 7887 SDValue Op0 = Op->getOperand(0); 7888 7889 if (!EnableQuadPrecision || 7890 (Op.getValueType() != MVT::f128 ) || 7891 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7892 (Op0.getOperand(0).getValueType() != MVT::i64) || 7893 (Op0.getOperand(1).getValueType() != MVT::i64)) 7894 return SDValue(); 7895 7896 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7897 Op0.getOperand(1)); 7898 } 7899 7900 // If this is a case we can't handle, return null and let the default 7901 // expansion code take care of it. If we CAN select this case, and if it 7902 // selects to a single instruction, return Op. Otherwise, if we can codegen 7903 // this case more efficiently than a constant pool load, lower it to the 7904 // sequence of ops that should be used. 7905 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7906 SelectionDAG &DAG) const { 7907 SDLoc dl(Op); 7908 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7909 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7910 7911 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7912 // We first build an i32 vector, load it into a QPX register, 7913 // then convert it to a floating-point vector and compare it 7914 // to a zero vector to get the boolean result. 7915 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7916 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7917 MachinePointerInfo PtrInfo = 7918 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7919 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7920 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7921 7922 assert(BVN->getNumOperands() == 4 && 7923 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7924 7925 bool IsConst = true; 7926 for (unsigned i = 0; i < 4; ++i) { 7927 if (BVN->getOperand(i).isUndef()) continue; 7928 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7929 IsConst = false; 7930 break; 7931 } 7932 } 7933 7934 if (IsConst) { 7935 Constant *One = 7936 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7937 Constant *NegOne = 7938 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7939 7940 Constant *CV[4]; 7941 for (unsigned i = 0; i < 4; ++i) { 7942 if (BVN->getOperand(i).isUndef()) 7943 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7944 else if (isNullConstant(BVN->getOperand(i))) 7945 CV[i] = NegOne; 7946 else 7947 CV[i] = One; 7948 } 7949 7950 Constant *CP = ConstantVector::get(CV); 7951 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7952 16 /* alignment */); 7953 7954 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7955 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7956 return DAG.getMemIntrinsicNode( 7957 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7958 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7959 } 7960 7961 SmallVector<SDValue, 4> Stores; 7962 for (unsigned i = 0; i < 4; ++i) { 7963 if (BVN->getOperand(i).isUndef()) continue; 7964 7965 unsigned Offset = 4*i; 7966 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7967 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7968 7969 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7970 if (StoreSize > 4) { 7971 Stores.push_back( 7972 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7973 PtrInfo.getWithOffset(Offset), MVT::i32)); 7974 } else { 7975 SDValue StoreValue = BVN->getOperand(i); 7976 if (StoreSize < 4) 7977 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7978 7979 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7980 PtrInfo.getWithOffset(Offset))); 7981 } 7982 } 7983 7984 SDValue StoreChain; 7985 if (!Stores.empty()) 7986 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7987 else 7988 StoreChain = DAG.getEntryNode(); 7989 7990 // Now load from v4i32 into the QPX register; this will extend it to 7991 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7992 // is typed as v4f64 because the QPX register integer states are not 7993 // explicitly represented. 7994 7995 SDValue Ops[] = {StoreChain, 7996 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7997 FIdx}; 7998 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7999 8000 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8001 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8002 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8003 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8004 LoadedVect); 8005 8006 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8007 8008 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8009 } 8010 8011 // All other QPX vectors are handled by generic code. 8012 if (Subtarget.hasQPX()) 8013 return SDValue(); 8014 8015 // Check if this is a splat of a constant value. 8016 APInt APSplatBits, APSplatUndef; 8017 unsigned SplatBitSize; 8018 bool HasAnyUndefs; 8019 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8020 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8021 SplatBitSize > 32) { 8022 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8023 // lowered to VSX instructions under certain conditions. 8024 // Without VSX, there is no pattern more efficient than expanding the node. 8025 if (Subtarget.hasVSX() && 8026 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8027 Subtarget.hasP8Vector())) 8028 return Op; 8029 return SDValue(); 8030 } 8031 8032 unsigned SplatBits = APSplatBits.getZExtValue(); 8033 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8034 unsigned SplatSize = SplatBitSize / 8; 8035 8036 // First, handle single instruction cases. 8037 8038 // All zeros? 8039 if (SplatBits == 0) { 8040 // Canonicalize all zero vectors to be v4i32. 8041 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8042 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8043 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8044 } 8045 return Op; 8046 } 8047 8048 // We have XXSPLTIB for constant splats one byte wide 8049 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8050 // This is a splat of 1-byte elements with some elements potentially undef. 8051 // Rather than trying to match undef in the SDAG patterns, ensure that all 8052 // elements are the same constant. 8053 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8054 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8055 dl, MVT::i32)); 8056 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8057 if (Op.getValueType() != MVT::v16i8) 8058 return DAG.getBitcast(Op.getValueType(), NewBV); 8059 return NewBV; 8060 } 8061 8062 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8063 // detect that constant splats like v8i16: 0xABAB are really just splats 8064 // of a 1-byte constant. In this case, we need to convert the node to a 8065 // splat of v16i8 and a bitcast. 8066 if (Op.getValueType() != MVT::v16i8) 8067 return DAG.getBitcast(Op.getValueType(), 8068 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8069 8070 return Op; 8071 } 8072 8073 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8074 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8075 (32-SplatBitSize)); 8076 if (SextVal >= -16 && SextVal <= 15) 8077 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8078 8079 // Two instruction sequences. 8080 8081 // If this value is in the range [-32,30] and is even, use: 8082 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8083 // If this value is in the range [17,31] and is odd, use: 8084 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8085 // If this value is in the range [-31,-17] and is odd, use: 8086 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8087 // Note the last two are three-instruction sequences. 8088 if (SextVal >= -32 && SextVal <= 31) { 8089 // To avoid having these optimizations undone by constant folding, 8090 // we convert to a pseudo that will be expanded later into one of 8091 // the above forms. 8092 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8093 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8094 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8095 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8096 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8097 if (VT == Op.getValueType()) 8098 return RetVal; 8099 else 8100 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8101 } 8102 8103 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8104 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8105 // for fneg/fabs. 8106 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8107 // Make -1 and vspltisw -1: 8108 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8109 8110 // Make the VSLW intrinsic, computing 0x8000_0000. 8111 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8112 OnesV, DAG, dl); 8113 8114 // xor by OnesV to invert it. 8115 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8116 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8117 } 8118 8119 // Check to see if this is a wide variety of vsplti*, binop self cases. 8120 static const signed char SplatCsts[] = { 8121 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8122 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8123 }; 8124 8125 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8126 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8127 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8128 int i = SplatCsts[idx]; 8129 8130 // Figure out what shift amount will be used by altivec if shifted by i in 8131 // this splat size. 8132 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8133 8134 // vsplti + shl self. 8135 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8136 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8137 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8138 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8139 Intrinsic::ppc_altivec_vslw 8140 }; 8141 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8142 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8143 } 8144 8145 // vsplti + srl self. 8146 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8147 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8148 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8149 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8150 Intrinsic::ppc_altivec_vsrw 8151 }; 8152 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8153 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8154 } 8155 8156 // vsplti + sra self. 8157 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8158 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8159 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8160 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8161 Intrinsic::ppc_altivec_vsraw 8162 }; 8163 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8164 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8165 } 8166 8167 // vsplti + rol self. 8168 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8169 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8170 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8171 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8172 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8173 Intrinsic::ppc_altivec_vrlw 8174 }; 8175 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8176 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8177 } 8178 8179 // t = vsplti c, result = vsldoi t, t, 1 8180 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8181 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8182 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8183 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8184 } 8185 // t = vsplti c, result = vsldoi t, t, 2 8186 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8187 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8188 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8189 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8190 } 8191 // t = vsplti c, result = vsldoi t, t, 3 8192 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8193 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8194 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8195 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8196 } 8197 } 8198 8199 return SDValue(); 8200 } 8201 8202 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8203 /// the specified operations to build the shuffle. 8204 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8205 SDValue RHS, SelectionDAG &DAG, 8206 const SDLoc &dl) { 8207 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8208 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8209 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8210 8211 enum { 8212 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8213 OP_VMRGHW, 8214 OP_VMRGLW, 8215 OP_VSPLTISW0, 8216 OP_VSPLTISW1, 8217 OP_VSPLTISW2, 8218 OP_VSPLTISW3, 8219 OP_VSLDOI4, 8220 OP_VSLDOI8, 8221 OP_VSLDOI12 8222 }; 8223 8224 if (OpNum == OP_COPY) { 8225 if (LHSID == (1*9+2)*9+3) return LHS; 8226 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8227 return RHS; 8228 } 8229 8230 SDValue OpLHS, OpRHS; 8231 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8232 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8233 8234 int ShufIdxs[16]; 8235 switch (OpNum) { 8236 default: llvm_unreachable("Unknown i32 permute!"); 8237 case OP_VMRGHW: 8238 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8239 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8240 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8241 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8242 break; 8243 case OP_VMRGLW: 8244 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8245 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8246 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8247 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8248 break; 8249 case OP_VSPLTISW0: 8250 for (unsigned i = 0; i != 16; ++i) 8251 ShufIdxs[i] = (i&3)+0; 8252 break; 8253 case OP_VSPLTISW1: 8254 for (unsigned i = 0; i != 16; ++i) 8255 ShufIdxs[i] = (i&3)+4; 8256 break; 8257 case OP_VSPLTISW2: 8258 for (unsigned i = 0; i != 16; ++i) 8259 ShufIdxs[i] = (i&3)+8; 8260 break; 8261 case OP_VSPLTISW3: 8262 for (unsigned i = 0; i != 16; ++i) 8263 ShufIdxs[i] = (i&3)+12; 8264 break; 8265 case OP_VSLDOI4: 8266 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8267 case OP_VSLDOI8: 8268 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8269 case OP_VSLDOI12: 8270 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8271 } 8272 EVT VT = OpLHS.getValueType(); 8273 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8274 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8275 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8276 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8277 } 8278 8279 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8280 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8281 /// SDValue. 8282 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8283 SelectionDAG &DAG) const { 8284 const unsigned BytesInVector = 16; 8285 bool IsLE = Subtarget.isLittleEndian(); 8286 SDLoc dl(N); 8287 SDValue V1 = N->getOperand(0); 8288 SDValue V2 = N->getOperand(1); 8289 unsigned ShiftElts = 0, InsertAtByte = 0; 8290 bool Swap = false; 8291 8292 // Shifts required to get the byte we want at element 7. 8293 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8294 0, 15, 14, 13, 12, 11, 10, 9}; 8295 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8296 1, 2, 3, 4, 5, 6, 7, 8}; 8297 8298 ArrayRef<int> Mask = N->getMask(); 8299 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8300 8301 // For each mask element, find out if we're just inserting something 8302 // from V2 into V1 or vice versa. 8303 // Possible permutations inserting an element from V2 into V1: 8304 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8305 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8306 // ... 8307 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8308 // Inserting from V1 into V2 will be similar, except mask range will be 8309 // [16,31]. 8310 8311 bool FoundCandidate = false; 8312 // If both vector operands for the shuffle are the same vector, the mask 8313 // will contain only elements from the first one and the second one will be 8314 // undef. 8315 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8316 // Go through the mask of half-words to find an element that's being moved 8317 // from one vector to the other. 8318 for (unsigned i = 0; i < BytesInVector; ++i) { 8319 unsigned CurrentElement = Mask[i]; 8320 // If 2nd operand is undefined, we should only look for element 7 in the 8321 // Mask. 8322 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8323 continue; 8324 8325 bool OtherElementsInOrder = true; 8326 // Examine the other elements in the Mask to see if they're in original 8327 // order. 8328 for (unsigned j = 0; j < BytesInVector; ++j) { 8329 if (j == i) 8330 continue; 8331 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8332 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8333 // in which we always assume we're always picking from the 1st operand. 8334 int MaskOffset = 8335 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8336 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8337 OtherElementsInOrder = false; 8338 break; 8339 } 8340 } 8341 // If other elements are in original order, we record the number of shifts 8342 // we need to get the element we want into element 7. Also record which byte 8343 // in the vector we should insert into. 8344 if (OtherElementsInOrder) { 8345 // If 2nd operand is undefined, we assume no shifts and no swapping. 8346 if (V2.isUndef()) { 8347 ShiftElts = 0; 8348 Swap = false; 8349 } else { 8350 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8351 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8352 : BigEndianShifts[CurrentElement & 0xF]; 8353 Swap = CurrentElement < BytesInVector; 8354 } 8355 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8356 FoundCandidate = true; 8357 break; 8358 } 8359 } 8360 8361 if (!FoundCandidate) 8362 return SDValue(); 8363 8364 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8365 // optionally with VECSHL if shift is required. 8366 if (Swap) 8367 std::swap(V1, V2); 8368 if (V2.isUndef()) 8369 V2 = V1; 8370 if (ShiftElts) { 8371 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8372 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8373 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8374 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8375 } 8376 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8377 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8378 } 8379 8380 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8381 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8382 /// SDValue. 8383 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8384 SelectionDAG &DAG) const { 8385 const unsigned NumHalfWords = 8; 8386 const unsigned BytesInVector = NumHalfWords * 2; 8387 // Check that the shuffle is on half-words. 8388 if (!isNByteElemShuffleMask(N, 2, 1)) 8389 return SDValue(); 8390 8391 bool IsLE = Subtarget.isLittleEndian(); 8392 SDLoc dl(N); 8393 SDValue V1 = N->getOperand(0); 8394 SDValue V2 = N->getOperand(1); 8395 unsigned ShiftElts = 0, InsertAtByte = 0; 8396 bool Swap = false; 8397 8398 // Shifts required to get the half-word we want at element 3. 8399 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8400 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8401 8402 uint32_t Mask = 0; 8403 uint32_t OriginalOrderLow = 0x1234567; 8404 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8405 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8406 // 32-bit space, only need 4-bit nibbles per element. 8407 for (unsigned i = 0; i < NumHalfWords; ++i) { 8408 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8409 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8410 } 8411 8412 // For each mask element, find out if we're just inserting something 8413 // from V2 into V1 or vice versa. Possible permutations inserting an element 8414 // from V2 into V1: 8415 // X, 1, 2, 3, 4, 5, 6, 7 8416 // 0, X, 2, 3, 4, 5, 6, 7 8417 // 0, 1, X, 3, 4, 5, 6, 7 8418 // 0, 1, 2, X, 4, 5, 6, 7 8419 // 0, 1, 2, 3, X, 5, 6, 7 8420 // 0, 1, 2, 3, 4, X, 6, 7 8421 // 0, 1, 2, 3, 4, 5, X, 7 8422 // 0, 1, 2, 3, 4, 5, 6, X 8423 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8424 8425 bool FoundCandidate = false; 8426 // Go through the mask of half-words to find an element that's being moved 8427 // from one vector to the other. 8428 for (unsigned i = 0; i < NumHalfWords; ++i) { 8429 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8430 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8431 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8432 uint32_t TargetOrder = 0x0; 8433 8434 // If both vector operands for the shuffle are the same vector, the mask 8435 // will contain only elements from the first one and the second one will be 8436 // undef. 8437 if (V2.isUndef()) { 8438 ShiftElts = 0; 8439 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8440 TargetOrder = OriginalOrderLow; 8441 Swap = false; 8442 // Skip if not the correct element or mask of other elements don't equal 8443 // to our expected order. 8444 if (MaskOneElt == VINSERTHSrcElem && 8445 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8446 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8447 FoundCandidate = true; 8448 break; 8449 } 8450 } else { // If both operands are defined. 8451 // Target order is [8,15] if the current mask is between [0,7]. 8452 TargetOrder = 8453 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8454 // Skip if mask of other elements don't equal our expected order. 8455 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8456 // We only need the last 3 bits for the number of shifts. 8457 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8458 : BigEndianShifts[MaskOneElt & 0x7]; 8459 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8460 Swap = MaskOneElt < NumHalfWords; 8461 FoundCandidate = true; 8462 break; 8463 } 8464 } 8465 } 8466 8467 if (!FoundCandidate) 8468 return SDValue(); 8469 8470 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8471 // optionally with VECSHL if shift is required. 8472 if (Swap) 8473 std::swap(V1, V2); 8474 if (V2.isUndef()) 8475 V2 = V1; 8476 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8477 if (ShiftElts) { 8478 // Double ShiftElts because we're left shifting on v16i8 type. 8479 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8480 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8481 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8482 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8483 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8484 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8485 } 8486 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8487 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8488 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8489 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8490 } 8491 8492 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8493 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8494 /// return the code it can be lowered into. Worst case, it can always be 8495 /// lowered into a vperm. 8496 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8497 SelectionDAG &DAG) const { 8498 SDLoc dl(Op); 8499 SDValue V1 = Op.getOperand(0); 8500 SDValue V2 = Op.getOperand(1); 8501 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8502 EVT VT = Op.getValueType(); 8503 bool isLittleEndian = Subtarget.isLittleEndian(); 8504 8505 unsigned ShiftElts, InsertAtByte; 8506 bool Swap = false; 8507 if (Subtarget.hasP9Vector() && 8508 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8509 isLittleEndian)) { 8510 if (Swap) 8511 std::swap(V1, V2); 8512 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8513 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8514 if (ShiftElts) { 8515 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8516 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8517 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8518 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8519 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8520 } 8521 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8522 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8523 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8524 } 8525 8526 if (Subtarget.hasP9Altivec()) { 8527 SDValue NewISDNode; 8528 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8529 return NewISDNode; 8530 8531 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8532 return NewISDNode; 8533 } 8534 8535 if (Subtarget.hasVSX() && 8536 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8537 if (Swap) 8538 std::swap(V1, V2); 8539 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8540 SDValue Conv2 = 8541 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8542 8543 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8544 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8545 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8546 } 8547 8548 if (Subtarget.hasVSX() && 8549 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8550 if (Swap) 8551 std::swap(V1, V2); 8552 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8553 SDValue Conv2 = 8554 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8555 8556 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8557 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8558 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8559 } 8560 8561 if (Subtarget.hasP9Vector()) { 8562 if (PPC::isXXBRHShuffleMask(SVOp)) { 8563 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8564 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8565 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8566 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8567 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8568 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8569 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8570 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8571 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8572 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8573 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8574 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8575 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8576 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8577 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8578 } 8579 } 8580 8581 if (Subtarget.hasVSX()) { 8582 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8583 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8584 8585 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8586 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8587 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8588 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8589 } 8590 8591 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8592 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8593 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8594 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8595 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8596 } 8597 } 8598 8599 if (Subtarget.hasQPX()) { 8600 if (VT.getVectorNumElements() != 4) 8601 return SDValue(); 8602 8603 if (V2.isUndef()) V2 = V1; 8604 8605 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8606 if (AlignIdx != -1) { 8607 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8608 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8609 } else if (SVOp->isSplat()) { 8610 int SplatIdx = SVOp->getSplatIndex(); 8611 if (SplatIdx >= 4) { 8612 std::swap(V1, V2); 8613 SplatIdx -= 4; 8614 } 8615 8616 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8617 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8618 } 8619 8620 // Lower this into a qvgpci/qvfperm pair. 8621 8622 // Compute the qvgpci literal 8623 unsigned idx = 0; 8624 for (unsigned i = 0; i < 4; ++i) { 8625 int m = SVOp->getMaskElt(i); 8626 unsigned mm = m >= 0 ? (unsigned) m : i; 8627 idx |= mm << (3-i)*3; 8628 } 8629 8630 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8631 DAG.getConstant(idx, dl, MVT::i32)); 8632 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8633 } 8634 8635 // Cases that are handled by instructions that take permute immediates 8636 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8637 // selected by the instruction selector. 8638 if (V2.isUndef()) { 8639 if (PPC::isSplatShuffleMask(SVOp, 1) || 8640 PPC::isSplatShuffleMask(SVOp, 2) || 8641 PPC::isSplatShuffleMask(SVOp, 4) || 8642 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8643 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8644 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8645 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8646 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8647 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8648 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8649 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8650 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8651 (Subtarget.hasP8Altivec() && ( 8652 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8653 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8654 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8655 return Op; 8656 } 8657 } 8658 8659 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8660 // and produce a fixed permutation. If any of these match, do not lower to 8661 // VPERM. 8662 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8663 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8664 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8665 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8666 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8667 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8668 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8669 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8670 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8671 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8672 (Subtarget.hasP8Altivec() && ( 8673 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8674 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8675 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8676 return Op; 8677 8678 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8679 // perfect shuffle table to emit an optimal matching sequence. 8680 ArrayRef<int> PermMask = SVOp->getMask(); 8681 8682 unsigned PFIndexes[4]; 8683 bool isFourElementShuffle = true; 8684 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8685 unsigned EltNo = 8; // Start out undef. 8686 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8687 if (PermMask[i*4+j] < 0) 8688 continue; // Undef, ignore it. 8689 8690 unsigned ByteSource = PermMask[i*4+j]; 8691 if ((ByteSource & 3) != j) { 8692 isFourElementShuffle = false; 8693 break; 8694 } 8695 8696 if (EltNo == 8) { 8697 EltNo = ByteSource/4; 8698 } else if (EltNo != ByteSource/4) { 8699 isFourElementShuffle = false; 8700 break; 8701 } 8702 } 8703 PFIndexes[i] = EltNo; 8704 } 8705 8706 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8707 // perfect shuffle vector to determine if it is cost effective to do this as 8708 // discrete instructions, or whether we should use a vperm. 8709 // For now, we skip this for little endian until such time as we have a 8710 // little-endian perfect shuffle table. 8711 if (isFourElementShuffle && !isLittleEndian) { 8712 // Compute the index in the perfect shuffle table. 8713 unsigned PFTableIndex = 8714 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8715 8716 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8717 unsigned Cost = (PFEntry >> 30); 8718 8719 // Determining when to avoid vperm is tricky. Many things affect the cost 8720 // of vperm, particularly how many times the perm mask needs to be computed. 8721 // For example, if the perm mask can be hoisted out of a loop or is already 8722 // used (perhaps because there are multiple permutes with the same shuffle 8723 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8724 // the loop requires an extra register. 8725 // 8726 // As a compromise, we only emit discrete instructions if the shuffle can be 8727 // generated in 3 or fewer operations. When we have loop information 8728 // available, if this block is within a loop, we should avoid using vperm 8729 // for 3-operation perms and use a constant pool load instead. 8730 if (Cost < 3) 8731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8732 } 8733 8734 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8735 // vector that will get spilled to the constant pool. 8736 if (V2.isUndef()) V2 = V1; 8737 8738 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8739 // that it is in input element units, not in bytes. Convert now. 8740 8741 // For little endian, the order of the input vectors is reversed, and 8742 // the permutation mask is complemented with respect to 31. This is 8743 // necessary to produce proper semantics with the big-endian-biased vperm 8744 // instruction. 8745 EVT EltVT = V1.getValueType().getVectorElementType(); 8746 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8747 8748 SmallVector<SDValue, 16> ResultMask; 8749 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8750 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8751 8752 for (unsigned j = 0; j != BytesPerElement; ++j) 8753 if (isLittleEndian) 8754 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8755 dl, MVT::i32)); 8756 else 8757 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8758 MVT::i32)); 8759 } 8760 8761 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8762 if (isLittleEndian) 8763 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8764 V2, V1, VPermMask); 8765 else 8766 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8767 V1, V2, VPermMask); 8768 } 8769 8770 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8771 /// vector comparison. If it is, return true and fill in Opc/isDot with 8772 /// information about the intrinsic. 8773 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8774 bool &isDot, const PPCSubtarget &Subtarget) { 8775 unsigned IntrinsicID = 8776 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8777 CompareOpc = -1; 8778 isDot = false; 8779 switch (IntrinsicID) { 8780 default: 8781 return false; 8782 // Comparison predicates. 8783 case Intrinsic::ppc_altivec_vcmpbfp_p: 8784 CompareOpc = 966; 8785 isDot = true; 8786 break; 8787 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8788 CompareOpc = 198; 8789 isDot = true; 8790 break; 8791 case Intrinsic::ppc_altivec_vcmpequb_p: 8792 CompareOpc = 6; 8793 isDot = true; 8794 break; 8795 case Intrinsic::ppc_altivec_vcmpequh_p: 8796 CompareOpc = 70; 8797 isDot = true; 8798 break; 8799 case Intrinsic::ppc_altivec_vcmpequw_p: 8800 CompareOpc = 134; 8801 isDot = true; 8802 break; 8803 case Intrinsic::ppc_altivec_vcmpequd_p: 8804 if (Subtarget.hasP8Altivec()) { 8805 CompareOpc = 199; 8806 isDot = true; 8807 } else 8808 return false; 8809 break; 8810 case Intrinsic::ppc_altivec_vcmpneb_p: 8811 case Intrinsic::ppc_altivec_vcmpneh_p: 8812 case Intrinsic::ppc_altivec_vcmpnew_p: 8813 case Intrinsic::ppc_altivec_vcmpnezb_p: 8814 case Intrinsic::ppc_altivec_vcmpnezh_p: 8815 case Intrinsic::ppc_altivec_vcmpnezw_p: 8816 if (Subtarget.hasP9Altivec()) { 8817 switch (IntrinsicID) { 8818 default: 8819 llvm_unreachable("Unknown comparison intrinsic."); 8820 case Intrinsic::ppc_altivec_vcmpneb_p: 8821 CompareOpc = 7; 8822 break; 8823 case Intrinsic::ppc_altivec_vcmpneh_p: 8824 CompareOpc = 71; 8825 break; 8826 case Intrinsic::ppc_altivec_vcmpnew_p: 8827 CompareOpc = 135; 8828 break; 8829 case Intrinsic::ppc_altivec_vcmpnezb_p: 8830 CompareOpc = 263; 8831 break; 8832 case Intrinsic::ppc_altivec_vcmpnezh_p: 8833 CompareOpc = 327; 8834 break; 8835 case Intrinsic::ppc_altivec_vcmpnezw_p: 8836 CompareOpc = 391; 8837 break; 8838 } 8839 isDot = true; 8840 } else 8841 return false; 8842 break; 8843 case Intrinsic::ppc_altivec_vcmpgefp_p: 8844 CompareOpc = 454; 8845 isDot = true; 8846 break; 8847 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8848 CompareOpc = 710; 8849 isDot = true; 8850 break; 8851 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8852 CompareOpc = 774; 8853 isDot = true; 8854 break; 8855 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8856 CompareOpc = 838; 8857 isDot = true; 8858 break; 8859 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8860 CompareOpc = 902; 8861 isDot = true; 8862 break; 8863 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8864 if (Subtarget.hasP8Altivec()) { 8865 CompareOpc = 967; 8866 isDot = true; 8867 } else 8868 return false; 8869 break; 8870 case Intrinsic::ppc_altivec_vcmpgtub_p: 8871 CompareOpc = 518; 8872 isDot = true; 8873 break; 8874 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8875 CompareOpc = 582; 8876 isDot = true; 8877 break; 8878 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8879 CompareOpc = 646; 8880 isDot = true; 8881 break; 8882 case Intrinsic::ppc_altivec_vcmpgtud_p: 8883 if (Subtarget.hasP8Altivec()) { 8884 CompareOpc = 711; 8885 isDot = true; 8886 } else 8887 return false; 8888 break; 8889 8890 // VSX predicate comparisons use the same infrastructure 8891 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8892 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8893 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8894 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8895 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8896 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8897 if (Subtarget.hasVSX()) { 8898 switch (IntrinsicID) { 8899 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8900 CompareOpc = 99; 8901 break; 8902 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8903 CompareOpc = 115; 8904 break; 8905 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8906 CompareOpc = 107; 8907 break; 8908 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8909 CompareOpc = 67; 8910 break; 8911 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8912 CompareOpc = 83; 8913 break; 8914 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8915 CompareOpc = 75; 8916 break; 8917 } 8918 isDot = true; 8919 } else 8920 return false; 8921 break; 8922 8923 // Normal Comparisons. 8924 case Intrinsic::ppc_altivec_vcmpbfp: 8925 CompareOpc = 966; 8926 break; 8927 case Intrinsic::ppc_altivec_vcmpeqfp: 8928 CompareOpc = 198; 8929 break; 8930 case Intrinsic::ppc_altivec_vcmpequb: 8931 CompareOpc = 6; 8932 break; 8933 case Intrinsic::ppc_altivec_vcmpequh: 8934 CompareOpc = 70; 8935 break; 8936 case Intrinsic::ppc_altivec_vcmpequw: 8937 CompareOpc = 134; 8938 break; 8939 case Intrinsic::ppc_altivec_vcmpequd: 8940 if (Subtarget.hasP8Altivec()) 8941 CompareOpc = 199; 8942 else 8943 return false; 8944 break; 8945 case Intrinsic::ppc_altivec_vcmpneb: 8946 case Intrinsic::ppc_altivec_vcmpneh: 8947 case Intrinsic::ppc_altivec_vcmpnew: 8948 case Intrinsic::ppc_altivec_vcmpnezb: 8949 case Intrinsic::ppc_altivec_vcmpnezh: 8950 case Intrinsic::ppc_altivec_vcmpnezw: 8951 if (Subtarget.hasP9Altivec()) 8952 switch (IntrinsicID) { 8953 default: 8954 llvm_unreachable("Unknown comparison intrinsic."); 8955 case Intrinsic::ppc_altivec_vcmpneb: 8956 CompareOpc = 7; 8957 break; 8958 case Intrinsic::ppc_altivec_vcmpneh: 8959 CompareOpc = 71; 8960 break; 8961 case Intrinsic::ppc_altivec_vcmpnew: 8962 CompareOpc = 135; 8963 break; 8964 case Intrinsic::ppc_altivec_vcmpnezb: 8965 CompareOpc = 263; 8966 break; 8967 case Intrinsic::ppc_altivec_vcmpnezh: 8968 CompareOpc = 327; 8969 break; 8970 case Intrinsic::ppc_altivec_vcmpnezw: 8971 CompareOpc = 391; 8972 break; 8973 } 8974 else 8975 return false; 8976 break; 8977 case Intrinsic::ppc_altivec_vcmpgefp: 8978 CompareOpc = 454; 8979 break; 8980 case Intrinsic::ppc_altivec_vcmpgtfp: 8981 CompareOpc = 710; 8982 break; 8983 case Intrinsic::ppc_altivec_vcmpgtsb: 8984 CompareOpc = 774; 8985 break; 8986 case Intrinsic::ppc_altivec_vcmpgtsh: 8987 CompareOpc = 838; 8988 break; 8989 case Intrinsic::ppc_altivec_vcmpgtsw: 8990 CompareOpc = 902; 8991 break; 8992 case Intrinsic::ppc_altivec_vcmpgtsd: 8993 if (Subtarget.hasP8Altivec()) 8994 CompareOpc = 967; 8995 else 8996 return false; 8997 break; 8998 case Intrinsic::ppc_altivec_vcmpgtub: 8999 CompareOpc = 518; 9000 break; 9001 case Intrinsic::ppc_altivec_vcmpgtuh: 9002 CompareOpc = 582; 9003 break; 9004 case Intrinsic::ppc_altivec_vcmpgtuw: 9005 CompareOpc = 646; 9006 break; 9007 case Intrinsic::ppc_altivec_vcmpgtud: 9008 if (Subtarget.hasP8Altivec()) 9009 CompareOpc = 711; 9010 else 9011 return false; 9012 break; 9013 } 9014 return true; 9015 } 9016 9017 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9018 /// lower, do it, otherwise return null. 9019 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9020 SelectionDAG &DAG) const { 9021 unsigned IntrinsicID = 9022 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9023 9024 SDLoc dl(Op); 9025 9026 if (IntrinsicID == Intrinsic::thread_pointer) { 9027 // Reads the thread pointer register, used for __builtin_thread_pointer. 9028 if (Subtarget.isPPC64()) 9029 return DAG.getRegister(PPC::X13, MVT::i64); 9030 return DAG.getRegister(PPC::R2, MVT::i32); 9031 } 9032 9033 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9034 // opcode number of the comparison. 9035 int CompareOpc; 9036 bool isDot; 9037 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9038 return SDValue(); // Don't custom lower most intrinsics. 9039 9040 // If this is a non-dot comparison, make the VCMP node and we are done. 9041 if (!isDot) { 9042 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9043 Op.getOperand(1), Op.getOperand(2), 9044 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9045 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9046 } 9047 9048 // Create the PPCISD altivec 'dot' comparison node. 9049 SDValue Ops[] = { 9050 Op.getOperand(2), // LHS 9051 Op.getOperand(3), // RHS 9052 DAG.getConstant(CompareOpc, dl, MVT::i32) 9053 }; 9054 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9055 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9056 9057 // Now that we have the comparison, emit a copy from the CR to a GPR. 9058 // This is flagged to the above dot comparison. 9059 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9060 DAG.getRegister(PPC::CR6, MVT::i32), 9061 CompNode.getValue(1)); 9062 9063 // Unpack the result based on how the target uses it. 9064 unsigned BitNo; // Bit # of CR6. 9065 bool InvertBit; // Invert result? 9066 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9067 default: // Can't happen, don't crash on invalid number though. 9068 case 0: // Return the value of the EQ bit of CR6. 9069 BitNo = 0; InvertBit = false; 9070 break; 9071 case 1: // Return the inverted value of the EQ bit of CR6. 9072 BitNo = 0; InvertBit = true; 9073 break; 9074 case 2: // Return the value of the LT bit of CR6. 9075 BitNo = 2; InvertBit = false; 9076 break; 9077 case 3: // Return the inverted value of the LT bit of CR6. 9078 BitNo = 2; InvertBit = true; 9079 break; 9080 } 9081 9082 // Shift the bit into the low position. 9083 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9084 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9085 // Isolate the bit. 9086 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9087 DAG.getConstant(1, dl, MVT::i32)); 9088 9089 // If we are supposed to, toggle the bit. 9090 if (InvertBit) 9091 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9092 DAG.getConstant(1, dl, MVT::i32)); 9093 return Flags; 9094 } 9095 9096 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9097 SelectionDAG &DAG) const { 9098 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9099 // the beginning of the argument list. 9100 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9101 SDLoc DL(Op); 9102 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9103 case Intrinsic::ppc_cfence: { 9104 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9105 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9106 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9107 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9108 Op.getOperand(ArgStart + 1)), 9109 Op.getOperand(0)), 9110 0); 9111 } 9112 default: 9113 break; 9114 } 9115 return SDValue(); 9116 } 9117 9118 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9119 // Check for a DIV with the same operands as this REM. 9120 for (auto UI : Op.getOperand(1)->uses()) { 9121 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9122 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9123 if (UI->getOperand(0) == Op.getOperand(0) && 9124 UI->getOperand(1) == Op.getOperand(1)) 9125 return SDValue(); 9126 } 9127 return Op; 9128 } 9129 9130 // Lower scalar BSWAP64 to xxbrd. 9131 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9132 SDLoc dl(Op); 9133 // MTVSRDD 9134 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9135 Op.getOperand(0)); 9136 // XXBRD 9137 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9138 // MFVSRD 9139 int VectorIndex = 0; 9140 if (Subtarget.isLittleEndian()) 9141 VectorIndex = 1; 9142 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9143 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9144 return Op; 9145 } 9146 9147 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9148 // compared to a value that is atomically loaded (atomic loads zero-extend). 9149 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9150 SelectionDAG &DAG) const { 9151 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9152 "Expecting an atomic compare-and-swap here."); 9153 SDLoc dl(Op); 9154 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9155 EVT MemVT = AtomicNode->getMemoryVT(); 9156 if (MemVT.getSizeInBits() >= 32) 9157 return Op; 9158 9159 SDValue CmpOp = Op.getOperand(2); 9160 // If this is already correctly zero-extended, leave it alone. 9161 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9162 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9163 return Op; 9164 9165 // Clear the high bits of the compare operand. 9166 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9167 SDValue NewCmpOp = 9168 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9169 DAG.getConstant(MaskVal, dl, MVT::i32)); 9170 9171 // Replace the existing compare operand with the properly zero-extended one. 9172 SmallVector<SDValue, 4> Ops; 9173 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9174 Ops.push_back(AtomicNode->getOperand(i)); 9175 Ops[2] = NewCmpOp; 9176 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9177 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9178 auto NodeTy = 9179 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9180 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9181 } 9182 9183 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9184 SelectionDAG &DAG) const { 9185 SDLoc dl(Op); 9186 // Create a stack slot that is 16-byte aligned. 9187 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9188 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9189 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9190 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9191 9192 // Store the input value into Value#0 of the stack slot. 9193 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9194 MachinePointerInfo()); 9195 // Load it out. 9196 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9197 } 9198 9199 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9200 SelectionDAG &DAG) const { 9201 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9202 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9203 9204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9205 // We have legal lowering for constant indices but not for variable ones. 9206 if (!C) 9207 return SDValue(); 9208 9209 EVT VT = Op.getValueType(); 9210 SDLoc dl(Op); 9211 SDValue V1 = Op.getOperand(0); 9212 SDValue V2 = Op.getOperand(1); 9213 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9214 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9215 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9216 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9217 unsigned InsertAtElement = C->getZExtValue(); 9218 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9219 if (Subtarget.isLittleEndian()) { 9220 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9221 } 9222 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9223 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9224 } 9225 return Op; 9226 } 9227 9228 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9229 SelectionDAG &DAG) const { 9230 SDLoc dl(Op); 9231 SDNode *N = Op.getNode(); 9232 9233 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9234 "Unknown extract_vector_elt type"); 9235 9236 SDValue Value = N->getOperand(0); 9237 9238 // The first part of this is like the store lowering except that we don't 9239 // need to track the chain. 9240 9241 // The values are now known to be -1 (false) or 1 (true). To convert this 9242 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9243 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9244 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9245 9246 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9247 // understand how to form the extending load. 9248 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9249 9250 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9251 9252 // Now convert to an integer and store. 9253 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9254 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9255 Value); 9256 9257 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9258 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9259 MachinePointerInfo PtrInfo = 9260 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9261 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9262 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9263 9264 SDValue StoreChain = DAG.getEntryNode(); 9265 SDValue Ops[] = {StoreChain, 9266 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9267 Value, FIdx}; 9268 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9269 9270 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9271 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9272 9273 // Extract the value requested. 9274 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9275 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9276 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9277 9278 SDValue IntVal = 9279 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9280 9281 if (!Subtarget.useCRBits()) 9282 return IntVal; 9283 9284 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9285 } 9286 9287 /// Lowering for QPX v4i1 loads 9288 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9289 SelectionDAG &DAG) const { 9290 SDLoc dl(Op); 9291 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9292 SDValue LoadChain = LN->getChain(); 9293 SDValue BasePtr = LN->getBasePtr(); 9294 9295 if (Op.getValueType() == MVT::v4f64 || 9296 Op.getValueType() == MVT::v4f32) { 9297 EVT MemVT = LN->getMemoryVT(); 9298 unsigned Alignment = LN->getAlignment(); 9299 9300 // If this load is properly aligned, then it is legal. 9301 if (Alignment >= MemVT.getStoreSize()) 9302 return Op; 9303 9304 EVT ScalarVT = Op.getValueType().getScalarType(), 9305 ScalarMemVT = MemVT.getScalarType(); 9306 unsigned Stride = ScalarMemVT.getStoreSize(); 9307 9308 SDValue Vals[4], LoadChains[4]; 9309 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9310 SDValue Load; 9311 if (ScalarVT != ScalarMemVT) 9312 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9313 BasePtr, 9314 LN->getPointerInfo().getWithOffset(Idx * Stride), 9315 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9316 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9317 else 9318 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9319 LN->getPointerInfo().getWithOffset(Idx * Stride), 9320 MinAlign(Alignment, Idx * Stride), 9321 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9322 9323 if (Idx == 0 && LN->isIndexed()) { 9324 assert(LN->getAddressingMode() == ISD::PRE_INC && 9325 "Unknown addressing mode on vector load"); 9326 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9327 LN->getAddressingMode()); 9328 } 9329 9330 Vals[Idx] = Load; 9331 LoadChains[Idx] = Load.getValue(1); 9332 9333 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9334 DAG.getConstant(Stride, dl, 9335 BasePtr.getValueType())); 9336 } 9337 9338 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9339 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9340 9341 if (LN->isIndexed()) { 9342 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9343 return DAG.getMergeValues(RetOps, dl); 9344 } 9345 9346 SDValue RetOps[] = { Value, TF }; 9347 return DAG.getMergeValues(RetOps, dl); 9348 } 9349 9350 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9351 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9352 9353 // To lower v4i1 from a byte array, we load the byte elements of the 9354 // vector and then reuse the BUILD_VECTOR logic. 9355 9356 SDValue VectElmts[4], VectElmtChains[4]; 9357 for (unsigned i = 0; i < 4; ++i) { 9358 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9359 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9360 9361 VectElmts[i] = DAG.getExtLoad( 9362 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9363 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9364 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9365 VectElmtChains[i] = VectElmts[i].getValue(1); 9366 } 9367 9368 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9369 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9370 9371 SDValue RVals[] = { Value, LoadChain }; 9372 return DAG.getMergeValues(RVals, dl); 9373 } 9374 9375 /// Lowering for QPX v4i1 stores 9376 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9377 SelectionDAG &DAG) const { 9378 SDLoc dl(Op); 9379 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9380 SDValue StoreChain = SN->getChain(); 9381 SDValue BasePtr = SN->getBasePtr(); 9382 SDValue Value = SN->getValue(); 9383 9384 if (Value.getValueType() == MVT::v4f64 || 9385 Value.getValueType() == MVT::v4f32) { 9386 EVT MemVT = SN->getMemoryVT(); 9387 unsigned Alignment = SN->getAlignment(); 9388 9389 // If this store is properly aligned, then it is legal. 9390 if (Alignment >= MemVT.getStoreSize()) 9391 return Op; 9392 9393 EVT ScalarVT = Value.getValueType().getScalarType(), 9394 ScalarMemVT = MemVT.getScalarType(); 9395 unsigned Stride = ScalarMemVT.getStoreSize(); 9396 9397 SDValue Stores[4]; 9398 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9399 SDValue Ex = DAG.getNode( 9400 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9401 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9402 SDValue Store; 9403 if (ScalarVT != ScalarMemVT) 9404 Store = 9405 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9406 SN->getPointerInfo().getWithOffset(Idx * Stride), 9407 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9408 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9409 else 9410 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9411 SN->getPointerInfo().getWithOffset(Idx * Stride), 9412 MinAlign(Alignment, Idx * Stride), 9413 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9414 9415 if (Idx == 0 && SN->isIndexed()) { 9416 assert(SN->getAddressingMode() == ISD::PRE_INC && 9417 "Unknown addressing mode on vector store"); 9418 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9419 SN->getAddressingMode()); 9420 } 9421 9422 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9423 DAG.getConstant(Stride, dl, 9424 BasePtr.getValueType())); 9425 Stores[Idx] = Store; 9426 } 9427 9428 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9429 9430 if (SN->isIndexed()) { 9431 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9432 return DAG.getMergeValues(RetOps, dl); 9433 } 9434 9435 return TF; 9436 } 9437 9438 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9439 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9440 9441 // The values are now known to be -1 (false) or 1 (true). To convert this 9442 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9443 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9444 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9445 9446 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9447 // understand how to form the extending load. 9448 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9449 9450 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9451 9452 // Now convert to an integer and store. 9453 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9454 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9455 Value); 9456 9457 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9458 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9459 MachinePointerInfo PtrInfo = 9460 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9461 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9462 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9463 9464 SDValue Ops[] = {StoreChain, 9465 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9466 Value, FIdx}; 9467 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9468 9469 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9470 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9471 9472 // Move data into the byte array. 9473 SDValue Loads[4], LoadChains[4]; 9474 for (unsigned i = 0; i < 4; ++i) { 9475 unsigned Offset = 4*i; 9476 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9477 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9478 9479 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9480 PtrInfo.getWithOffset(Offset)); 9481 LoadChains[i] = Loads[i].getValue(1); 9482 } 9483 9484 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9485 9486 SDValue Stores[4]; 9487 for (unsigned i = 0; i < 4; ++i) { 9488 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9489 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9490 9491 Stores[i] = DAG.getTruncStore( 9492 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9493 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9494 SN->getAAInfo()); 9495 } 9496 9497 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9498 9499 return StoreChain; 9500 } 9501 9502 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9503 SDLoc dl(Op); 9504 if (Op.getValueType() == MVT::v4i32) { 9505 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9506 9507 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9508 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9509 9510 SDValue RHSSwap = // = vrlw RHS, 16 9511 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9512 9513 // Shrinkify inputs to v8i16. 9514 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9515 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9516 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9517 9518 // Low parts multiplied together, generating 32-bit results (we ignore the 9519 // top parts). 9520 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9521 LHS, RHS, DAG, dl, MVT::v4i32); 9522 9523 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9524 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9525 // Shift the high parts up 16 bits. 9526 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9527 Neg16, DAG, dl); 9528 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9529 } else if (Op.getValueType() == MVT::v8i16) { 9530 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9531 9532 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9533 9534 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9535 LHS, RHS, Zero, DAG, dl); 9536 } else if (Op.getValueType() == MVT::v16i8) { 9537 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9538 bool isLittleEndian = Subtarget.isLittleEndian(); 9539 9540 // Multiply the even 8-bit parts, producing 16-bit sums. 9541 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9542 LHS, RHS, DAG, dl, MVT::v8i16); 9543 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9544 9545 // Multiply the odd 8-bit parts, producing 16-bit sums. 9546 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9547 LHS, RHS, DAG, dl, MVT::v8i16); 9548 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9549 9550 // Merge the results together. Because vmuleub and vmuloub are 9551 // instructions with a big-endian bias, we must reverse the 9552 // element numbering and reverse the meaning of "odd" and "even" 9553 // when generating little endian code. 9554 int Ops[16]; 9555 for (unsigned i = 0; i != 8; ++i) { 9556 if (isLittleEndian) { 9557 Ops[i*2 ] = 2*i; 9558 Ops[i*2+1] = 2*i+16; 9559 } else { 9560 Ops[i*2 ] = 2*i+1; 9561 Ops[i*2+1] = 2*i+1+16; 9562 } 9563 } 9564 if (isLittleEndian) 9565 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9566 else 9567 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9568 } else { 9569 llvm_unreachable("Unknown mul to lower!"); 9570 } 9571 } 9572 9573 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9574 9575 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9576 9577 EVT VT = Op.getValueType(); 9578 assert(VT.isVector() && 9579 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9580 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9581 VT == MVT::v16i8) && 9582 "Unexpected vector element type!"); 9583 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9584 "Current subtarget doesn't support smax v2i64!"); 9585 9586 // For vector abs, it can be lowered to: 9587 // abs x 9588 // ==> 9589 // y = -x 9590 // smax(x, y) 9591 9592 SDLoc dl(Op); 9593 SDValue X = Op.getOperand(0); 9594 SDValue Zero = DAG.getConstant(0, dl, VT); 9595 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9596 9597 // SMAX patch https://reviews.llvm.org/D47332 9598 // hasn't landed yet, so use intrinsic first here. 9599 // TODO: Should use SMAX directly once SMAX patch landed 9600 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9601 if (VT == MVT::v2i64) 9602 BifID = Intrinsic::ppc_altivec_vmaxsd; 9603 else if (VT == MVT::v8i16) 9604 BifID = Intrinsic::ppc_altivec_vmaxsh; 9605 else if (VT == MVT::v16i8) 9606 BifID = Intrinsic::ppc_altivec_vmaxsb; 9607 9608 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9609 } 9610 9611 /// LowerOperation - Provide custom lowering hooks for some operations. 9612 /// 9613 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9614 switch (Op.getOpcode()) { 9615 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9616 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9617 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9618 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9619 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9620 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9621 case ISD::SETCC: return LowerSETCC(Op, DAG); 9622 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9623 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9624 9625 // Variable argument lowering. 9626 case ISD::VASTART: return LowerVASTART(Op, DAG); 9627 case ISD::VAARG: return LowerVAARG(Op, DAG); 9628 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9629 9630 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9631 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9632 case ISD::GET_DYNAMIC_AREA_OFFSET: 9633 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9634 9635 // Exception handling lowering. 9636 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9637 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9638 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9639 9640 case ISD::LOAD: return LowerLOAD(Op, DAG); 9641 case ISD::STORE: return LowerSTORE(Op, DAG); 9642 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9643 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9644 case ISD::FP_TO_UINT: 9645 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9646 case ISD::UINT_TO_FP: 9647 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9648 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9649 9650 // Lower 64-bit shifts. 9651 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9652 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9653 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9654 9655 // Vector-related lowering. 9656 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9657 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9658 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9659 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9660 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9661 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9662 case ISD::MUL: return LowerMUL(Op, DAG); 9663 case ISD::ABS: return LowerABS(Op, DAG); 9664 9665 // For counter-based loop handling. 9666 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9667 9668 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9669 9670 // Frame & Return address. 9671 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9672 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9673 9674 case ISD::INTRINSIC_VOID: 9675 return LowerINTRINSIC_VOID(Op, DAG); 9676 case ISD::SREM: 9677 case ISD::UREM: 9678 return LowerREM(Op, DAG); 9679 case ISD::BSWAP: 9680 return LowerBSWAP(Op, DAG); 9681 case ISD::ATOMIC_CMP_SWAP: 9682 return LowerATOMIC_CMP_SWAP(Op, DAG); 9683 } 9684 } 9685 9686 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9687 SmallVectorImpl<SDValue>&Results, 9688 SelectionDAG &DAG) const { 9689 SDLoc dl(N); 9690 switch (N->getOpcode()) { 9691 default: 9692 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9693 case ISD::READCYCLECOUNTER: { 9694 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9695 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9696 9697 Results.push_back(RTB); 9698 Results.push_back(RTB.getValue(1)); 9699 Results.push_back(RTB.getValue(2)); 9700 break; 9701 } 9702 case ISD::INTRINSIC_W_CHAIN: { 9703 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9704 Intrinsic::ppc_is_decremented_ctr_nonzero) 9705 break; 9706 9707 assert(N->getValueType(0) == MVT::i1 && 9708 "Unexpected result type for CTR decrement intrinsic"); 9709 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9710 N->getValueType(0)); 9711 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9712 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9713 N->getOperand(1)); 9714 9715 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9716 Results.push_back(NewInt.getValue(1)); 9717 break; 9718 } 9719 case ISD::VAARG: { 9720 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9721 return; 9722 9723 EVT VT = N->getValueType(0); 9724 9725 if (VT == MVT::i64) { 9726 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9727 9728 Results.push_back(NewNode); 9729 Results.push_back(NewNode.getValue(1)); 9730 } 9731 return; 9732 } 9733 case ISD::FP_TO_SINT: 9734 case ISD::FP_TO_UINT: 9735 // LowerFP_TO_INT() can only handle f32 and f64. 9736 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9737 return; 9738 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9739 return; 9740 case ISD::TRUNCATE: { 9741 EVT TrgVT = N->getValueType(0); 9742 if (TrgVT.isVector() && 9743 isOperationCustom(N->getOpcode(), TrgVT) && 9744 N->getOperand(0).getValueType().getSizeInBits() <= 128) 9745 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 9746 return; 9747 } 9748 case ISD::BITCAST: 9749 // Don't handle bitcast here. 9750 return; 9751 } 9752 } 9753 9754 //===----------------------------------------------------------------------===// 9755 // Other Lowering Code 9756 //===----------------------------------------------------------------------===// 9757 9758 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9759 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9760 Function *Func = Intrinsic::getDeclaration(M, Id); 9761 return Builder.CreateCall(Func, {}); 9762 } 9763 9764 // The mappings for emitLeading/TrailingFence is taken from 9765 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9766 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9767 Instruction *Inst, 9768 AtomicOrdering Ord) const { 9769 if (Ord == AtomicOrdering::SequentiallyConsistent) 9770 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9771 if (isReleaseOrStronger(Ord)) 9772 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9773 return nullptr; 9774 } 9775 9776 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9777 Instruction *Inst, 9778 AtomicOrdering Ord) const { 9779 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9780 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9781 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9782 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9783 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9784 return Builder.CreateCall( 9785 Intrinsic::getDeclaration( 9786 Builder.GetInsertBlock()->getParent()->getParent(), 9787 Intrinsic::ppc_cfence, {Inst->getType()}), 9788 {Inst}); 9789 // FIXME: Can use isync for rmw operation. 9790 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9791 } 9792 return nullptr; 9793 } 9794 9795 MachineBasicBlock * 9796 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9797 unsigned AtomicSize, 9798 unsigned BinOpcode, 9799 unsigned CmpOpcode, 9800 unsigned CmpPred) const { 9801 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9802 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9803 9804 auto LoadMnemonic = PPC::LDARX; 9805 auto StoreMnemonic = PPC::STDCX; 9806 switch (AtomicSize) { 9807 default: 9808 llvm_unreachable("Unexpected size of atomic entity"); 9809 case 1: 9810 LoadMnemonic = PPC::LBARX; 9811 StoreMnemonic = PPC::STBCX; 9812 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9813 break; 9814 case 2: 9815 LoadMnemonic = PPC::LHARX; 9816 StoreMnemonic = PPC::STHCX; 9817 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9818 break; 9819 case 4: 9820 LoadMnemonic = PPC::LWARX; 9821 StoreMnemonic = PPC::STWCX; 9822 break; 9823 case 8: 9824 LoadMnemonic = PPC::LDARX; 9825 StoreMnemonic = PPC::STDCX; 9826 break; 9827 } 9828 9829 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9830 MachineFunction *F = BB->getParent(); 9831 MachineFunction::iterator It = ++BB->getIterator(); 9832 9833 unsigned dest = MI.getOperand(0).getReg(); 9834 unsigned ptrA = MI.getOperand(1).getReg(); 9835 unsigned ptrB = MI.getOperand(2).getReg(); 9836 unsigned incr = MI.getOperand(3).getReg(); 9837 DebugLoc dl = MI.getDebugLoc(); 9838 9839 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9840 MachineBasicBlock *loop2MBB = 9841 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9842 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9843 F->insert(It, loopMBB); 9844 if (CmpOpcode) 9845 F->insert(It, loop2MBB); 9846 F->insert(It, exitMBB); 9847 exitMBB->splice(exitMBB->begin(), BB, 9848 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9849 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9850 9851 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9852 unsigned TmpReg = (!BinOpcode) ? incr : 9853 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9854 : &PPC::GPRCRegClass); 9855 9856 // thisMBB: 9857 // ... 9858 // fallthrough --> loopMBB 9859 BB->addSuccessor(loopMBB); 9860 9861 // loopMBB: 9862 // l[wd]arx dest, ptr 9863 // add r0, dest, incr 9864 // st[wd]cx. r0, ptr 9865 // bne- loopMBB 9866 // fallthrough --> exitMBB 9867 9868 // For max/min... 9869 // loopMBB: 9870 // l[wd]arx dest, ptr 9871 // cmpl?[wd] incr, dest 9872 // bgt exitMBB 9873 // loop2MBB: 9874 // st[wd]cx. dest, ptr 9875 // bne- loopMBB 9876 // fallthrough --> exitMBB 9877 9878 BB = loopMBB; 9879 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9880 .addReg(ptrA).addReg(ptrB); 9881 if (BinOpcode) 9882 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9883 if (CmpOpcode) { 9884 // Signed comparisons of byte or halfword values must be sign-extended. 9885 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9886 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9887 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9888 ExtReg).addReg(dest); 9889 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9890 .addReg(incr).addReg(ExtReg); 9891 } else 9892 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9893 .addReg(incr).addReg(dest); 9894 9895 BuildMI(BB, dl, TII->get(PPC::BCC)) 9896 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9897 BB->addSuccessor(loop2MBB); 9898 BB->addSuccessor(exitMBB); 9899 BB = loop2MBB; 9900 } 9901 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9902 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9903 BuildMI(BB, dl, TII->get(PPC::BCC)) 9904 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9905 BB->addSuccessor(loopMBB); 9906 BB->addSuccessor(exitMBB); 9907 9908 // exitMBB: 9909 // ... 9910 BB = exitMBB; 9911 return BB; 9912 } 9913 9914 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 9915 MachineInstr &MI, MachineBasicBlock *BB, 9916 bool is8bit, // operation 9917 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 9918 // If we support part-word atomic mnemonics, just use them 9919 if (Subtarget.hasPartwordAtomics()) 9920 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 9921 CmpPred); 9922 9923 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9924 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9925 // In 64 bit mode we have to use 64 bits for addresses, even though the 9926 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9927 // registers without caring whether they're 32 or 64, but here we're 9928 // doing actual arithmetic on the addresses. 9929 bool is64bit = Subtarget.isPPC64(); 9930 bool isLittleEndian = Subtarget.isLittleEndian(); 9931 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9932 9933 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9934 MachineFunction *F = BB->getParent(); 9935 MachineFunction::iterator It = ++BB->getIterator(); 9936 9937 unsigned dest = MI.getOperand(0).getReg(); 9938 unsigned ptrA = MI.getOperand(1).getReg(); 9939 unsigned ptrB = MI.getOperand(2).getReg(); 9940 unsigned incr = MI.getOperand(3).getReg(); 9941 DebugLoc dl = MI.getDebugLoc(); 9942 9943 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9944 MachineBasicBlock *loop2MBB = 9945 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9946 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9947 F->insert(It, loopMBB); 9948 if (CmpOpcode) 9949 F->insert(It, loop2MBB); 9950 F->insert(It, exitMBB); 9951 exitMBB->splice(exitMBB->begin(), BB, 9952 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9953 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9954 9955 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9956 const TargetRegisterClass *RC = 9957 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9958 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 9959 9960 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9961 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 9962 unsigned ShiftReg = 9963 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 9964 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC); 9965 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 9966 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 9967 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 9968 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 9969 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 9970 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 9971 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 9972 unsigned Ptr1Reg; 9973 unsigned TmpReg = 9974 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 9975 9976 // thisMBB: 9977 // ... 9978 // fallthrough --> loopMBB 9979 BB->addSuccessor(loopMBB); 9980 9981 // The 4-byte load must be aligned, while a char or short may be 9982 // anywhere in the word. Hence all this nasty bookkeeping code. 9983 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9984 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9985 // xori shift, shift1, 24 [16] 9986 // rlwinm ptr, ptr1, 0, 0, 29 9987 // slw incr2, incr, shift 9988 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9989 // slw mask, mask2, shift 9990 // loopMBB: 9991 // lwarx tmpDest, ptr 9992 // add tmp, tmpDest, incr2 9993 // andc tmp2, tmpDest, mask 9994 // and tmp3, tmp, mask 9995 // or tmp4, tmp3, tmp2 9996 // stwcx. tmp4, ptr 9997 // bne- loopMBB 9998 // fallthrough --> exitMBB 9999 // srw dest, tmpDest, shift 10000 if (ptrA != ZeroReg) { 10001 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10002 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10003 .addReg(ptrA) 10004 .addReg(ptrB); 10005 } else { 10006 Ptr1Reg = ptrB; 10007 } 10008 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10009 // mode. 10010 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10011 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10012 .addImm(3) 10013 .addImm(27) 10014 .addImm(is8bit ? 28 : 27); 10015 if (!isLittleEndian) 10016 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10017 .addReg(Shift1Reg) 10018 .addImm(is8bit ? 24 : 16); 10019 if (is64bit) 10020 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10021 .addReg(Ptr1Reg) 10022 .addImm(0) 10023 .addImm(61); 10024 else 10025 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10026 .addReg(Ptr1Reg) 10027 .addImm(0) 10028 .addImm(0) 10029 .addImm(29); 10030 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10031 if (is8bit) 10032 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10033 else { 10034 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10035 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10036 .addReg(Mask3Reg) 10037 .addImm(65535); 10038 } 10039 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10040 .addReg(Mask2Reg) 10041 .addReg(ShiftReg); 10042 10043 BB = loopMBB; 10044 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10045 .addReg(ZeroReg) 10046 .addReg(PtrReg); 10047 if (BinOpcode) 10048 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10049 .addReg(Incr2Reg) 10050 .addReg(TmpDestReg); 10051 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10052 .addReg(TmpDestReg) 10053 .addReg(MaskReg); 10054 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10055 if (CmpOpcode) { 10056 // For unsigned comparisons, we can directly compare the shifted values. 10057 // For signed comparisons we shift and sign extend. 10058 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10059 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10060 .addReg(TmpDestReg) 10061 .addReg(MaskReg); 10062 unsigned ValueReg = SReg; 10063 unsigned CmpReg = Incr2Reg; 10064 if (CmpOpcode == PPC::CMPW) { 10065 ValueReg = RegInfo.createVirtualRegister(GPRC); 10066 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10067 .addReg(SReg) 10068 .addReg(ShiftReg); 10069 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10070 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10071 .addReg(ValueReg); 10072 ValueReg = ValueSReg; 10073 CmpReg = incr; 10074 } 10075 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10076 .addReg(CmpReg) 10077 .addReg(ValueReg); 10078 BuildMI(BB, dl, TII->get(PPC::BCC)) 10079 .addImm(CmpPred) 10080 .addReg(PPC::CR0) 10081 .addMBB(exitMBB); 10082 BB->addSuccessor(loop2MBB); 10083 BB->addSuccessor(exitMBB); 10084 BB = loop2MBB; 10085 } 10086 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10087 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10088 .addReg(Tmp4Reg) 10089 .addReg(ZeroReg) 10090 .addReg(PtrReg); 10091 BuildMI(BB, dl, TII->get(PPC::BCC)) 10092 .addImm(PPC::PRED_NE) 10093 .addReg(PPC::CR0) 10094 .addMBB(loopMBB); 10095 BB->addSuccessor(loopMBB); 10096 BB->addSuccessor(exitMBB); 10097 10098 // exitMBB: 10099 // ... 10100 BB = exitMBB; 10101 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10102 .addReg(TmpDestReg) 10103 .addReg(ShiftReg); 10104 return BB; 10105 } 10106 10107 llvm::MachineBasicBlock * 10108 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10109 MachineBasicBlock *MBB) const { 10110 DebugLoc DL = MI.getDebugLoc(); 10111 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10112 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10113 10114 MachineFunction *MF = MBB->getParent(); 10115 MachineRegisterInfo &MRI = MF->getRegInfo(); 10116 10117 const BasicBlock *BB = MBB->getBasicBlock(); 10118 MachineFunction::iterator I = ++MBB->getIterator(); 10119 10120 unsigned DstReg = MI.getOperand(0).getReg(); 10121 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10122 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10123 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10124 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10125 10126 MVT PVT = getPointerTy(MF->getDataLayout()); 10127 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10128 "Invalid Pointer Size!"); 10129 // For v = setjmp(buf), we generate 10130 // 10131 // thisMBB: 10132 // SjLjSetup mainMBB 10133 // bl mainMBB 10134 // v_restore = 1 10135 // b sinkMBB 10136 // 10137 // mainMBB: 10138 // buf[LabelOffset] = LR 10139 // v_main = 0 10140 // 10141 // sinkMBB: 10142 // v = phi(main, restore) 10143 // 10144 10145 MachineBasicBlock *thisMBB = MBB; 10146 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10147 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10148 MF->insert(I, mainMBB); 10149 MF->insert(I, sinkMBB); 10150 10151 MachineInstrBuilder MIB; 10152 10153 // Transfer the remainder of BB and its successor edges to sinkMBB. 10154 sinkMBB->splice(sinkMBB->begin(), MBB, 10155 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10156 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10157 10158 // Note that the structure of the jmp_buf used here is not compatible 10159 // with that used by libc, and is not designed to be. Specifically, it 10160 // stores only those 'reserved' registers that LLVM does not otherwise 10161 // understand how to spill. Also, by convention, by the time this 10162 // intrinsic is called, Clang has already stored the frame address in the 10163 // first slot of the buffer and stack address in the third. Following the 10164 // X86 target code, we'll store the jump address in the second slot. We also 10165 // need to save the TOC pointer (R2) to handle jumps between shared 10166 // libraries, and that will be stored in the fourth slot. The thread 10167 // identifier (R13) is not affected. 10168 10169 // thisMBB: 10170 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10171 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10172 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10173 10174 // Prepare IP either in reg. 10175 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10176 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10177 unsigned BufReg = MI.getOperand(1).getReg(); 10178 10179 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10180 setUsesTOCBasePtr(*MBB->getParent()); 10181 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10182 .addReg(PPC::X2) 10183 .addImm(TOCOffset) 10184 .addReg(BufReg) 10185 .cloneMemRefs(MI); 10186 } 10187 10188 // Naked functions never have a base pointer, and so we use r1. For all 10189 // other functions, this decision must be delayed until during PEI. 10190 unsigned BaseReg; 10191 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10192 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10193 else 10194 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10195 10196 MIB = BuildMI(*thisMBB, MI, DL, 10197 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10198 .addReg(BaseReg) 10199 .addImm(BPOffset) 10200 .addReg(BufReg) 10201 .cloneMemRefs(MI); 10202 10203 // Setup 10204 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10205 MIB.addRegMask(TRI->getNoPreservedMask()); 10206 10207 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10208 10209 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10210 .addMBB(mainMBB); 10211 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10212 10213 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10214 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10215 10216 // mainMBB: 10217 // mainDstReg = 0 10218 MIB = 10219 BuildMI(mainMBB, DL, 10220 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10221 10222 // Store IP 10223 if (Subtarget.isPPC64()) { 10224 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10225 .addReg(LabelReg) 10226 .addImm(LabelOffset) 10227 .addReg(BufReg); 10228 } else { 10229 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10230 .addReg(LabelReg) 10231 .addImm(LabelOffset) 10232 .addReg(BufReg); 10233 } 10234 MIB.cloneMemRefs(MI); 10235 10236 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10237 mainMBB->addSuccessor(sinkMBB); 10238 10239 // sinkMBB: 10240 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10241 TII->get(PPC::PHI), DstReg) 10242 .addReg(mainDstReg).addMBB(mainMBB) 10243 .addReg(restoreDstReg).addMBB(thisMBB); 10244 10245 MI.eraseFromParent(); 10246 return sinkMBB; 10247 } 10248 10249 MachineBasicBlock * 10250 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10251 MachineBasicBlock *MBB) const { 10252 DebugLoc DL = MI.getDebugLoc(); 10253 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10254 10255 MachineFunction *MF = MBB->getParent(); 10256 MachineRegisterInfo &MRI = MF->getRegInfo(); 10257 10258 MVT PVT = getPointerTy(MF->getDataLayout()); 10259 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10260 "Invalid Pointer Size!"); 10261 10262 const TargetRegisterClass *RC = 10263 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10264 unsigned Tmp = MRI.createVirtualRegister(RC); 10265 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10266 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10267 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10268 unsigned BP = 10269 (PVT == MVT::i64) 10270 ? PPC::X30 10271 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10272 : PPC::R30); 10273 10274 MachineInstrBuilder MIB; 10275 10276 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10277 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10278 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10279 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10280 10281 unsigned BufReg = MI.getOperand(0).getReg(); 10282 10283 // Reload FP (the jumped-to function may not have had a 10284 // frame pointer, and if so, then its r31 will be restored 10285 // as necessary). 10286 if (PVT == MVT::i64) { 10287 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10288 .addImm(0) 10289 .addReg(BufReg); 10290 } else { 10291 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10292 .addImm(0) 10293 .addReg(BufReg); 10294 } 10295 MIB.cloneMemRefs(MI); 10296 10297 // Reload IP 10298 if (PVT == MVT::i64) { 10299 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10300 .addImm(LabelOffset) 10301 .addReg(BufReg); 10302 } else { 10303 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10304 .addImm(LabelOffset) 10305 .addReg(BufReg); 10306 } 10307 MIB.cloneMemRefs(MI); 10308 10309 // Reload SP 10310 if (PVT == MVT::i64) { 10311 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10312 .addImm(SPOffset) 10313 .addReg(BufReg); 10314 } else { 10315 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10316 .addImm(SPOffset) 10317 .addReg(BufReg); 10318 } 10319 MIB.cloneMemRefs(MI); 10320 10321 // Reload BP 10322 if (PVT == MVT::i64) { 10323 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10324 .addImm(BPOffset) 10325 .addReg(BufReg); 10326 } else { 10327 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10328 .addImm(BPOffset) 10329 .addReg(BufReg); 10330 } 10331 MIB.cloneMemRefs(MI); 10332 10333 // Reload TOC 10334 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10335 setUsesTOCBasePtr(*MBB->getParent()); 10336 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10337 .addImm(TOCOffset) 10338 .addReg(BufReg) 10339 .cloneMemRefs(MI); 10340 } 10341 10342 // Jump 10343 BuildMI(*MBB, MI, DL, 10344 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10345 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10346 10347 MI.eraseFromParent(); 10348 return MBB; 10349 } 10350 10351 MachineBasicBlock * 10352 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10353 MachineBasicBlock *BB) const { 10354 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10355 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10356 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10357 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10358 // Call lowering should have added an r2 operand to indicate a dependence 10359 // on the TOC base pointer value. It can't however, because there is no 10360 // way to mark the dependence as implicit there, and so the stackmap code 10361 // will confuse it with a regular operand. Instead, add the dependence 10362 // here. 10363 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10364 } 10365 10366 return emitPatchPoint(MI, BB); 10367 } 10368 10369 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10370 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10371 return emitEHSjLjSetJmp(MI, BB); 10372 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10373 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10374 return emitEHSjLjLongJmp(MI, BB); 10375 } 10376 10377 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10378 10379 // To "insert" these instructions we actually have to insert their 10380 // control-flow patterns. 10381 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10382 MachineFunction::iterator It = ++BB->getIterator(); 10383 10384 MachineFunction *F = BB->getParent(); 10385 10386 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10387 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10388 MI.getOpcode() == PPC::SELECT_I8) { 10389 SmallVector<MachineOperand, 2> Cond; 10390 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10391 MI.getOpcode() == PPC::SELECT_CC_I8) 10392 Cond.push_back(MI.getOperand(4)); 10393 else 10394 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10395 Cond.push_back(MI.getOperand(1)); 10396 10397 DebugLoc dl = MI.getDebugLoc(); 10398 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10399 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10400 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10401 MI.getOpcode() == PPC::SELECT_CC_I8 || 10402 MI.getOpcode() == PPC::SELECT_CC_F4 || 10403 MI.getOpcode() == PPC::SELECT_CC_F8 || 10404 MI.getOpcode() == PPC::SELECT_CC_F16 || 10405 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10406 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10407 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10408 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10409 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10410 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10411 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10412 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10413 MI.getOpcode() == PPC::SELECT_CC_SPE || 10414 MI.getOpcode() == PPC::SELECT_I4 || 10415 MI.getOpcode() == PPC::SELECT_I8 || 10416 MI.getOpcode() == PPC::SELECT_F4 || 10417 MI.getOpcode() == PPC::SELECT_F8 || 10418 MI.getOpcode() == PPC::SELECT_F16 || 10419 MI.getOpcode() == PPC::SELECT_QFRC || 10420 MI.getOpcode() == PPC::SELECT_QSRC || 10421 MI.getOpcode() == PPC::SELECT_QBRC || 10422 MI.getOpcode() == PPC::SELECT_SPE || 10423 MI.getOpcode() == PPC::SELECT_SPE4 || 10424 MI.getOpcode() == PPC::SELECT_VRRC || 10425 MI.getOpcode() == PPC::SELECT_VSFRC || 10426 MI.getOpcode() == PPC::SELECT_VSSRC || 10427 MI.getOpcode() == PPC::SELECT_VSRC) { 10428 // The incoming instruction knows the destination vreg to set, the 10429 // condition code register to branch on, the true/false values to 10430 // select between, and a branch opcode to use. 10431 10432 // thisMBB: 10433 // ... 10434 // TrueVal = ... 10435 // cmpTY ccX, r1, r2 10436 // bCC copy1MBB 10437 // fallthrough --> copy0MBB 10438 MachineBasicBlock *thisMBB = BB; 10439 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10440 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10441 DebugLoc dl = MI.getDebugLoc(); 10442 F->insert(It, copy0MBB); 10443 F->insert(It, sinkMBB); 10444 10445 // Transfer the remainder of BB and its successor edges to sinkMBB. 10446 sinkMBB->splice(sinkMBB->begin(), BB, 10447 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10448 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10449 10450 // Next, add the true and fallthrough blocks as its successors. 10451 BB->addSuccessor(copy0MBB); 10452 BB->addSuccessor(sinkMBB); 10453 10454 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10455 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10456 MI.getOpcode() == PPC::SELECT_F16 || 10457 MI.getOpcode() == PPC::SELECT_SPE4 || 10458 MI.getOpcode() == PPC::SELECT_SPE || 10459 MI.getOpcode() == PPC::SELECT_QFRC || 10460 MI.getOpcode() == PPC::SELECT_QSRC || 10461 MI.getOpcode() == PPC::SELECT_QBRC || 10462 MI.getOpcode() == PPC::SELECT_VRRC || 10463 MI.getOpcode() == PPC::SELECT_VSFRC || 10464 MI.getOpcode() == PPC::SELECT_VSSRC || 10465 MI.getOpcode() == PPC::SELECT_VSRC) { 10466 BuildMI(BB, dl, TII->get(PPC::BC)) 10467 .addReg(MI.getOperand(1).getReg()) 10468 .addMBB(sinkMBB); 10469 } else { 10470 unsigned SelectPred = MI.getOperand(4).getImm(); 10471 BuildMI(BB, dl, TII->get(PPC::BCC)) 10472 .addImm(SelectPred) 10473 .addReg(MI.getOperand(1).getReg()) 10474 .addMBB(sinkMBB); 10475 } 10476 10477 // copy0MBB: 10478 // %FalseValue = ... 10479 // # fallthrough to sinkMBB 10480 BB = copy0MBB; 10481 10482 // Update machine-CFG edges 10483 BB->addSuccessor(sinkMBB); 10484 10485 // sinkMBB: 10486 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10487 // ... 10488 BB = sinkMBB; 10489 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10490 .addReg(MI.getOperand(3).getReg()) 10491 .addMBB(copy0MBB) 10492 .addReg(MI.getOperand(2).getReg()) 10493 .addMBB(thisMBB); 10494 } else if (MI.getOpcode() == PPC::ReadTB) { 10495 // To read the 64-bit time-base register on a 32-bit target, we read the 10496 // two halves. Should the counter have wrapped while it was being read, we 10497 // need to try again. 10498 // ... 10499 // readLoop: 10500 // mfspr Rx,TBU # load from TBU 10501 // mfspr Ry,TB # load from TB 10502 // mfspr Rz,TBU # load from TBU 10503 // cmpw crX,Rx,Rz # check if 'old'='new' 10504 // bne readLoop # branch if they're not equal 10505 // ... 10506 10507 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10508 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10509 DebugLoc dl = MI.getDebugLoc(); 10510 F->insert(It, readMBB); 10511 F->insert(It, sinkMBB); 10512 10513 // Transfer the remainder of BB and its successor edges to sinkMBB. 10514 sinkMBB->splice(sinkMBB->begin(), BB, 10515 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10516 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10517 10518 BB->addSuccessor(readMBB); 10519 BB = readMBB; 10520 10521 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10522 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10523 unsigned LoReg = MI.getOperand(0).getReg(); 10524 unsigned HiReg = MI.getOperand(1).getReg(); 10525 10526 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10527 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10528 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10529 10530 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10531 10532 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10533 .addReg(HiReg) 10534 .addReg(ReadAgainReg); 10535 BuildMI(BB, dl, TII->get(PPC::BCC)) 10536 .addImm(PPC::PRED_NE) 10537 .addReg(CmpReg) 10538 .addMBB(readMBB); 10539 10540 BB->addSuccessor(readMBB); 10541 BB->addSuccessor(sinkMBB); 10542 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10543 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10544 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10545 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10547 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10548 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10549 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10550 10551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10552 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10553 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10554 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10556 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10557 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10558 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10559 10560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10561 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10562 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10563 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10564 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10565 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10566 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10567 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10568 10569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10570 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10571 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10572 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10573 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10574 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10575 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10576 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10577 10578 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10579 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10580 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10581 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10582 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10583 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10584 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10585 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10586 10587 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10588 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10589 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10590 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10591 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10592 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10593 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10594 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10595 10596 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10597 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10598 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10599 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10600 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10601 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10602 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10603 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10604 10605 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10606 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10607 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10608 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10609 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10610 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10611 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10612 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10613 10614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10615 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10616 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10617 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10618 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10619 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10620 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10621 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10622 10623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10624 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10625 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10626 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10627 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10628 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10629 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10630 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10631 10632 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10633 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10634 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10635 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10636 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10637 BB = EmitAtomicBinary(MI, BB, 4, 0); 10638 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10639 BB = EmitAtomicBinary(MI, BB, 8, 0); 10640 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10641 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10642 (Subtarget.hasPartwordAtomics() && 10643 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10644 (Subtarget.hasPartwordAtomics() && 10645 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10646 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10647 10648 auto LoadMnemonic = PPC::LDARX; 10649 auto StoreMnemonic = PPC::STDCX; 10650 switch (MI.getOpcode()) { 10651 default: 10652 llvm_unreachable("Compare and swap of unknown size"); 10653 case PPC::ATOMIC_CMP_SWAP_I8: 10654 LoadMnemonic = PPC::LBARX; 10655 StoreMnemonic = PPC::STBCX; 10656 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10657 break; 10658 case PPC::ATOMIC_CMP_SWAP_I16: 10659 LoadMnemonic = PPC::LHARX; 10660 StoreMnemonic = PPC::STHCX; 10661 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10662 break; 10663 case PPC::ATOMIC_CMP_SWAP_I32: 10664 LoadMnemonic = PPC::LWARX; 10665 StoreMnemonic = PPC::STWCX; 10666 break; 10667 case PPC::ATOMIC_CMP_SWAP_I64: 10668 LoadMnemonic = PPC::LDARX; 10669 StoreMnemonic = PPC::STDCX; 10670 break; 10671 } 10672 unsigned dest = MI.getOperand(0).getReg(); 10673 unsigned ptrA = MI.getOperand(1).getReg(); 10674 unsigned ptrB = MI.getOperand(2).getReg(); 10675 unsigned oldval = MI.getOperand(3).getReg(); 10676 unsigned newval = MI.getOperand(4).getReg(); 10677 DebugLoc dl = MI.getDebugLoc(); 10678 10679 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10680 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10681 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10682 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10683 F->insert(It, loop1MBB); 10684 F->insert(It, loop2MBB); 10685 F->insert(It, midMBB); 10686 F->insert(It, exitMBB); 10687 exitMBB->splice(exitMBB->begin(), BB, 10688 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10689 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10690 10691 // thisMBB: 10692 // ... 10693 // fallthrough --> loopMBB 10694 BB->addSuccessor(loop1MBB); 10695 10696 // loop1MBB: 10697 // l[bhwd]arx dest, ptr 10698 // cmp[wd] dest, oldval 10699 // bne- midMBB 10700 // loop2MBB: 10701 // st[bhwd]cx. newval, ptr 10702 // bne- loopMBB 10703 // b exitBB 10704 // midMBB: 10705 // st[bhwd]cx. dest, ptr 10706 // exitBB: 10707 BB = loop1MBB; 10708 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10709 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10710 .addReg(oldval) 10711 .addReg(dest); 10712 BuildMI(BB, dl, TII->get(PPC::BCC)) 10713 .addImm(PPC::PRED_NE) 10714 .addReg(PPC::CR0) 10715 .addMBB(midMBB); 10716 BB->addSuccessor(loop2MBB); 10717 BB->addSuccessor(midMBB); 10718 10719 BB = loop2MBB; 10720 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10721 .addReg(newval) 10722 .addReg(ptrA) 10723 .addReg(ptrB); 10724 BuildMI(BB, dl, TII->get(PPC::BCC)) 10725 .addImm(PPC::PRED_NE) 10726 .addReg(PPC::CR0) 10727 .addMBB(loop1MBB); 10728 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10729 BB->addSuccessor(loop1MBB); 10730 BB->addSuccessor(exitMBB); 10731 10732 BB = midMBB; 10733 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10734 .addReg(dest) 10735 .addReg(ptrA) 10736 .addReg(ptrB); 10737 BB->addSuccessor(exitMBB); 10738 10739 // exitMBB: 10740 // ... 10741 BB = exitMBB; 10742 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10743 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10744 // We must use 64-bit registers for addresses when targeting 64-bit, 10745 // since we're actually doing arithmetic on them. Other registers 10746 // can be 32-bit. 10747 bool is64bit = Subtarget.isPPC64(); 10748 bool isLittleEndian = Subtarget.isLittleEndian(); 10749 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10750 10751 unsigned dest = MI.getOperand(0).getReg(); 10752 unsigned ptrA = MI.getOperand(1).getReg(); 10753 unsigned ptrB = MI.getOperand(2).getReg(); 10754 unsigned oldval = MI.getOperand(3).getReg(); 10755 unsigned newval = MI.getOperand(4).getReg(); 10756 DebugLoc dl = MI.getDebugLoc(); 10757 10758 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10759 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10760 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10761 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10762 F->insert(It, loop1MBB); 10763 F->insert(It, loop2MBB); 10764 F->insert(It, midMBB); 10765 F->insert(It, exitMBB); 10766 exitMBB->splice(exitMBB->begin(), BB, 10767 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10768 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10769 10770 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10771 const TargetRegisterClass *RC = 10772 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10773 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10774 10775 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10776 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10777 unsigned ShiftReg = 10778 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10779 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 10780 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 10781 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 10782 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 10783 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10784 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10785 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10786 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10787 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10788 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10789 unsigned Ptr1Reg; 10790 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC); 10791 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10792 // thisMBB: 10793 // ... 10794 // fallthrough --> loopMBB 10795 BB->addSuccessor(loop1MBB); 10796 10797 // The 4-byte load must be aligned, while a char or short may be 10798 // anywhere in the word. Hence all this nasty bookkeeping code. 10799 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10800 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10801 // xori shift, shift1, 24 [16] 10802 // rlwinm ptr, ptr1, 0, 0, 29 10803 // slw newval2, newval, shift 10804 // slw oldval2, oldval,shift 10805 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10806 // slw mask, mask2, shift 10807 // and newval3, newval2, mask 10808 // and oldval3, oldval2, mask 10809 // loop1MBB: 10810 // lwarx tmpDest, ptr 10811 // and tmp, tmpDest, mask 10812 // cmpw tmp, oldval3 10813 // bne- midMBB 10814 // loop2MBB: 10815 // andc tmp2, tmpDest, mask 10816 // or tmp4, tmp2, newval3 10817 // stwcx. tmp4, ptr 10818 // bne- loop1MBB 10819 // b exitBB 10820 // midMBB: 10821 // stwcx. tmpDest, ptr 10822 // exitBB: 10823 // srw dest, tmpDest, shift 10824 if (ptrA != ZeroReg) { 10825 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10826 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10827 .addReg(ptrA) 10828 .addReg(ptrB); 10829 } else { 10830 Ptr1Reg = ptrB; 10831 } 10832 10833 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10834 // mode. 10835 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10836 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10837 .addImm(3) 10838 .addImm(27) 10839 .addImm(is8bit ? 28 : 27); 10840 if (!isLittleEndian) 10841 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10842 .addReg(Shift1Reg) 10843 .addImm(is8bit ? 24 : 16); 10844 if (is64bit) 10845 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10846 .addReg(Ptr1Reg) 10847 .addImm(0) 10848 .addImm(61); 10849 else 10850 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10851 .addReg(Ptr1Reg) 10852 .addImm(0) 10853 .addImm(0) 10854 .addImm(29); 10855 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10856 .addReg(newval) 10857 .addReg(ShiftReg); 10858 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10859 .addReg(oldval) 10860 .addReg(ShiftReg); 10861 if (is8bit) 10862 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10863 else { 10864 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10865 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10866 .addReg(Mask3Reg) 10867 .addImm(65535); 10868 } 10869 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10870 .addReg(Mask2Reg) 10871 .addReg(ShiftReg); 10872 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10873 .addReg(NewVal2Reg) 10874 .addReg(MaskReg); 10875 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10876 .addReg(OldVal2Reg) 10877 .addReg(MaskReg); 10878 10879 BB = loop1MBB; 10880 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10881 .addReg(ZeroReg) 10882 .addReg(PtrReg); 10883 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 10884 .addReg(TmpDestReg) 10885 .addReg(MaskReg); 10886 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10887 .addReg(TmpReg) 10888 .addReg(OldVal3Reg); 10889 BuildMI(BB, dl, TII->get(PPC::BCC)) 10890 .addImm(PPC::PRED_NE) 10891 .addReg(PPC::CR0) 10892 .addMBB(midMBB); 10893 BB->addSuccessor(loop2MBB); 10894 BB->addSuccessor(midMBB); 10895 10896 BB = loop2MBB; 10897 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10898 .addReg(TmpDestReg) 10899 .addReg(MaskReg); 10900 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 10901 .addReg(Tmp2Reg) 10902 .addReg(NewVal3Reg); 10903 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10904 .addReg(Tmp4Reg) 10905 .addReg(ZeroReg) 10906 .addReg(PtrReg); 10907 BuildMI(BB, dl, TII->get(PPC::BCC)) 10908 .addImm(PPC::PRED_NE) 10909 .addReg(PPC::CR0) 10910 .addMBB(loop1MBB); 10911 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10912 BB->addSuccessor(loop1MBB); 10913 BB->addSuccessor(exitMBB); 10914 10915 BB = midMBB; 10916 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10917 .addReg(TmpDestReg) 10918 .addReg(ZeroReg) 10919 .addReg(PtrReg); 10920 BB->addSuccessor(exitMBB); 10921 10922 // exitMBB: 10923 // ... 10924 BB = exitMBB; 10925 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10926 .addReg(TmpReg) 10927 .addReg(ShiftReg); 10928 } else if (MI.getOpcode() == PPC::FADDrtz) { 10929 // This pseudo performs an FADD with rounding mode temporarily forced 10930 // to round-to-zero. We emit this via custom inserter since the FPSCR 10931 // is not modeled at the SelectionDAG level. 10932 unsigned Dest = MI.getOperand(0).getReg(); 10933 unsigned Src1 = MI.getOperand(1).getReg(); 10934 unsigned Src2 = MI.getOperand(2).getReg(); 10935 DebugLoc dl = MI.getDebugLoc(); 10936 10937 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10938 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10939 10940 // Save FPSCR value. 10941 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10942 10943 // Set rounding mode to round-to-zero. 10944 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10945 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10946 10947 // Perform addition. 10948 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10949 10950 // Restore FPSCR value. 10951 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10952 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10953 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10954 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10955 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10956 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10957 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10958 ? PPC::ANDIo8 10959 : PPC::ANDIo; 10960 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10961 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10962 10963 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10964 unsigned Dest = RegInfo.createVirtualRegister( 10965 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 10966 10967 DebugLoc dl = MI.getDebugLoc(); 10968 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10969 .addReg(MI.getOperand(1).getReg()) 10970 .addImm(1); 10971 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10972 MI.getOperand(0).getReg()) 10973 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10974 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10975 DebugLoc Dl = MI.getDebugLoc(); 10976 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10977 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10978 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10979 return BB; 10980 } else if (MI.getOpcode() == PPC::SETRNDi) { 10981 DebugLoc dl = MI.getDebugLoc(); 10982 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 10983 10984 // Save FPSCR value. 10985 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 10986 10987 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 10988 // the following settings: 10989 // 00 Round to nearest 10990 // 01 Round to 0 10991 // 10 Round to +inf 10992 // 11 Round to -inf 10993 10994 // When the operand is immediate, using the two least significant bits of 10995 // the immediate to set the bits 62:63 of FPSCR. 10996 unsigned Mode = MI.getOperand(1).getImm(); 10997 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 10998 .addImm(31); 10999 11000 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11001 .addImm(30); 11002 } else if (MI.getOpcode() == PPC::SETRND) { 11003 DebugLoc dl = MI.getDebugLoc(); 11004 11005 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11006 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11007 // If the target doesn't have DirectMove, we should use stack to do the 11008 // conversion, because the target doesn't have the instructions like mtvsrd 11009 // or mfvsrd to do this conversion directly. 11010 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11011 if (Subtarget.hasDirectMove()) { 11012 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11013 .addReg(SrcReg); 11014 } else { 11015 // Use stack to do the register copy. 11016 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11017 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11018 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11019 if (RC == &PPC::F8RCRegClass) { 11020 // Copy register from F8RCRegClass to G8RCRegclass. 11021 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11022 "Unsupported RegClass."); 11023 11024 StoreOp = PPC::STFD; 11025 LoadOp = PPC::LD; 11026 } else { 11027 // Copy register from G8RCRegClass to F8RCRegclass. 11028 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11029 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11030 "Unsupported RegClass."); 11031 } 11032 11033 MachineFrameInfo &MFI = F->getFrameInfo(); 11034 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11035 11036 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11037 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11038 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11039 MFI.getObjectAlignment(FrameIdx)); 11040 11041 // Store the SrcReg into the stack. 11042 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11043 .addReg(SrcReg) 11044 .addImm(0) 11045 .addFrameIndex(FrameIdx) 11046 .addMemOperand(MMOStore); 11047 11048 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11049 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11050 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11051 MFI.getObjectAlignment(FrameIdx)); 11052 11053 // Load from the stack where SrcReg is stored, and save to DestReg, 11054 // so we have done the RegClass conversion from RegClass::SrcReg to 11055 // RegClass::DestReg. 11056 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11057 .addImm(0) 11058 .addFrameIndex(FrameIdx) 11059 .addMemOperand(MMOLoad); 11060 } 11061 }; 11062 11063 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11064 11065 // Save FPSCR value. 11066 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11067 11068 // When the operand is gprc register, use two least significant bits of the 11069 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11070 // 11071 // copy OldFPSCRTmpReg, OldFPSCRReg 11072 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11073 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11074 // copy NewFPSCRReg, NewFPSCRTmpReg 11075 // mtfsf 255, NewFPSCRReg 11076 MachineOperand SrcOp = MI.getOperand(1); 11077 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11078 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11079 11080 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11081 11082 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11083 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11084 11085 // The first operand of INSERT_SUBREG should be a register which has 11086 // subregisters, we only care about its RegClass, so we should use an 11087 // IMPLICIT_DEF register. 11088 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11089 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11090 .addReg(ImDefReg) 11091 .add(SrcOp) 11092 .addImm(1); 11093 11094 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11095 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11096 .addReg(OldFPSCRTmpReg) 11097 .addReg(ExtSrcReg) 11098 .addImm(0) 11099 .addImm(62); 11100 11101 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11102 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11103 11104 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11105 // bits of FPSCR. 11106 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11107 .addImm(255) 11108 .addReg(NewFPSCRReg) 11109 .addImm(0) 11110 .addImm(0); 11111 } else { 11112 llvm_unreachable("Unexpected instr type to insert"); 11113 } 11114 11115 MI.eraseFromParent(); // The pseudo instruction is gone now. 11116 return BB; 11117 } 11118 11119 //===----------------------------------------------------------------------===// 11120 // Target Optimization Hooks 11121 //===----------------------------------------------------------------------===// 11122 11123 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11124 // For the estimates, convergence is quadratic, so we essentially double the 11125 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11126 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11127 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11128 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11129 if (VT.getScalarType() == MVT::f64) 11130 RefinementSteps++; 11131 return RefinementSteps; 11132 } 11133 11134 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11135 int Enabled, int &RefinementSteps, 11136 bool &UseOneConstNR, 11137 bool Reciprocal) const { 11138 EVT VT = Operand.getValueType(); 11139 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11140 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11141 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11142 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11143 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11144 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11145 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11146 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11147 11148 // The Newton-Raphson computation with a single constant does not provide 11149 // enough accuracy on some CPUs. 11150 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11151 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11152 } 11153 return SDValue(); 11154 } 11155 11156 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11157 int Enabled, 11158 int &RefinementSteps) const { 11159 EVT VT = Operand.getValueType(); 11160 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11161 (VT == MVT::f64 && Subtarget.hasFRE()) || 11162 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11163 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11164 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11165 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11166 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11167 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11168 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11169 } 11170 return SDValue(); 11171 } 11172 11173 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11174 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11175 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11176 // enabled for division), this functionality is redundant with the default 11177 // combiner logic (once the division -> reciprocal/multiply transformation 11178 // has taken place). As a result, this matters more for older cores than for 11179 // newer ones. 11180 11181 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11182 // reciprocal if there are two or more FDIVs (for embedded cores with only 11183 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11184 switch (Subtarget.getDarwinDirective()) { 11185 default: 11186 return 3; 11187 case PPC::DIR_440: 11188 case PPC::DIR_A2: 11189 case PPC::DIR_E500: 11190 case PPC::DIR_E500mc: 11191 case PPC::DIR_E5500: 11192 return 2; 11193 } 11194 } 11195 11196 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11197 // collapsed, and so we need to look through chains of them. 11198 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11199 int64_t& Offset, SelectionDAG &DAG) { 11200 if (DAG.isBaseWithConstantOffset(Loc)) { 11201 Base = Loc.getOperand(0); 11202 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11203 11204 // The base might itself be a base plus an offset, and if so, accumulate 11205 // that as well. 11206 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11207 } 11208 } 11209 11210 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11211 unsigned Bytes, int Dist, 11212 SelectionDAG &DAG) { 11213 if (VT.getSizeInBits() / 8 != Bytes) 11214 return false; 11215 11216 SDValue BaseLoc = Base->getBasePtr(); 11217 if (Loc.getOpcode() == ISD::FrameIndex) { 11218 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11219 return false; 11220 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11221 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11222 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11223 int FS = MFI.getObjectSize(FI); 11224 int BFS = MFI.getObjectSize(BFI); 11225 if (FS != BFS || FS != (int)Bytes) return false; 11226 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11227 } 11228 11229 SDValue Base1 = Loc, Base2 = BaseLoc; 11230 int64_t Offset1 = 0, Offset2 = 0; 11231 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11232 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11233 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11234 return true; 11235 11236 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11237 const GlobalValue *GV1 = nullptr; 11238 const GlobalValue *GV2 = nullptr; 11239 Offset1 = 0; 11240 Offset2 = 0; 11241 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11242 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11243 if (isGA1 && isGA2 && GV1 == GV2) 11244 return Offset1 == (Offset2 + Dist*Bytes); 11245 return false; 11246 } 11247 11248 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11249 // not enforce equality of the chain operands. 11250 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11251 unsigned Bytes, int Dist, 11252 SelectionDAG &DAG) { 11253 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11254 EVT VT = LS->getMemoryVT(); 11255 SDValue Loc = LS->getBasePtr(); 11256 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11257 } 11258 11259 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11260 EVT VT; 11261 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11262 default: return false; 11263 case Intrinsic::ppc_qpx_qvlfd: 11264 case Intrinsic::ppc_qpx_qvlfda: 11265 VT = MVT::v4f64; 11266 break; 11267 case Intrinsic::ppc_qpx_qvlfs: 11268 case Intrinsic::ppc_qpx_qvlfsa: 11269 VT = MVT::v4f32; 11270 break; 11271 case Intrinsic::ppc_qpx_qvlfcd: 11272 case Intrinsic::ppc_qpx_qvlfcda: 11273 VT = MVT::v2f64; 11274 break; 11275 case Intrinsic::ppc_qpx_qvlfcs: 11276 case Intrinsic::ppc_qpx_qvlfcsa: 11277 VT = MVT::v2f32; 11278 break; 11279 case Intrinsic::ppc_qpx_qvlfiwa: 11280 case Intrinsic::ppc_qpx_qvlfiwz: 11281 case Intrinsic::ppc_altivec_lvx: 11282 case Intrinsic::ppc_altivec_lvxl: 11283 case Intrinsic::ppc_vsx_lxvw4x: 11284 case Intrinsic::ppc_vsx_lxvw4x_be: 11285 VT = MVT::v4i32; 11286 break; 11287 case Intrinsic::ppc_vsx_lxvd2x: 11288 case Intrinsic::ppc_vsx_lxvd2x_be: 11289 VT = MVT::v2f64; 11290 break; 11291 case Intrinsic::ppc_altivec_lvebx: 11292 VT = MVT::i8; 11293 break; 11294 case Intrinsic::ppc_altivec_lvehx: 11295 VT = MVT::i16; 11296 break; 11297 case Intrinsic::ppc_altivec_lvewx: 11298 VT = MVT::i32; 11299 break; 11300 } 11301 11302 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11303 } 11304 11305 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11306 EVT VT; 11307 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11308 default: return false; 11309 case Intrinsic::ppc_qpx_qvstfd: 11310 case Intrinsic::ppc_qpx_qvstfda: 11311 VT = MVT::v4f64; 11312 break; 11313 case Intrinsic::ppc_qpx_qvstfs: 11314 case Intrinsic::ppc_qpx_qvstfsa: 11315 VT = MVT::v4f32; 11316 break; 11317 case Intrinsic::ppc_qpx_qvstfcd: 11318 case Intrinsic::ppc_qpx_qvstfcda: 11319 VT = MVT::v2f64; 11320 break; 11321 case Intrinsic::ppc_qpx_qvstfcs: 11322 case Intrinsic::ppc_qpx_qvstfcsa: 11323 VT = MVT::v2f32; 11324 break; 11325 case Intrinsic::ppc_qpx_qvstfiw: 11326 case Intrinsic::ppc_qpx_qvstfiwa: 11327 case Intrinsic::ppc_altivec_stvx: 11328 case Intrinsic::ppc_altivec_stvxl: 11329 case Intrinsic::ppc_vsx_stxvw4x: 11330 VT = MVT::v4i32; 11331 break; 11332 case Intrinsic::ppc_vsx_stxvd2x: 11333 VT = MVT::v2f64; 11334 break; 11335 case Intrinsic::ppc_vsx_stxvw4x_be: 11336 VT = MVT::v4i32; 11337 break; 11338 case Intrinsic::ppc_vsx_stxvd2x_be: 11339 VT = MVT::v2f64; 11340 break; 11341 case Intrinsic::ppc_altivec_stvebx: 11342 VT = MVT::i8; 11343 break; 11344 case Intrinsic::ppc_altivec_stvehx: 11345 VT = MVT::i16; 11346 break; 11347 case Intrinsic::ppc_altivec_stvewx: 11348 VT = MVT::i32; 11349 break; 11350 } 11351 11352 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11353 } 11354 11355 return false; 11356 } 11357 11358 // Return true is there is a nearyby consecutive load to the one provided 11359 // (regardless of alignment). We search up and down the chain, looking though 11360 // token factors and other loads (but nothing else). As a result, a true result 11361 // indicates that it is safe to create a new consecutive load adjacent to the 11362 // load provided. 11363 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11364 SDValue Chain = LD->getChain(); 11365 EVT VT = LD->getMemoryVT(); 11366 11367 SmallSet<SDNode *, 16> LoadRoots; 11368 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11369 SmallSet<SDNode *, 16> Visited; 11370 11371 // First, search up the chain, branching to follow all token-factor operands. 11372 // If we find a consecutive load, then we're done, otherwise, record all 11373 // nodes just above the top-level loads and token factors. 11374 while (!Queue.empty()) { 11375 SDNode *ChainNext = Queue.pop_back_val(); 11376 if (!Visited.insert(ChainNext).second) 11377 continue; 11378 11379 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11380 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11381 return true; 11382 11383 if (!Visited.count(ChainLD->getChain().getNode())) 11384 Queue.push_back(ChainLD->getChain().getNode()); 11385 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11386 for (const SDUse &O : ChainNext->ops()) 11387 if (!Visited.count(O.getNode())) 11388 Queue.push_back(O.getNode()); 11389 } else 11390 LoadRoots.insert(ChainNext); 11391 } 11392 11393 // Second, search down the chain, starting from the top-level nodes recorded 11394 // in the first phase. These top-level nodes are the nodes just above all 11395 // loads and token factors. Starting with their uses, recursively look though 11396 // all loads (just the chain uses) and token factors to find a consecutive 11397 // load. 11398 Visited.clear(); 11399 Queue.clear(); 11400 11401 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11402 IE = LoadRoots.end(); I != IE; ++I) { 11403 Queue.push_back(*I); 11404 11405 while (!Queue.empty()) { 11406 SDNode *LoadRoot = Queue.pop_back_val(); 11407 if (!Visited.insert(LoadRoot).second) 11408 continue; 11409 11410 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11411 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11412 return true; 11413 11414 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11415 UE = LoadRoot->use_end(); UI != UE; ++UI) 11416 if (((isa<MemSDNode>(*UI) && 11417 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11418 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11419 Queue.push_back(*UI); 11420 } 11421 } 11422 11423 return false; 11424 } 11425 11426 /// This function is called when we have proved that a SETCC node can be replaced 11427 /// by subtraction (and other supporting instructions) so that the result of 11428 /// comparison is kept in a GPR instead of CR. This function is purely for 11429 /// codegen purposes and has some flags to guide the codegen process. 11430 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11431 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11432 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11433 11434 // Zero extend the operands to the largest legal integer. Originally, they 11435 // must be of a strictly smaller size. 11436 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11437 DAG.getConstant(Size, DL, MVT::i32)); 11438 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11439 DAG.getConstant(Size, DL, MVT::i32)); 11440 11441 // Swap if needed. Depends on the condition code. 11442 if (Swap) 11443 std::swap(Op0, Op1); 11444 11445 // Subtract extended integers. 11446 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11447 11448 // Move the sign bit to the least significant position and zero out the rest. 11449 // Now the least significant bit carries the result of original comparison. 11450 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11451 DAG.getConstant(Size - 1, DL, MVT::i32)); 11452 auto Final = Shifted; 11453 11454 // Complement the result if needed. Based on the condition code. 11455 if (Complement) 11456 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11457 DAG.getConstant(1, DL, MVT::i64)); 11458 11459 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11460 } 11461 11462 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11463 DAGCombinerInfo &DCI) const { 11464 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11465 11466 SelectionDAG &DAG = DCI.DAG; 11467 SDLoc DL(N); 11468 11469 // Size of integers being compared has a critical role in the following 11470 // analysis, so we prefer to do this when all types are legal. 11471 if (!DCI.isAfterLegalizeDAG()) 11472 return SDValue(); 11473 11474 // If all users of SETCC extend its value to a legal integer type 11475 // then we replace SETCC with a subtraction 11476 for (SDNode::use_iterator UI = N->use_begin(), 11477 UE = N->use_end(); UI != UE; ++UI) { 11478 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11479 return SDValue(); 11480 } 11481 11482 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11483 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11484 11485 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11486 11487 if (OpSize < Size) { 11488 switch (CC) { 11489 default: break; 11490 case ISD::SETULT: 11491 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11492 case ISD::SETULE: 11493 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11494 case ISD::SETUGT: 11495 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11496 case ISD::SETUGE: 11497 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11498 } 11499 } 11500 11501 return SDValue(); 11502 } 11503 11504 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11505 DAGCombinerInfo &DCI) const { 11506 SelectionDAG &DAG = DCI.DAG; 11507 SDLoc dl(N); 11508 11509 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11510 // If we're tracking CR bits, we need to be careful that we don't have: 11511 // trunc(binary-ops(zext(x), zext(y))) 11512 // or 11513 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11514 // such that we're unnecessarily moving things into GPRs when it would be 11515 // better to keep them in CR bits. 11516 11517 // Note that trunc here can be an actual i1 trunc, or can be the effective 11518 // truncation that comes from a setcc or select_cc. 11519 if (N->getOpcode() == ISD::TRUNCATE && 11520 N->getValueType(0) != MVT::i1) 11521 return SDValue(); 11522 11523 if (N->getOperand(0).getValueType() != MVT::i32 && 11524 N->getOperand(0).getValueType() != MVT::i64) 11525 return SDValue(); 11526 11527 if (N->getOpcode() == ISD::SETCC || 11528 N->getOpcode() == ISD::SELECT_CC) { 11529 // If we're looking at a comparison, then we need to make sure that the 11530 // high bits (all except for the first) don't matter the result. 11531 ISD::CondCode CC = 11532 cast<CondCodeSDNode>(N->getOperand( 11533 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11534 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11535 11536 if (ISD::isSignedIntSetCC(CC)) { 11537 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11538 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11539 return SDValue(); 11540 } else if (ISD::isUnsignedIntSetCC(CC)) { 11541 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11542 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11543 !DAG.MaskedValueIsZero(N->getOperand(1), 11544 APInt::getHighBitsSet(OpBits, OpBits-1))) 11545 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11546 : SDValue()); 11547 } else { 11548 // This is neither a signed nor an unsigned comparison, just make sure 11549 // that the high bits are equal. 11550 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11551 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11552 11553 // We don't really care about what is known about the first bit (if 11554 // anything), so clear it in all masks prior to comparing them. 11555 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11556 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11557 11558 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11559 return SDValue(); 11560 } 11561 } 11562 11563 // We now know that the higher-order bits are irrelevant, we just need to 11564 // make sure that all of the intermediate operations are bit operations, and 11565 // all inputs are extensions. 11566 if (N->getOperand(0).getOpcode() != ISD::AND && 11567 N->getOperand(0).getOpcode() != ISD::OR && 11568 N->getOperand(0).getOpcode() != ISD::XOR && 11569 N->getOperand(0).getOpcode() != ISD::SELECT && 11570 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11571 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11572 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11573 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11574 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11575 return SDValue(); 11576 11577 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11578 N->getOperand(1).getOpcode() != ISD::AND && 11579 N->getOperand(1).getOpcode() != ISD::OR && 11580 N->getOperand(1).getOpcode() != ISD::XOR && 11581 N->getOperand(1).getOpcode() != ISD::SELECT && 11582 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11583 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11584 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11585 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11586 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11587 return SDValue(); 11588 11589 SmallVector<SDValue, 4> Inputs; 11590 SmallVector<SDValue, 8> BinOps, PromOps; 11591 SmallPtrSet<SDNode *, 16> Visited; 11592 11593 for (unsigned i = 0; i < 2; ++i) { 11594 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11595 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11596 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11597 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11598 isa<ConstantSDNode>(N->getOperand(i))) 11599 Inputs.push_back(N->getOperand(i)); 11600 else 11601 BinOps.push_back(N->getOperand(i)); 11602 11603 if (N->getOpcode() == ISD::TRUNCATE) 11604 break; 11605 } 11606 11607 // Visit all inputs, collect all binary operations (and, or, xor and 11608 // select) that are all fed by extensions. 11609 while (!BinOps.empty()) { 11610 SDValue BinOp = BinOps.back(); 11611 BinOps.pop_back(); 11612 11613 if (!Visited.insert(BinOp.getNode()).second) 11614 continue; 11615 11616 PromOps.push_back(BinOp); 11617 11618 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11619 // The condition of the select is not promoted. 11620 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11621 continue; 11622 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11623 continue; 11624 11625 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11626 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11627 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11628 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11629 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11630 Inputs.push_back(BinOp.getOperand(i)); 11631 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11632 BinOp.getOperand(i).getOpcode() == ISD::OR || 11633 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11634 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11635 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11636 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11637 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11638 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11639 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11640 BinOps.push_back(BinOp.getOperand(i)); 11641 } else { 11642 // We have an input that is not an extension or another binary 11643 // operation; we'll abort this transformation. 11644 return SDValue(); 11645 } 11646 } 11647 } 11648 11649 // Make sure that this is a self-contained cluster of operations (which 11650 // is not quite the same thing as saying that everything has only one 11651 // use). 11652 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11653 if (isa<ConstantSDNode>(Inputs[i])) 11654 continue; 11655 11656 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11657 UE = Inputs[i].getNode()->use_end(); 11658 UI != UE; ++UI) { 11659 SDNode *User = *UI; 11660 if (User != N && !Visited.count(User)) 11661 return SDValue(); 11662 11663 // Make sure that we're not going to promote the non-output-value 11664 // operand(s) or SELECT or SELECT_CC. 11665 // FIXME: Although we could sometimes handle this, and it does occur in 11666 // practice that one of the condition inputs to the select is also one of 11667 // the outputs, we currently can't deal with this. 11668 if (User->getOpcode() == ISD::SELECT) { 11669 if (User->getOperand(0) == Inputs[i]) 11670 return SDValue(); 11671 } else if (User->getOpcode() == ISD::SELECT_CC) { 11672 if (User->getOperand(0) == Inputs[i] || 11673 User->getOperand(1) == Inputs[i]) 11674 return SDValue(); 11675 } 11676 } 11677 } 11678 11679 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11680 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11681 UE = PromOps[i].getNode()->use_end(); 11682 UI != UE; ++UI) { 11683 SDNode *User = *UI; 11684 if (User != N && !Visited.count(User)) 11685 return SDValue(); 11686 11687 // Make sure that we're not going to promote the non-output-value 11688 // operand(s) or SELECT or SELECT_CC. 11689 // FIXME: Although we could sometimes handle this, and it does occur in 11690 // practice that one of the condition inputs to the select is also one of 11691 // the outputs, we currently can't deal with this. 11692 if (User->getOpcode() == ISD::SELECT) { 11693 if (User->getOperand(0) == PromOps[i]) 11694 return SDValue(); 11695 } else if (User->getOpcode() == ISD::SELECT_CC) { 11696 if (User->getOperand(0) == PromOps[i] || 11697 User->getOperand(1) == PromOps[i]) 11698 return SDValue(); 11699 } 11700 } 11701 } 11702 11703 // Replace all inputs with the extension operand. 11704 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11705 // Constants may have users outside the cluster of to-be-promoted nodes, 11706 // and so we need to replace those as we do the promotions. 11707 if (isa<ConstantSDNode>(Inputs[i])) 11708 continue; 11709 else 11710 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11711 } 11712 11713 std::list<HandleSDNode> PromOpHandles; 11714 for (auto &PromOp : PromOps) 11715 PromOpHandles.emplace_back(PromOp); 11716 11717 // Replace all operations (these are all the same, but have a different 11718 // (i1) return type). DAG.getNode will validate that the types of 11719 // a binary operator match, so go through the list in reverse so that 11720 // we've likely promoted both operands first. Any intermediate truncations or 11721 // extensions disappear. 11722 while (!PromOpHandles.empty()) { 11723 SDValue PromOp = PromOpHandles.back().getValue(); 11724 PromOpHandles.pop_back(); 11725 11726 if (PromOp.getOpcode() == ISD::TRUNCATE || 11727 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11728 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11729 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11730 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11731 PromOp.getOperand(0).getValueType() != MVT::i1) { 11732 // The operand is not yet ready (see comment below). 11733 PromOpHandles.emplace_front(PromOp); 11734 continue; 11735 } 11736 11737 SDValue RepValue = PromOp.getOperand(0); 11738 if (isa<ConstantSDNode>(RepValue)) 11739 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11740 11741 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11742 continue; 11743 } 11744 11745 unsigned C; 11746 switch (PromOp.getOpcode()) { 11747 default: C = 0; break; 11748 case ISD::SELECT: C = 1; break; 11749 case ISD::SELECT_CC: C = 2; break; 11750 } 11751 11752 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11753 PromOp.getOperand(C).getValueType() != MVT::i1) || 11754 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11755 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11756 // The to-be-promoted operands of this node have not yet been 11757 // promoted (this should be rare because we're going through the 11758 // list backward, but if one of the operands has several users in 11759 // this cluster of to-be-promoted nodes, it is possible). 11760 PromOpHandles.emplace_front(PromOp); 11761 continue; 11762 } 11763 11764 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11765 PromOp.getNode()->op_end()); 11766 11767 // If there are any constant inputs, make sure they're replaced now. 11768 for (unsigned i = 0; i < 2; ++i) 11769 if (isa<ConstantSDNode>(Ops[C+i])) 11770 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11771 11772 DAG.ReplaceAllUsesOfValueWith(PromOp, 11773 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11774 } 11775 11776 // Now we're left with the initial truncation itself. 11777 if (N->getOpcode() == ISD::TRUNCATE) 11778 return N->getOperand(0); 11779 11780 // Otherwise, this is a comparison. The operands to be compared have just 11781 // changed type (to i1), but everything else is the same. 11782 return SDValue(N, 0); 11783 } 11784 11785 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11786 DAGCombinerInfo &DCI) const { 11787 SelectionDAG &DAG = DCI.DAG; 11788 SDLoc dl(N); 11789 11790 // If we're tracking CR bits, we need to be careful that we don't have: 11791 // zext(binary-ops(trunc(x), trunc(y))) 11792 // or 11793 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11794 // such that we're unnecessarily moving things into CR bits that can more 11795 // efficiently stay in GPRs. Note that if we're not certain that the high 11796 // bits are set as required by the final extension, we still may need to do 11797 // some masking to get the proper behavior. 11798 11799 // This same functionality is important on PPC64 when dealing with 11800 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11801 // the return values of functions. Because it is so similar, it is handled 11802 // here as well. 11803 11804 if (N->getValueType(0) != MVT::i32 && 11805 N->getValueType(0) != MVT::i64) 11806 return SDValue(); 11807 11808 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11809 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11810 return SDValue(); 11811 11812 if (N->getOperand(0).getOpcode() != ISD::AND && 11813 N->getOperand(0).getOpcode() != ISD::OR && 11814 N->getOperand(0).getOpcode() != ISD::XOR && 11815 N->getOperand(0).getOpcode() != ISD::SELECT && 11816 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11817 return SDValue(); 11818 11819 SmallVector<SDValue, 4> Inputs; 11820 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11821 SmallPtrSet<SDNode *, 16> Visited; 11822 11823 // Visit all inputs, collect all binary operations (and, or, xor and 11824 // select) that are all fed by truncations. 11825 while (!BinOps.empty()) { 11826 SDValue BinOp = BinOps.back(); 11827 BinOps.pop_back(); 11828 11829 if (!Visited.insert(BinOp.getNode()).second) 11830 continue; 11831 11832 PromOps.push_back(BinOp); 11833 11834 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11835 // The condition of the select is not promoted. 11836 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11837 continue; 11838 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11839 continue; 11840 11841 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11842 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11843 Inputs.push_back(BinOp.getOperand(i)); 11844 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11845 BinOp.getOperand(i).getOpcode() == ISD::OR || 11846 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11847 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11848 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11849 BinOps.push_back(BinOp.getOperand(i)); 11850 } else { 11851 // We have an input that is not a truncation or another binary 11852 // operation; we'll abort this transformation. 11853 return SDValue(); 11854 } 11855 } 11856 } 11857 11858 // The operands of a select that must be truncated when the select is 11859 // promoted because the operand is actually part of the to-be-promoted set. 11860 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11861 11862 // Make sure that this is a self-contained cluster of operations (which 11863 // is not quite the same thing as saying that everything has only one 11864 // use). 11865 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11866 if (isa<ConstantSDNode>(Inputs[i])) 11867 continue; 11868 11869 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11870 UE = Inputs[i].getNode()->use_end(); 11871 UI != UE; ++UI) { 11872 SDNode *User = *UI; 11873 if (User != N && !Visited.count(User)) 11874 return SDValue(); 11875 11876 // If we're going to promote the non-output-value operand(s) or SELECT or 11877 // SELECT_CC, record them for truncation. 11878 if (User->getOpcode() == ISD::SELECT) { 11879 if (User->getOperand(0) == Inputs[i]) 11880 SelectTruncOp[0].insert(std::make_pair(User, 11881 User->getOperand(0).getValueType())); 11882 } else if (User->getOpcode() == ISD::SELECT_CC) { 11883 if (User->getOperand(0) == Inputs[i]) 11884 SelectTruncOp[0].insert(std::make_pair(User, 11885 User->getOperand(0).getValueType())); 11886 if (User->getOperand(1) == Inputs[i]) 11887 SelectTruncOp[1].insert(std::make_pair(User, 11888 User->getOperand(1).getValueType())); 11889 } 11890 } 11891 } 11892 11893 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11894 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11895 UE = PromOps[i].getNode()->use_end(); 11896 UI != UE; ++UI) { 11897 SDNode *User = *UI; 11898 if (User != N && !Visited.count(User)) 11899 return SDValue(); 11900 11901 // If we're going to promote the non-output-value operand(s) or SELECT or 11902 // SELECT_CC, record them for truncation. 11903 if (User->getOpcode() == ISD::SELECT) { 11904 if (User->getOperand(0) == PromOps[i]) 11905 SelectTruncOp[0].insert(std::make_pair(User, 11906 User->getOperand(0).getValueType())); 11907 } else if (User->getOpcode() == ISD::SELECT_CC) { 11908 if (User->getOperand(0) == PromOps[i]) 11909 SelectTruncOp[0].insert(std::make_pair(User, 11910 User->getOperand(0).getValueType())); 11911 if (User->getOperand(1) == PromOps[i]) 11912 SelectTruncOp[1].insert(std::make_pair(User, 11913 User->getOperand(1).getValueType())); 11914 } 11915 } 11916 } 11917 11918 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11919 bool ReallyNeedsExt = false; 11920 if (N->getOpcode() != ISD::ANY_EXTEND) { 11921 // If all of the inputs are not already sign/zero extended, then 11922 // we'll still need to do that at the end. 11923 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11924 if (isa<ConstantSDNode>(Inputs[i])) 11925 continue; 11926 11927 unsigned OpBits = 11928 Inputs[i].getOperand(0).getValueSizeInBits(); 11929 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11930 11931 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11932 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11933 APInt::getHighBitsSet(OpBits, 11934 OpBits-PromBits))) || 11935 (N->getOpcode() == ISD::SIGN_EXTEND && 11936 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11937 (OpBits-(PromBits-1)))) { 11938 ReallyNeedsExt = true; 11939 break; 11940 } 11941 } 11942 } 11943 11944 // Replace all inputs, either with the truncation operand, or a 11945 // truncation or extension to the final output type. 11946 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11947 // Constant inputs need to be replaced with the to-be-promoted nodes that 11948 // use them because they might have users outside of the cluster of 11949 // promoted nodes. 11950 if (isa<ConstantSDNode>(Inputs[i])) 11951 continue; 11952 11953 SDValue InSrc = Inputs[i].getOperand(0); 11954 if (Inputs[i].getValueType() == N->getValueType(0)) 11955 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11956 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11957 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11958 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11959 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11960 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11961 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11962 else 11963 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11964 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11965 } 11966 11967 std::list<HandleSDNode> PromOpHandles; 11968 for (auto &PromOp : PromOps) 11969 PromOpHandles.emplace_back(PromOp); 11970 11971 // Replace all operations (these are all the same, but have a different 11972 // (promoted) return type). DAG.getNode will validate that the types of 11973 // a binary operator match, so go through the list in reverse so that 11974 // we've likely promoted both operands first. 11975 while (!PromOpHandles.empty()) { 11976 SDValue PromOp = PromOpHandles.back().getValue(); 11977 PromOpHandles.pop_back(); 11978 11979 unsigned C; 11980 switch (PromOp.getOpcode()) { 11981 default: C = 0; break; 11982 case ISD::SELECT: C = 1; break; 11983 case ISD::SELECT_CC: C = 2; break; 11984 } 11985 11986 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11987 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11988 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11989 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11990 // The to-be-promoted operands of this node have not yet been 11991 // promoted (this should be rare because we're going through the 11992 // list backward, but if one of the operands has several users in 11993 // this cluster of to-be-promoted nodes, it is possible). 11994 PromOpHandles.emplace_front(PromOp); 11995 continue; 11996 } 11997 11998 // For SELECT and SELECT_CC nodes, we do a similar check for any 11999 // to-be-promoted comparison inputs. 12000 if (PromOp.getOpcode() == ISD::SELECT || 12001 PromOp.getOpcode() == ISD::SELECT_CC) { 12002 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12003 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12004 (SelectTruncOp[1].count(PromOp.getNode()) && 12005 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12006 PromOpHandles.emplace_front(PromOp); 12007 continue; 12008 } 12009 } 12010 12011 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12012 PromOp.getNode()->op_end()); 12013 12014 // If this node has constant inputs, then they'll need to be promoted here. 12015 for (unsigned i = 0; i < 2; ++i) { 12016 if (!isa<ConstantSDNode>(Ops[C+i])) 12017 continue; 12018 if (Ops[C+i].getValueType() == N->getValueType(0)) 12019 continue; 12020 12021 if (N->getOpcode() == ISD::SIGN_EXTEND) 12022 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12023 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12024 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12025 else 12026 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12027 } 12028 12029 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12030 // truncate them again to the original value type. 12031 if (PromOp.getOpcode() == ISD::SELECT || 12032 PromOp.getOpcode() == ISD::SELECT_CC) { 12033 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12034 if (SI0 != SelectTruncOp[0].end()) 12035 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12036 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12037 if (SI1 != SelectTruncOp[1].end()) 12038 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12039 } 12040 12041 DAG.ReplaceAllUsesOfValueWith(PromOp, 12042 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12043 } 12044 12045 // Now we're left with the initial extension itself. 12046 if (!ReallyNeedsExt) 12047 return N->getOperand(0); 12048 12049 // To zero extend, just mask off everything except for the first bit (in the 12050 // i1 case). 12051 if (N->getOpcode() == ISD::ZERO_EXTEND) 12052 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12053 DAG.getConstant(APInt::getLowBitsSet( 12054 N->getValueSizeInBits(0), PromBits), 12055 dl, N->getValueType(0))); 12056 12057 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12058 "Invalid extension type"); 12059 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12060 SDValue ShiftCst = 12061 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12062 return DAG.getNode( 12063 ISD::SRA, dl, N->getValueType(0), 12064 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12065 ShiftCst); 12066 } 12067 12068 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12069 DAGCombinerInfo &DCI) const { 12070 assert(N->getOpcode() == ISD::SETCC && 12071 "Should be called with a SETCC node"); 12072 12073 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12074 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12075 SDValue LHS = N->getOperand(0); 12076 SDValue RHS = N->getOperand(1); 12077 12078 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12079 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12080 LHS.hasOneUse()) 12081 std::swap(LHS, RHS); 12082 12083 // x == 0-y --> x+y == 0 12084 // x != 0-y --> x+y != 0 12085 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12086 RHS.hasOneUse()) { 12087 SDLoc DL(N); 12088 SelectionDAG &DAG = DCI.DAG; 12089 EVT VT = N->getValueType(0); 12090 EVT OpVT = LHS.getValueType(); 12091 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12092 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12093 } 12094 } 12095 12096 return DAGCombineTruncBoolExt(N, DCI); 12097 } 12098 12099 // Is this an extending load from an f32 to an f64? 12100 static bool isFPExtLoad(SDValue Op) { 12101 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12102 return LD->getExtensionType() == ISD::EXTLOAD && 12103 Op.getValueType() == MVT::f64; 12104 return false; 12105 } 12106 12107 /// Reduces the number of fp-to-int conversion when building a vector. 12108 /// 12109 /// If this vector is built out of floating to integer conversions, 12110 /// transform it to a vector built out of floating point values followed by a 12111 /// single floating to integer conversion of the vector. 12112 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12113 /// becomes (fptosi (build_vector ($A, $B, ...))) 12114 SDValue PPCTargetLowering:: 12115 combineElementTruncationToVectorTruncation(SDNode *N, 12116 DAGCombinerInfo &DCI) const { 12117 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12118 "Should be called with a BUILD_VECTOR node"); 12119 12120 SelectionDAG &DAG = DCI.DAG; 12121 SDLoc dl(N); 12122 12123 SDValue FirstInput = N->getOperand(0); 12124 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12125 "The input operand must be an fp-to-int conversion."); 12126 12127 // This combine happens after legalization so the fp_to_[su]i nodes are 12128 // already converted to PPCSISD nodes. 12129 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12130 if (FirstConversion == PPCISD::FCTIDZ || 12131 FirstConversion == PPCISD::FCTIDUZ || 12132 FirstConversion == PPCISD::FCTIWZ || 12133 FirstConversion == PPCISD::FCTIWUZ) { 12134 bool IsSplat = true; 12135 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12136 FirstConversion == PPCISD::FCTIWUZ; 12137 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12138 SmallVector<SDValue, 4> Ops; 12139 EVT TargetVT = N->getValueType(0); 12140 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12141 SDValue NextOp = N->getOperand(i); 12142 if (NextOp.getOpcode() != PPCISD::MFVSR) 12143 return SDValue(); 12144 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12145 if (NextConversion != FirstConversion) 12146 return SDValue(); 12147 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12148 // This is not valid if the input was originally double precision. It is 12149 // also not profitable to do unless this is an extending load in which 12150 // case doing this combine will allow us to combine consecutive loads. 12151 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12152 return SDValue(); 12153 if (N->getOperand(i) != FirstInput) 12154 IsSplat = false; 12155 } 12156 12157 // If this is a splat, we leave it as-is since there will be only a single 12158 // fp-to-int conversion followed by a splat of the integer. This is better 12159 // for 32-bit and smaller ints and neutral for 64-bit ints. 12160 if (IsSplat) 12161 return SDValue(); 12162 12163 // Now that we know we have the right type of node, get its operands 12164 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12165 SDValue In = N->getOperand(i).getOperand(0); 12166 if (Is32Bit) { 12167 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12168 // here, we know that all inputs are extending loads so this is safe). 12169 if (In.isUndef()) 12170 Ops.push_back(DAG.getUNDEF(SrcVT)); 12171 else { 12172 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12173 MVT::f32, In.getOperand(0), 12174 DAG.getIntPtrConstant(1, dl)); 12175 Ops.push_back(Trunc); 12176 } 12177 } else 12178 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12179 } 12180 12181 unsigned Opcode; 12182 if (FirstConversion == PPCISD::FCTIDZ || 12183 FirstConversion == PPCISD::FCTIWZ) 12184 Opcode = ISD::FP_TO_SINT; 12185 else 12186 Opcode = ISD::FP_TO_UINT; 12187 12188 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12189 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12190 return DAG.getNode(Opcode, dl, TargetVT, BV); 12191 } 12192 return SDValue(); 12193 } 12194 12195 /// Reduce the number of loads when building a vector. 12196 /// 12197 /// Building a vector out of multiple loads can be converted to a load 12198 /// of the vector type if the loads are consecutive. If the loads are 12199 /// consecutive but in descending order, a shuffle is added at the end 12200 /// to reorder the vector. 12201 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12202 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12203 "Should be called with a BUILD_VECTOR node"); 12204 12205 SDLoc dl(N); 12206 12207 // Return early for non byte-sized type, as they can't be consecutive. 12208 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12209 return SDValue(); 12210 12211 bool InputsAreConsecutiveLoads = true; 12212 bool InputsAreReverseConsecutive = true; 12213 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12214 SDValue FirstInput = N->getOperand(0); 12215 bool IsRoundOfExtLoad = false; 12216 12217 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12218 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12219 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12220 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12221 } 12222 // Not a build vector of (possibly fp_rounded) loads. 12223 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12224 N->getNumOperands() == 1) 12225 return SDValue(); 12226 12227 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12228 // If any inputs are fp_round(extload), they all must be. 12229 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12230 return SDValue(); 12231 12232 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12233 N->getOperand(i); 12234 if (NextInput.getOpcode() != ISD::LOAD) 12235 return SDValue(); 12236 12237 SDValue PreviousInput = 12238 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12239 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12240 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12241 12242 // If any inputs are fp_round(extload), they all must be. 12243 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12244 return SDValue(); 12245 12246 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12247 InputsAreConsecutiveLoads = false; 12248 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12249 InputsAreReverseConsecutive = false; 12250 12251 // Exit early if the loads are neither consecutive nor reverse consecutive. 12252 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12253 return SDValue(); 12254 } 12255 12256 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12257 "The loads cannot be both consecutive and reverse consecutive."); 12258 12259 SDValue FirstLoadOp = 12260 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12261 SDValue LastLoadOp = 12262 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12263 N->getOperand(N->getNumOperands()-1); 12264 12265 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12266 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12267 if (InputsAreConsecutiveLoads) { 12268 assert(LD1 && "Input needs to be a LoadSDNode."); 12269 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12270 LD1->getBasePtr(), LD1->getPointerInfo(), 12271 LD1->getAlignment()); 12272 } 12273 if (InputsAreReverseConsecutive) { 12274 assert(LDL && "Input needs to be a LoadSDNode."); 12275 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12276 LDL->getBasePtr(), LDL->getPointerInfo(), 12277 LDL->getAlignment()); 12278 SmallVector<int, 16> Ops; 12279 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12280 Ops.push_back(i); 12281 12282 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12283 DAG.getUNDEF(N->getValueType(0)), Ops); 12284 } 12285 return SDValue(); 12286 } 12287 12288 // This function adds the required vector_shuffle needed to get 12289 // the elements of the vector extract in the correct position 12290 // as specified by the CorrectElems encoding. 12291 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12292 SDValue Input, uint64_t Elems, 12293 uint64_t CorrectElems) { 12294 SDLoc dl(N); 12295 12296 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12297 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12298 12299 // Knowing the element indices being extracted from the original 12300 // vector and the order in which they're being inserted, just put 12301 // them at element indices required for the instruction. 12302 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12303 if (DAG.getDataLayout().isLittleEndian()) 12304 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12305 else 12306 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12307 CorrectElems = CorrectElems >> 8; 12308 Elems = Elems >> 8; 12309 } 12310 12311 SDValue Shuffle = 12312 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12313 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12314 12315 EVT Ty = N->getValueType(0); 12316 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12317 return BV; 12318 } 12319 12320 // Look for build vector patterns where input operands come from sign 12321 // extended vector_extract elements of specific indices. If the correct indices 12322 // aren't used, add a vector shuffle to fix up the indices and create a new 12323 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12324 // during instruction selection. 12325 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12326 // This array encodes the indices that the vector sign extend instructions 12327 // extract from when extending from one type to another for both BE and LE. 12328 // The right nibble of each byte corresponds to the LE incides. 12329 // and the left nibble of each byte corresponds to the BE incides. 12330 // For example: 0x3074B8FC byte->word 12331 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12332 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12333 // For example: 0x000070F8 byte->double word 12334 // For LE: the allowed indices are: 0x0,0x8 12335 // For BE: the allowed indices are: 0x7,0xF 12336 uint64_t TargetElems[] = { 12337 0x3074B8FC, // b->w 12338 0x000070F8, // b->d 12339 0x10325476, // h->w 12340 0x00003074, // h->d 12341 0x00001032, // w->d 12342 }; 12343 12344 uint64_t Elems = 0; 12345 int Index; 12346 SDValue Input; 12347 12348 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12349 if (!Op) 12350 return false; 12351 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12352 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12353 return false; 12354 12355 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12356 // of the right width. 12357 SDValue Extract = Op.getOperand(0); 12358 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12359 Extract = Extract.getOperand(0); 12360 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12361 return false; 12362 12363 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12364 if (!ExtOp) 12365 return false; 12366 12367 Index = ExtOp->getZExtValue(); 12368 if (Input && Input != Extract.getOperand(0)) 12369 return false; 12370 12371 if (!Input) 12372 Input = Extract.getOperand(0); 12373 12374 Elems = Elems << 8; 12375 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12376 Elems |= Index; 12377 12378 return true; 12379 }; 12380 12381 // If the build vector operands aren't sign extended vector extracts, 12382 // of the same input vector, then return. 12383 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12384 if (!isSExtOfVecExtract(N->getOperand(i))) { 12385 return SDValue(); 12386 } 12387 } 12388 12389 // If the vector extract indicies are not correct, add the appropriate 12390 // vector_shuffle. 12391 int TgtElemArrayIdx; 12392 int InputSize = Input.getValueType().getScalarSizeInBits(); 12393 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12394 if (InputSize + OutputSize == 40) 12395 TgtElemArrayIdx = 0; 12396 else if (InputSize + OutputSize == 72) 12397 TgtElemArrayIdx = 1; 12398 else if (InputSize + OutputSize == 48) 12399 TgtElemArrayIdx = 2; 12400 else if (InputSize + OutputSize == 80) 12401 TgtElemArrayIdx = 3; 12402 else if (InputSize + OutputSize == 96) 12403 TgtElemArrayIdx = 4; 12404 else 12405 return SDValue(); 12406 12407 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12408 CorrectElems = DAG.getDataLayout().isLittleEndian() 12409 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12410 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12411 if (Elems != CorrectElems) { 12412 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12413 } 12414 12415 // Regular lowering will catch cases where a shuffle is not needed. 12416 return SDValue(); 12417 } 12418 12419 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12420 DAGCombinerInfo &DCI) const { 12421 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12422 "Should be called with a BUILD_VECTOR node"); 12423 12424 SelectionDAG &DAG = DCI.DAG; 12425 SDLoc dl(N); 12426 12427 if (!Subtarget.hasVSX()) 12428 return SDValue(); 12429 12430 // The target independent DAG combiner will leave a build_vector of 12431 // float-to-int conversions intact. We can generate MUCH better code for 12432 // a float-to-int conversion of a vector of floats. 12433 SDValue FirstInput = N->getOperand(0); 12434 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12435 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12436 if (Reduced) 12437 return Reduced; 12438 } 12439 12440 // If we're building a vector out of consecutive loads, just load that 12441 // vector type. 12442 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12443 if (Reduced) 12444 return Reduced; 12445 12446 // If we're building a vector out of extended elements from another vector 12447 // we have P9 vector integer extend instructions. The code assumes legal 12448 // input types (i.e. it can't handle things like v4i16) so do not run before 12449 // legalization. 12450 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12451 Reduced = combineBVOfVecSExt(N, DAG); 12452 if (Reduced) 12453 return Reduced; 12454 } 12455 12456 12457 if (N->getValueType(0) != MVT::v2f64) 12458 return SDValue(); 12459 12460 // Looking for: 12461 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12462 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12463 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12464 return SDValue(); 12465 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12466 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12467 return SDValue(); 12468 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12469 return SDValue(); 12470 12471 SDValue Ext1 = FirstInput.getOperand(0); 12472 SDValue Ext2 = N->getOperand(1).getOperand(0); 12473 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12474 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12475 return SDValue(); 12476 12477 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12478 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12479 if (!Ext1Op || !Ext2Op) 12480 return SDValue(); 12481 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12482 Ext1.getOperand(0) != Ext2.getOperand(0)) 12483 return SDValue(); 12484 12485 int FirstElem = Ext1Op->getZExtValue(); 12486 int SecondElem = Ext2Op->getZExtValue(); 12487 int SubvecIdx; 12488 if (FirstElem == 0 && SecondElem == 1) 12489 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12490 else if (FirstElem == 2 && SecondElem == 3) 12491 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12492 else 12493 return SDValue(); 12494 12495 SDValue SrcVec = Ext1.getOperand(0); 12496 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12497 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12498 return DAG.getNode(NodeType, dl, MVT::v2f64, 12499 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12500 } 12501 12502 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12503 DAGCombinerInfo &DCI) const { 12504 assert((N->getOpcode() == ISD::SINT_TO_FP || 12505 N->getOpcode() == ISD::UINT_TO_FP) && 12506 "Need an int -> FP conversion node here"); 12507 12508 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12509 return SDValue(); 12510 12511 SelectionDAG &DAG = DCI.DAG; 12512 SDLoc dl(N); 12513 SDValue Op(N, 0); 12514 12515 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12516 // from the hardware. 12517 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12518 return SDValue(); 12519 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12520 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12521 return SDValue(); 12522 12523 SDValue FirstOperand(Op.getOperand(0)); 12524 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12525 (FirstOperand.getValueType() == MVT::i8 || 12526 FirstOperand.getValueType() == MVT::i16); 12527 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12528 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12529 bool DstDouble = Op.getValueType() == MVT::f64; 12530 unsigned ConvOp = Signed ? 12531 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12532 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12533 SDValue WidthConst = 12534 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12535 dl, false); 12536 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12537 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12538 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12539 DAG.getVTList(MVT::f64, MVT::Other), 12540 Ops, MVT::i8, LDN->getMemOperand()); 12541 12542 // For signed conversion, we need to sign-extend the value in the VSR 12543 if (Signed) { 12544 SDValue ExtOps[] = { Ld, WidthConst }; 12545 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12546 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12547 } else 12548 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12549 } 12550 12551 12552 // For i32 intermediate values, unfortunately, the conversion functions 12553 // leave the upper 32 bits of the value are undefined. Within the set of 12554 // scalar instructions, we have no method for zero- or sign-extending the 12555 // value. Thus, we cannot handle i32 intermediate values here. 12556 if (Op.getOperand(0).getValueType() == MVT::i32) 12557 return SDValue(); 12558 12559 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12560 "UINT_TO_FP is supported only with FPCVT"); 12561 12562 // If we have FCFIDS, then use it when converting to single-precision. 12563 // Otherwise, convert to double-precision and then round. 12564 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12565 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12566 : PPCISD::FCFIDS) 12567 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12568 : PPCISD::FCFID); 12569 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12570 ? MVT::f32 12571 : MVT::f64; 12572 12573 // If we're converting from a float, to an int, and back to a float again, 12574 // then we don't need the store/load pair at all. 12575 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12576 Subtarget.hasFPCVT()) || 12577 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12578 SDValue Src = Op.getOperand(0).getOperand(0); 12579 if (Src.getValueType() == MVT::f32) { 12580 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12581 DCI.AddToWorklist(Src.getNode()); 12582 } else if (Src.getValueType() != MVT::f64) { 12583 // Make sure that we don't pick up a ppc_fp128 source value. 12584 return SDValue(); 12585 } 12586 12587 unsigned FCTOp = 12588 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12589 PPCISD::FCTIDUZ; 12590 12591 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12592 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12593 12594 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12595 FP = DAG.getNode(ISD::FP_ROUND, dl, 12596 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12597 DCI.AddToWorklist(FP.getNode()); 12598 } 12599 12600 return FP; 12601 } 12602 12603 return SDValue(); 12604 } 12605 12606 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12607 // builtins) into loads with swaps. 12608 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12609 DAGCombinerInfo &DCI) const { 12610 SelectionDAG &DAG = DCI.DAG; 12611 SDLoc dl(N); 12612 SDValue Chain; 12613 SDValue Base; 12614 MachineMemOperand *MMO; 12615 12616 switch (N->getOpcode()) { 12617 default: 12618 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12619 case ISD::LOAD: { 12620 LoadSDNode *LD = cast<LoadSDNode>(N); 12621 Chain = LD->getChain(); 12622 Base = LD->getBasePtr(); 12623 MMO = LD->getMemOperand(); 12624 // If the MMO suggests this isn't a load of a full vector, leave 12625 // things alone. For a built-in, we have to make the change for 12626 // correctness, so if there is a size problem that will be a bug. 12627 if (MMO->getSize() < 16) 12628 return SDValue(); 12629 break; 12630 } 12631 case ISD::INTRINSIC_W_CHAIN: { 12632 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12633 Chain = Intrin->getChain(); 12634 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12635 // us what we want. Get operand 2 instead. 12636 Base = Intrin->getOperand(2); 12637 MMO = Intrin->getMemOperand(); 12638 break; 12639 } 12640 } 12641 12642 MVT VecTy = N->getValueType(0).getSimpleVT(); 12643 12644 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12645 // aligned and the type is a vector with elements up to 4 bytes 12646 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12647 && VecTy.getScalarSizeInBits() <= 32 ) { 12648 return SDValue(); 12649 } 12650 12651 SDValue LoadOps[] = { Chain, Base }; 12652 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12653 DAG.getVTList(MVT::v2f64, MVT::Other), 12654 LoadOps, MVT::v2f64, MMO); 12655 12656 DCI.AddToWorklist(Load.getNode()); 12657 Chain = Load.getValue(1); 12658 SDValue Swap = DAG.getNode( 12659 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12660 DCI.AddToWorklist(Swap.getNode()); 12661 12662 // Add a bitcast if the resulting load type doesn't match v2f64. 12663 if (VecTy != MVT::v2f64) { 12664 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12665 DCI.AddToWorklist(N.getNode()); 12666 // Package {bitcast value, swap's chain} to match Load's shape. 12667 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12668 N, Swap.getValue(1)); 12669 } 12670 12671 return Swap; 12672 } 12673 12674 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12675 // builtins) into stores with swaps. 12676 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12677 DAGCombinerInfo &DCI) const { 12678 SelectionDAG &DAG = DCI.DAG; 12679 SDLoc dl(N); 12680 SDValue Chain; 12681 SDValue Base; 12682 unsigned SrcOpnd; 12683 MachineMemOperand *MMO; 12684 12685 switch (N->getOpcode()) { 12686 default: 12687 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12688 case ISD::STORE: { 12689 StoreSDNode *ST = cast<StoreSDNode>(N); 12690 Chain = ST->getChain(); 12691 Base = ST->getBasePtr(); 12692 MMO = ST->getMemOperand(); 12693 SrcOpnd = 1; 12694 // If the MMO suggests this isn't a store of a full vector, leave 12695 // things alone. For a built-in, we have to make the change for 12696 // correctness, so if there is a size problem that will be a bug. 12697 if (MMO->getSize() < 16) 12698 return SDValue(); 12699 break; 12700 } 12701 case ISD::INTRINSIC_VOID: { 12702 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12703 Chain = Intrin->getChain(); 12704 // Intrin->getBasePtr() oddly does not get what we want. 12705 Base = Intrin->getOperand(3); 12706 MMO = Intrin->getMemOperand(); 12707 SrcOpnd = 2; 12708 break; 12709 } 12710 } 12711 12712 SDValue Src = N->getOperand(SrcOpnd); 12713 MVT VecTy = Src.getValueType().getSimpleVT(); 12714 12715 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12716 // aligned and the type is a vector with elements up to 4 bytes 12717 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12718 && VecTy.getScalarSizeInBits() <= 32 ) { 12719 return SDValue(); 12720 } 12721 12722 // All stores are done as v2f64 and possible bit cast. 12723 if (VecTy != MVT::v2f64) { 12724 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12725 DCI.AddToWorklist(Src.getNode()); 12726 } 12727 12728 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12729 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12730 DCI.AddToWorklist(Swap.getNode()); 12731 Chain = Swap.getValue(1); 12732 SDValue StoreOps[] = { Chain, Swap, Base }; 12733 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12734 DAG.getVTList(MVT::Other), 12735 StoreOps, VecTy, MMO); 12736 DCI.AddToWorklist(Store.getNode()); 12737 return Store; 12738 } 12739 12740 // Handle DAG combine for STORE (FP_TO_INT F). 12741 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12742 DAGCombinerInfo &DCI) const { 12743 12744 SelectionDAG &DAG = DCI.DAG; 12745 SDLoc dl(N); 12746 unsigned Opcode = N->getOperand(1).getOpcode(); 12747 12748 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12749 && "Not a FP_TO_INT Instruction!"); 12750 12751 SDValue Val = N->getOperand(1).getOperand(0); 12752 EVT Op1VT = N->getOperand(1).getValueType(); 12753 EVT ResVT = Val.getValueType(); 12754 12755 // Floating point types smaller than 32 bits are not legal on Power. 12756 if (ResVT.getScalarSizeInBits() < 32) 12757 return SDValue(); 12758 12759 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12760 bool ValidTypeForStoreFltAsInt = 12761 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12762 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12763 12764 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12765 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12766 return SDValue(); 12767 12768 // Extend f32 values to f64 12769 if (ResVT.getScalarSizeInBits() == 32) { 12770 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12771 DCI.AddToWorklist(Val.getNode()); 12772 } 12773 12774 // Set signed or unsigned conversion opcode. 12775 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12776 PPCISD::FP_TO_SINT_IN_VSR : 12777 PPCISD::FP_TO_UINT_IN_VSR; 12778 12779 Val = DAG.getNode(ConvOpcode, 12780 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12781 DCI.AddToWorklist(Val.getNode()); 12782 12783 // Set number of bytes being converted. 12784 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12785 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12786 DAG.getIntPtrConstant(ByteSize, dl, false), 12787 DAG.getValueType(Op1VT) }; 12788 12789 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12790 DAG.getVTList(MVT::Other), Ops, 12791 cast<StoreSDNode>(N)->getMemoryVT(), 12792 cast<StoreSDNode>(N)->getMemOperand()); 12793 12794 DCI.AddToWorklist(Val.getNode()); 12795 return Val; 12796 } 12797 12798 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12799 DAGCombinerInfo &DCI) const { 12800 SelectionDAG &DAG = DCI.DAG; 12801 SDLoc dl(N); 12802 switch (N->getOpcode()) { 12803 default: break; 12804 case ISD::ADD: 12805 return combineADD(N, DCI); 12806 case ISD::SHL: 12807 return combineSHL(N, DCI); 12808 case ISD::SRA: 12809 return combineSRA(N, DCI); 12810 case ISD::SRL: 12811 return combineSRL(N, DCI); 12812 case ISD::MUL: 12813 return combineMUL(N, DCI); 12814 case PPCISD::SHL: 12815 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12816 return N->getOperand(0); 12817 break; 12818 case PPCISD::SRL: 12819 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12820 return N->getOperand(0); 12821 break; 12822 case PPCISD::SRA: 12823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12824 if (C->isNullValue() || // 0 >>s V -> 0. 12825 C->isAllOnesValue()) // -1 >>s V -> -1. 12826 return N->getOperand(0); 12827 } 12828 break; 12829 case ISD::SIGN_EXTEND: 12830 case ISD::ZERO_EXTEND: 12831 case ISD::ANY_EXTEND: 12832 return DAGCombineExtBoolTrunc(N, DCI); 12833 case ISD::TRUNCATE: 12834 return combineTRUNCATE(N, DCI); 12835 case ISD::SETCC: 12836 if (SDValue CSCC = combineSetCC(N, DCI)) 12837 return CSCC; 12838 LLVM_FALLTHROUGH; 12839 case ISD::SELECT_CC: 12840 return DAGCombineTruncBoolExt(N, DCI); 12841 case ISD::SINT_TO_FP: 12842 case ISD::UINT_TO_FP: 12843 return combineFPToIntToFP(N, DCI); 12844 case ISD::STORE: { 12845 12846 EVT Op1VT = N->getOperand(1).getValueType(); 12847 unsigned Opcode = N->getOperand(1).getOpcode(); 12848 12849 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12850 SDValue Val= combineStoreFPToInt(N, DCI); 12851 if (Val) 12852 return Val; 12853 } 12854 12855 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12856 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12857 N->getOperand(1).getNode()->hasOneUse() && 12858 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12859 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12860 12861 // STBRX can only handle simple types and it makes no sense to store less 12862 // two bytes in byte-reversed order. 12863 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12864 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 12865 break; 12866 12867 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12868 // Do an any-extend to 32-bits if this is a half-word input. 12869 if (BSwapOp.getValueType() == MVT::i16) 12870 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12871 12872 // If the type of BSWAP operand is wider than stored memory width 12873 // it need to be shifted to the right side before STBRX. 12874 if (Op1VT.bitsGT(mVT)) { 12875 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12876 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12877 DAG.getConstant(Shift, dl, MVT::i32)); 12878 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12879 if (Op1VT == MVT::i64) 12880 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12881 } 12882 12883 SDValue Ops[] = { 12884 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12885 }; 12886 return 12887 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12888 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12889 cast<StoreSDNode>(N)->getMemOperand()); 12890 } 12891 12892 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12893 // So it can increase the chance of CSE constant construction. 12894 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12895 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12896 // Need to sign-extended to 64-bits to handle negative values. 12897 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12898 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12899 MemVT.getSizeInBits()); 12900 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12901 12902 // DAG.getTruncStore() can't be used here because it doesn't accept 12903 // the general (base + offset) addressing mode. 12904 // So we use UpdateNodeOperands and setTruncatingStore instead. 12905 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12906 N->getOperand(3)); 12907 cast<StoreSDNode>(N)->setTruncatingStore(true); 12908 return SDValue(N, 0); 12909 } 12910 12911 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12912 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12913 if (Op1VT.isSimple()) { 12914 MVT StoreVT = Op1VT.getSimpleVT(); 12915 if (Subtarget.needsSwapsForVSXMemOps() && 12916 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12917 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12918 return expandVSXStoreForLE(N, DCI); 12919 } 12920 break; 12921 } 12922 case ISD::LOAD: { 12923 LoadSDNode *LD = cast<LoadSDNode>(N); 12924 EVT VT = LD->getValueType(0); 12925 12926 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12927 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12928 if (VT.isSimple()) { 12929 MVT LoadVT = VT.getSimpleVT(); 12930 if (Subtarget.needsSwapsForVSXMemOps() && 12931 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12932 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12933 return expandVSXLoadForLE(N, DCI); 12934 } 12935 12936 // We sometimes end up with a 64-bit integer load, from which we extract 12937 // two single-precision floating-point numbers. This happens with 12938 // std::complex<float>, and other similar structures, because of the way we 12939 // canonicalize structure copies. However, if we lack direct moves, 12940 // then the final bitcasts from the extracted integer values to the 12941 // floating-point numbers turn into store/load pairs. Even with direct moves, 12942 // just loading the two floating-point numbers is likely better. 12943 auto ReplaceTwoFloatLoad = [&]() { 12944 if (VT != MVT::i64) 12945 return false; 12946 12947 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12948 LD->isVolatile()) 12949 return false; 12950 12951 // We're looking for a sequence like this: 12952 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12953 // t16: i64 = srl t13, Constant:i32<32> 12954 // t17: i32 = truncate t16 12955 // t18: f32 = bitcast t17 12956 // t19: i32 = truncate t13 12957 // t20: f32 = bitcast t19 12958 12959 if (!LD->hasNUsesOfValue(2, 0)) 12960 return false; 12961 12962 auto UI = LD->use_begin(); 12963 while (UI.getUse().getResNo() != 0) ++UI; 12964 SDNode *Trunc = *UI++; 12965 while (UI.getUse().getResNo() != 0) ++UI; 12966 SDNode *RightShift = *UI; 12967 if (Trunc->getOpcode() != ISD::TRUNCATE) 12968 std::swap(Trunc, RightShift); 12969 12970 if (Trunc->getOpcode() != ISD::TRUNCATE || 12971 Trunc->getValueType(0) != MVT::i32 || 12972 !Trunc->hasOneUse()) 12973 return false; 12974 if (RightShift->getOpcode() != ISD::SRL || 12975 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12976 RightShift->getConstantOperandVal(1) != 32 || 12977 !RightShift->hasOneUse()) 12978 return false; 12979 12980 SDNode *Trunc2 = *RightShift->use_begin(); 12981 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12982 Trunc2->getValueType(0) != MVT::i32 || 12983 !Trunc2->hasOneUse()) 12984 return false; 12985 12986 SDNode *Bitcast = *Trunc->use_begin(); 12987 SDNode *Bitcast2 = *Trunc2->use_begin(); 12988 12989 if (Bitcast->getOpcode() != ISD::BITCAST || 12990 Bitcast->getValueType(0) != MVT::f32) 12991 return false; 12992 if (Bitcast2->getOpcode() != ISD::BITCAST || 12993 Bitcast2->getValueType(0) != MVT::f32) 12994 return false; 12995 12996 if (Subtarget.isLittleEndian()) 12997 std::swap(Bitcast, Bitcast2); 12998 12999 // Bitcast has the second float (in memory-layout order) and Bitcast2 13000 // has the first one. 13001 13002 SDValue BasePtr = LD->getBasePtr(); 13003 if (LD->isIndexed()) { 13004 assert(LD->getAddressingMode() == ISD::PRE_INC && 13005 "Non-pre-inc AM on PPC?"); 13006 BasePtr = 13007 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13008 LD->getOffset()); 13009 } 13010 13011 auto MMOFlags = 13012 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13013 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13014 LD->getPointerInfo(), LD->getAlignment(), 13015 MMOFlags, LD->getAAInfo()); 13016 SDValue AddPtr = 13017 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13018 BasePtr, DAG.getIntPtrConstant(4, dl)); 13019 SDValue FloatLoad2 = DAG.getLoad( 13020 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13021 LD->getPointerInfo().getWithOffset(4), 13022 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13023 13024 if (LD->isIndexed()) { 13025 // Note that DAGCombine should re-form any pre-increment load(s) from 13026 // what is produced here if that makes sense. 13027 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13028 } 13029 13030 DCI.CombineTo(Bitcast2, FloatLoad); 13031 DCI.CombineTo(Bitcast, FloatLoad2); 13032 13033 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13034 SDValue(FloatLoad2.getNode(), 1)); 13035 return true; 13036 }; 13037 13038 if (ReplaceTwoFloatLoad()) 13039 return SDValue(N, 0); 13040 13041 EVT MemVT = LD->getMemoryVT(); 13042 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13043 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13044 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13045 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13046 if (LD->isUnindexed() && VT.isVector() && 13047 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13048 // P8 and later hardware should just use LOAD. 13049 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13050 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13051 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13052 LD->getAlignment() >= ScalarABIAlignment)) && 13053 LD->getAlignment() < ABIAlignment) { 13054 // This is a type-legal unaligned Altivec or QPX load. 13055 SDValue Chain = LD->getChain(); 13056 SDValue Ptr = LD->getBasePtr(); 13057 bool isLittleEndian = Subtarget.isLittleEndian(); 13058 13059 // This implements the loading of unaligned vectors as described in 13060 // the venerable Apple Velocity Engine overview. Specifically: 13061 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13062 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13063 // 13064 // The general idea is to expand a sequence of one or more unaligned 13065 // loads into an alignment-based permutation-control instruction (lvsl 13066 // or lvsr), a series of regular vector loads (which always truncate 13067 // their input address to an aligned address), and a series of 13068 // permutations. The results of these permutations are the requested 13069 // loaded values. The trick is that the last "extra" load is not taken 13070 // from the address you might suspect (sizeof(vector) bytes after the 13071 // last requested load), but rather sizeof(vector) - 1 bytes after the 13072 // last requested vector. The point of this is to avoid a page fault if 13073 // the base address happened to be aligned. This works because if the 13074 // base address is aligned, then adding less than a full vector length 13075 // will cause the last vector in the sequence to be (re)loaded. 13076 // Otherwise, the next vector will be fetched as you might suspect was 13077 // necessary. 13078 13079 // We might be able to reuse the permutation generation from 13080 // a different base address offset from this one by an aligned amount. 13081 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13082 // optimization later. 13083 Intrinsic::ID Intr, IntrLD, IntrPerm; 13084 MVT PermCntlTy, PermTy, LDTy; 13085 if (Subtarget.hasAltivec()) { 13086 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13087 Intrinsic::ppc_altivec_lvsl; 13088 IntrLD = Intrinsic::ppc_altivec_lvx; 13089 IntrPerm = Intrinsic::ppc_altivec_vperm; 13090 PermCntlTy = MVT::v16i8; 13091 PermTy = MVT::v4i32; 13092 LDTy = MVT::v4i32; 13093 } else { 13094 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13095 Intrinsic::ppc_qpx_qvlpcls; 13096 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13097 Intrinsic::ppc_qpx_qvlfs; 13098 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13099 PermCntlTy = MVT::v4f64; 13100 PermTy = MVT::v4f64; 13101 LDTy = MemVT.getSimpleVT(); 13102 } 13103 13104 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13105 13106 // Create the new MMO for the new base load. It is like the original MMO, 13107 // but represents an area in memory almost twice the vector size centered 13108 // on the original address. If the address is unaligned, we might start 13109 // reading up to (sizeof(vector)-1) bytes below the address of the 13110 // original unaligned load. 13111 MachineFunction &MF = DAG.getMachineFunction(); 13112 MachineMemOperand *BaseMMO = 13113 MF.getMachineMemOperand(LD->getMemOperand(), 13114 -(long)MemVT.getStoreSize()+1, 13115 2*MemVT.getStoreSize()-1); 13116 13117 // Create the new base load. 13118 SDValue LDXIntID = 13119 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13120 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13121 SDValue BaseLoad = 13122 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13123 DAG.getVTList(PermTy, MVT::Other), 13124 BaseLoadOps, LDTy, BaseMMO); 13125 13126 // Note that the value of IncOffset (which is provided to the next 13127 // load's pointer info offset value, and thus used to calculate the 13128 // alignment), and the value of IncValue (which is actually used to 13129 // increment the pointer value) are different! This is because we 13130 // require the next load to appear to be aligned, even though it 13131 // is actually offset from the base pointer by a lesser amount. 13132 int IncOffset = VT.getSizeInBits() / 8; 13133 int IncValue = IncOffset; 13134 13135 // Walk (both up and down) the chain looking for another load at the real 13136 // (aligned) offset (the alignment of the other load does not matter in 13137 // this case). If found, then do not use the offset reduction trick, as 13138 // that will prevent the loads from being later combined (as they would 13139 // otherwise be duplicates). 13140 if (!findConsecutiveLoad(LD, DAG)) 13141 --IncValue; 13142 13143 SDValue Increment = 13144 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13145 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13146 13147 MachineMemOperand *ExtraMMO = 13148 MF.getMachineMemOperand(LD->getMemOperand(), 13149 1, 2*MemVT.getStoreSize()-1); 13150 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13151 SDValue ExtraLoad = 13152 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13153 DAG.getVTList(PermTy, MVT::Other), 13154 ExtraLoadOps, LDTy, ExtraMMO); 13155 13156 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13157 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13158 13159 // Because vperm has a big-endian bias, we must reverse the order 13160 // of the input vectors and complement the permute control vector 13161 // when generating little endian code. We have already handled the 13162 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13163 // and ExtraLoad here. 13164 SDValue Perm; 13165 if (isLittleEndian) 13166 Perm = BuildIntrinsicOp(IntrPerm, 13167 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13168 else 13169 Perm = BuildIntrinsicOp(IntrPerm, 13170 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13171 13172 if (VT != PermTy) 13173 Perm = Subtarget.hasAltivec() ? 13174 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13175 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13176 DAG.getTargetConstant(1, dl, MVT::i64)); 13177 // second argument is 1 because this rounding 13178 // is always exact. 13179 13180 // The output of the permutation is our loaded result, the TokenFactor is 13181 // our new chain. 13182 DCI.CombineTo(N, Perm, TF); 13183 return SDValue(N, 0); 13184 } 13185 } 13186 break; 13187 case ISD::INTRINSIC_WO_CHAIN: { 13188 bool isLittleEndian = Subtarget.isLittleEndian(); 13189 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13190 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13191 : Intrinsic::ppc_altivec_lvsl); 13192 if ((IID == Intr || 13193 IID == Intrinsic::ppc_qpx_qvlpcld || 13194 IID == Intrinsic::ppc_qpx_qvlpcls) && 13195 N->getOperand(1)->getOpcode() == ISD::ADD) { 13196 SDValue Add = N->getOperand(1); 13197 13198 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13199 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13200 13201 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13202 APInt::getAllOnesValue(Bits /* alignment */) 13203 .zext(Add.getScalarValueSizeInBits()))) { 13204 SDNode *BasePtr = Add->getOperand(0).getNode(); 13205 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13206 UE = BasePtr->use_end(); 13207 UI != UE; ++UI) { 13208 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13209 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13210 // We've found another LVSL/LVSR, and this address is an aligned 13211 // multiple of that one. The results will be the same, so use the 13212 // one we've just found instead. 13213 13214 return SDValue(*UI, 0); 13215 } 13216 } 13217 } 13218 13219 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13220 SDNode *BasePtr = Add->getOperand(0).getNode(); 13221 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13222 UE = BasePtr->use_end(); UI != UE; ++UI) { 13223 if (UI->getOpcode() == ISD::ADD && 13224 isa<ConstantSDNode>(UI->getOperand(1)) && 13225 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13226 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13227 (1ULL << Bits) == 0) { 13228 SDNode *OtherAdd = *UI; 13229 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13230 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13231 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13232 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13233 return SDValue(*VI, 0); 13234 } 13235 } 13236 } 13237 } 13238 } 13239 } 13240 13241 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13242 // Expose the vabsduw/h/b opportunity for down stream 13243 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13244 (IID == Intrinsic::ppc_altivec_vmaxsw || 13245 IID == Intrinsic::ppc_altivec_vmaxsh || 13246 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13247 SDValue V1 = N->getOperand(1); 13248 SDValue V2 = N->getOperand(2); 13249 if ((V1.getSimpleValueType() == MVT::v4i32 || 13250 V1.getSimpleValueType() == MVT::v8i16 || 13251 V1.getSimpleValueType() == MVT::v16i8) && 13252 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13253 // (0-a, a) 13254 if (V1.getOpcode() == ISD::SUB && 13255 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13256 V1.getOperand(1) == V2) { 13257 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13258 } 13259 // (a, 0-a) 13260 if (V2.getOpcode() == ISD::SUB && 13261 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13262 V2.getOperand(1) == V1) { 13263 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13264 } 13265 // (x-y, y-x) 13266 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13267 V1.getOperand(0) == V2.getOperand(1) && 13268 V1.getOperand(1) == V2.getOperand(0)) { 13269 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13270 } 13271 } 13272 } 13273 } 13274 13275 break; 13276 case ISD::INTRINSIC_W_CHAIN: 13277 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13278 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13279 if (Subtarget.needsSwapsForVSXMemOps()) { 13280 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13281 default: 13282 break; 13283 case Intrinsic::ppc_vsx_lxvw4x: 13284 case Intrinsic::ppc_vsx_lxvd2x: 13285 return expandVSXLoadForLE(N, DCI); 13286 } 13287 } 13288 break; 13289 case ISD::INTRINSIC_VOID: 13290 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13291 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13292 if (Subtarget.needsSwapsForVSXMemOps()) { 13293 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13294 default: 13295 break; 13296 case Intrinsic::ppc_vsx_stxvw4x: 13297 case Intrinsic::ppc_vsx_stxvd2x: 13298 return expandVSXStoreForLE(N, DCI); 13299 } 13300 } 13301 break; 13302 case ISD::BSWAP: 13303 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13304 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13305 N->getOperand(0).hasOneUse() && 13306 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13307 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13308 N->getValueType(0) == MVT::i64))) { 13309 SDValue Load = N->getOperand(0); 13310 LoadSDNode *LD = cast<LoadSDNode>(Load); 13311 // Create the byte-swapping load. 13312 SDValue Ops[] = { 13313 LD->getChain(), // Chain 13314 LD->getBasePtr(), // Ptr 13315 DAG.getValueType(N->getValueType(0)) // VT 13316 }; 13317 SDValue BSLoad = 13318 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13319 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13320 MVT::i64 : MVT::i32, MVT::Other), 13321 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13322 13323 // If this is an i16 load, insert the truncate. 13324 SDValue ResVal = BSLoad; 13325 if (N->getValueType(0) == MVT::i16) 13326 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13327 13328 // First, combine the bswap away. This makes the value produced by the 13329 // load dead. 13330 DCI.CombineTo(N, ResVal); 13331 13332 // Next, combine the load away, we give it a bogus result value but a real 13333 // chain result. The result value is dead because the bswap is dead. 13334 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13335 13336 // Return N so it doesn't get rechecked! 13337 return SDValue(N, 0); 13338 } 13339 break; 13340 case PPCISD::VCMP: 13341 // If a VCMPo node already exists with exactly the same operands as this 13342 // node, use its result instead of this node (VCMPo computes both a CR6 and 13343 // a normal output). 13344 // 13345 if (!N->getOperand(0).hasOneUse() && 13346 !N->getOperand(1).hasOneUse() && 13347 !N->getOperand(2).hasOneUse()) { 13348 13349 // Scan all of the users of the LHS, looking for VCMPo's that match. 13350 SDNode *VCMPoNode = nullptr; 13351 13352 SDNode *LHSN = N->getOperand(0).getNode(); 13353 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13354 UI != E; ++UI) 13355 if (UI->getOpcode() == PPCISD::VCMPo && 13356 UI->getOperand(1) == N->getOperand(1) && 13357 UI->getOperand(2) == N->getOperand(2) && 13358 UI->getOperand(0) == N->getOperand(0)) { 13359 VCMPoNode = *UI; 13360 break; 13361 } 13362 13363 // If there is no VCMPo node, or if the flag value has a single use, don't 13364 // transform this. 13365 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13366 break; 13367 13368 // Look at the (necessarily single) use of the flag value. If it has a 13369 // chain, this transformation is more complex. Note that multiple things 13370 // could use the value result, which we should ignore. 13371 SDNode *FlagUser = nullptr; 13372 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13373 FlagUser == nullptr; ++UI) { 13374 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13375 SDNode *User = *UI; 13376 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13377 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13378 FlagUser = User; 13379 break; 13380 } 13381 } 13382 } 13383 13384 // If the user is a MFOCRF instruction, we know this is safe. 13385 // Otherwise we give up for right now. 13386 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13387 return SDValue(VCMPoNode, 0); 13388 } 13389 break; 13390 case ISD::BRCOND: { 13391 SDValue Cond = N->getOperand(1); 13392 SDValue Target = N->getOperand(2); 13393 13394 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13395 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13396 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13397 13398 // We now need to make the intrinsic dead (it cannot be instruction 13399 // selected). 13400 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13401 assert(Cond.getNode()->hasOneUse() && 13402 "Counter decrement has more than one use"); 13403 13404 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13405 N->getOperand(0), Target); 13406 } 13407 } 13408 break; 13409 case ISD::BR_CC: { 13410 // If this is a branch on an altivec predicate comparison, lower this so 13411 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13412 // lowering is done pre-legalize, because the legalizer lowers the predicate 13413 // compare down to code that is difficult to reassemble. 13414 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13415 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13416 13417 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13418 // value. If so, pass-through the AND to get to the intrinsic. 13419 if (LHS.getOpcode() == ISD::AND && 13420 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13421 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13422 Intrinsic::ppc_is_decremented_ctr_nonzero && 13423 isa<ConstantSDNode>(LHS.getOperand(1)) && 13424 !isNullConstant(LHS.getOperand(1))) 13425 LHS = LHS.getOperand(0); 13426 13427 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13428 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13429 Intrinsic::ppc_is_decremented_ctr_nonzero && 13430 isa<ConstantSDNode>(RHS)) { 13431 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13432 "Counter decrement comparison is not EQ or NE"); 13433 13434 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13435 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13436 (CC == ISD::SETNE && !Val); 13437 13438 // We now need to make the intrinsic dead (it cannot be instruction 13439 // selected). 13440 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13441 assert(LHS.getNode()->hasOneUse() && 13442 "Counter decrement has more than one use"); 13443 13444 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13445 N->getOperand(0), N->getOperand(4)); 13446 } 13447 13448 int CompareOpc; 13449 bool isDot; 13450 13451 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13452 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13453 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13454 assert(isDot && "Can't compare against a vector result!"); 13455 13456 // If this is a comparison against something other than 0/1, then we know 13457 // that the condition is never/always true. 13458 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13459 if (Val != 0 && Val != 1) { 13460 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13461 return N->getOperand(0); 13462 // Always !=, turn it into an unconditional branch. 13463 return DAG.getNode(ISD::BR, dl, MVT::Other, 13464 N->getOperand(0), N->getOperand(4)); 13465 } 13466 13467 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13468 13469 // Create the PPCISD altivec 'dot' comparison node. 13470 SDValue Ops[] = { 13471 LHS.getOperand(2), // LHS of compare 13472 LHS.getOperand(3), // RHS of compare 13473 DAG.getConstant(CompareOpc, dl, MVT::i32) 13474 }; 13475 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13476 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13477 13478 // Unpack the result based on how the target uses it. 13479 PPC::Predicate CompOpc; 13480 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13481 default: // Can't happen, don't crash on invalid number though. 13482 case 0: // Branch on the value of the EQ bit of CR6. 13483 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13484 break; 13485 case 1: // Branch on the inverted value of the EQ bit of CR6. 13486 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13487 break; 13488 case 2: // Branch on the value of the LT bit of CR6. 13489 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13490 break; 13491 case 3: // Branch on the inverted value of the LT bit of CR6. 13492 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13493 break; 13494 } 13495 13496 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13497 DAG.getConstant(CompOpc, dl, MVT::i32), 13498 DAG.getRegister(PPC::CR6, MVT::i32), 13499 N->getOperand(4), CompNode.getValue(1)); 13500 } 13501 break; 13502 } 13503 case ISD::BUILD_VECTOR: 13504 return DAGCombineBuildVector(N, DCI); 13505 case ISD::ABS: 13506 return combineABS(N, DCI); 13507 case ISD::VSELECT: 13508 return combineVSelect(N, DCI); 13509 } 13510 13511 return SDValue(); 13512 } 13513 13514 SDValue 13515 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13516 SelectionDAG &DAG, 13517 SmallVectorImpl<SDNode *> &Created) const { 13518 // fold (sdiv X, pow2) 13519 EVT VT = N->getValueType(0); 13520 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13521 return SDValue(); 13522 if ((VT != MVT::i32 && VT != MVT::i64) || 13523 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13524 return SDValue(); 13525 13526 SDLoc DL(N); 13527 SDValue N0 = N->getOperand(0); 13528 13529 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13530 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13531 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13532 13533 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13534 Created.push_back(Op.getNode()); 13535 13536 if (IsNegPow2) { 13537 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13538 Created.push_back(Op.getNode()); 13539 } 13540 13541 return Op; 13542 } 13543 13544 //===----------------------------------------------------------------------===// 13545 // Inline Assembly Support 13546 //===----------------------------------------------------------------------===// 13547 13548 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13549 KnownBits &Known, 13550 const APInt &DemandedElts, 13551 const SelectionDAG &DAG, 13552 unsigned Depth) const { 13553 Known.resetAll(); 13554 switch (Op.getOpcode()) { 13555 default: break; 13556 case PPCISD::LBRX: { 13557 // lhbrx is known to have the top bits cleared out. 13558 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13559 Known.Zero = 0xFFFF0000; 13560 break; 13561 } 13562 case ISD::INTRINSIC_WO_CHAIN: { 13563 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13564 default: break; 13565 case Intrinsic::ppc_altivec_vcmpbfp_p: 13566 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13567 case Intrinsic::ppc_altivec_vcmpequb_p: 13568 case Intrinsic::ppc_altivec_vcmpequh_p: 13569 case Intrinsic::ppc_altivec_vcmpequw_p: 13570 case Intrinsic::ppc_altivec_vcmpequd_p: 13571 case Intrinsic::ppc_altivec_vcmpgefp_p: 13572 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13573 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13574 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13575 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13576 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13577 case Intrinsic::ppc_altivec_vcmpgtub_p: 13578 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13579 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13580 case Intrinsic::ppc_altivec_vcmpgtud_p: 13581 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13582 break; 13583 } 13584 } 13585 } 13586 } 13587 13588 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13589 switch (Subtarget.getDarwinDirective()) { 13590 default: break; 13591 case PPC::DIR_970: 13592 case PPC::DIR_PWR4: 13593 case PPC::DIR_PWR5: 13594 case PPC::DIR_PWR5X: 13595 case PPC::DIR_PWR6: 13596 case PPC::DIR_PWR6X: 13597 case PPC::DIR_PWR7: 13598 case PPC::DIR_PWR8: 13599 case PPC::DIR_PWR9: { 13600 if (!ML) 13601 break; 13602 13603 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13604 13605 // For small loops (between 5 and 8 instructions), align to a 32-byte 13606 // boundary so that the entire loop fits in one instruction-cache line. 13607 uint64_t LoopSize = 0; 13608 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13609 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13610 LoopSize += TII->getInstSizeInBytes(*J); 13611 if (LoopSize > 32) 13612 break; 13613 } 13614 13615 if (LoopSize > 16 && LoopSize <= 32) 13616 return 5; 13617 13618 break; 13619 } 13620 } 13621 13622 return TargetLowering::getPrefLoopAlignment(ML); 13623 } 13624 13625 /// getConstraintType - Given a constraint, return the type of 13626 /// constraint it is for this target. 13627 PPCTargetLowering::ConstraintType 13628 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13629 if (Constraint.size() == 1) { 13630 switch (Constraint[0]) { 13631 default: break; 13632 case 'b': 13633 case 'r': 13634 case 'f': 13635 case 'd': 13636 case 'v': 13637 case 'y': 13638 return C_RegisterClass; 13639 case 'Z': 13640 // FIXME: While Z does indicate a memory constraint, it specifically 13641 // indicates an r+r address (used in conjunction with the 'y' modifier 13642 // in the replacement string). Currently, we're forcing the base 13643 // register to be r0 in the asm printer (which is interpreted as zero) 13644 // and forming the complete address in the second register. This is 13645 // suboptimal. 13646 return C_Memory; 13647 } 13648 } else if (Constraint == "wc") { // individual CR bits. 13649 return C_RegisterClass; 13650 } else if (Constraint == "wa" || Constraint == "wd" || 13651 Constraint == "wf" || Constraint == "ws" || 13652 Constraint == "wi") { 13653 return C_RegisterClass; // VSX registers. 13654 } 13655 return TargetLowering::getConstraintType(Constraint); 13656 } 13657 13658 /// Examine constraint type and operand type and determine a weight value. 13659 /// This object must already have been set up with the operand type 13660 /// and the current alternative constraint selected. 13661 TargetLowering::ConstraintWeight 13662 PPCTargetLowering::getSingleConstraintMatchWeight( 13663 AsmOperandInfo &info, const char *constraint) const { 13664 ConstraintWeight weight = CW_Invalid; 13665 Value *CallOperandVal = info.CallOperandVal; 13666 // If we don't have a value, we can't do a match, 13667 // but allow it at the lowest weight. 13668 if (!CallOperandVal) 13669 return CW_Default; 13670 Type *type = CallOperandVal->getType(); 13671 13672 // Look at the constraint type. 13673 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13674 return CW_Register; // an individual CR bit. 13675 else if ((StringRef(constraint) == "wa" || 13676 StringRef(constraint) == "wd" || 13677 StringRef(constraint) == "wf") && 13678 type->isVectorTy()) 13679 return CW_Register; 13680 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13681 return CW_Register; 13682 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13683 return CW_Register; // just hold 64-bit integers data. 13684 13685 switch (*constraint) { 13686 default: 13687 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13688 break; 13689 case 'b': 13690 if (type->isIntegerTy()) 13691 weight = CW_Register; 13692 break; 13693 case 'f': 13694 if (type->isFloatTy()) 13695 weight = CW_Register; 13696 break; 13697 case 'd': 13698 if (type->isDoubleTy()) 13699 weight = CW_Register; 13700 break; 13701 case 'v': 13702 if (type->isVectorTy()) 13703 weight = CW_Register; 13704 break; 13705 case 'y': 13706 weight = CW_Register; 13707 break; 13708 case 'Z': 13709 weight = CW_Memory; 13710 break; 13711 } 13712 return weight; 13713 } 13714 13715 std::pair<unsigned, const TargetRegisterClass *> 13716 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13717 StringRef Constraint, 13718 MVT VT) const { 13719 if (Constraint.size() == 1) { 13720 // GCC RS6000 Constraint Letters 13721 switch (Constraint[0]) { 13722 case 'b': // R1-R31 13723 if (VT == MVT::i64 && Subtarget.isPPC64()) 13724 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13725 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13726 case 'r': // R0-R31 13727 if (VT == MVT::i64 && Subtarget.isPPC64()) 13728 return std::make_pair(0U, &PPC::G8RCRegClass); 13729 return std::make_pair(0U, &PPC::GPRCRegClass); 13730 // 'd' and 'f' constraints are both defined to be "the floating point 13731 // registers", where one is for 32-bit and the other for 64-bit. We don't 13732 // really care overly much here so just give them all the same reg classes. 13733 case 'd': 13734 case 'f': 13735 if (Subtarget.hasSPE()) { 13736 if (VT == MVT::f32 || VT == MVT::i32) 13737 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13738 if (VT == MVT::f64 || VT == MVT::i64) 13739 return std::make_pair(0U, &PPC::SPERCRegClass); 13740 } else { 13741 if (VT == MVT::f32 || VT == MVT::i32) 13742 return std::make_pair(0U, &PPC::F4RCRegClass); 13743 if (VT == MVT::f64 || VT == MVT::i64) 13744 return std::make_pair(0U, &PPC::F8RCRegClass); 13745 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13746 return std::make_pair(0U, &PPC::QFRCRegClass); 13747 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13748 return std::make_pair(0U, &PPC::QSRCRegClass); 13749 } 13750 break; 13751 case 'v': 13752 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13753 return std::make_pair(0U, &PPC::QFRCRegClass); 13754 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13755 return std::make_pair(0U, &PPC::QSRCRegClass); 13756 if (Subtarget.hasAltivec()) 13757 return std::make_pair(0U, &PPC::VRRCRegClass); 13758 break; 13759 case 'y': // crrc 13760 return std::make_pair(0U, &PPC::CRRCRegClass); 13761 } 13762 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13763 // An individual CR bit. 13764 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13765 } else if ((Constraint == "wa" || Constraint == "wd" || 13766 Constraint == "wf" || Constraint == "wi") && 13767 Subtarget.hasVSX()) { 13768 return std::make_pair(0U, &PPC::VSRCRegClass); 13769 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13770 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13771 return std::make_pair(0U, &PPC::VSSRCRegClass); 13772 else 13773 return std::make_pair(0U, &PPC::VSFRCRegClass); 13774 } 13775 13776 std::pair<unsigned, const TargetRegisterClass *> R = 13777 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13778 13779 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13780 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13781 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13782 // register. 13783 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13784 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13785 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13786 PPC::GPRCRegClass.contains(R.first)) 13787 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13788 PPC::sub_32, &PPC::G8RCRegClass), 13789 &PPC::G8RCRegClass); 13790 13791 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13792 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13793 R.first = PPC::CR0; 13794 R.second = &PPC::CRRCRegClass; 13795 } 13796 13797 return R; 13798 } 13799 13800 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13801 /// vector. If it is invalid, don't add anything to Ops. 13802 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13803 std::string &Constraint, 13804 std::vector<SDValue>&Ops, 13805 SelectionDAG &DAG) const { 13806 SDValue Result; 13807 13808 // Only support length 1 constraints. 13809 if (Constraint.length() > 1) return; 13810 13811 char Letter = Constraint[0]; 13812 switch (Letter) { 13813 default: break; 13814 case 'I': 13815 case 'J': 13816 case 'K': 13817 case 'L': 13818 case 'M': 13819 case 'N': 13820 case 'O': 13821 case 'P': { 13822 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13823 if (!CST) return; // Must be an immediate to match. 13824 SDLoc dl(Op); 13825 int64_t Value = CST->getSExtValue(); 13826 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13827 // numbers are printed as such. 13828 switch (Letter) { 13829 default: llvm_unreachable("Unknown constraint letter!"); 13830 case 'I': // "I" is a signed 16-bit constant. 13831 if (isInt<16>(Value)) 13832 Result = DAG.getTargetConstant(Value, dl, TCVT); 13833 break; 13834 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13835 if (isShiftedUInt<16, 16>(Value)) 13836 Result = DAG.getTargetConstant(Value, dl, TCVT); 13837 break; 13838 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13839 if (isShiftedInt<16, 16>(Value)) 13840 Result = DAG.getTargetConstant(Value, dl, TCVT); 13841 break; 13842 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13843 if (isUInt<16>(Value)) 13844 Result = DAG.getTargetConstant(Value, dl, TCVT); 13845 break; 13846 case 'M': // "M" is a constant that is greater than 31. 13847 if (Value > 31) 13848 Result = DAG.getTargetConstant(Value, dl, TCVT); 13849 break; 13850 case 'N': // "N" is a positive constant that is an exact power of two. 13851 if (Value > 0 && isPowerOf2_64(Value)) 13852 Result = DAG.getTargetConstant(Value, dl, TCVT); 13853 break; 13854 case 'O': // "O" is the constant zero. 13855 if (Value == 0) 13856 Result = DAG.getTargetConstant(Value, dl, TCVT); 13857 break; 13858 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13859 if (isInt<16>(-Value)) 13860 Result = DAG.getTargetConstant(Value, dl, TCVT); 13861 break; 13862 } 13863 break; 13864 } 13865 } 13866 13867 if (Result.getNode()) { 13868 Ops.push_back(Result); 13869 return; 13870 } 13871 13872 // Handle standard constraint letters. 13873 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13874 } 13875 13876 // isLegalAddressingMode - Return true if the addressing mode represented 13877 // by AM is legal for this target, for a load/store of the specified type. 13878 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13879 const AddrMode &AM, Type *Ty, 13880 unsigned AS, Instruction *I) const { 13881 // PPC does not allow r+i addressing modes for vectors! 13882 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13883 return false; 13884 13885 // PPC allows a sign-extended 16-bit immediate field. 13886 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13887 return false; 13888 13889 // No global is ever allowed as a base. 13890 if (AM.BaseGV) 13891 return false; 13892 13893 // PPC only support r+r, 13894 switch (AM.Scale) { 13895 case 0: // "r+i" or just "i", depending on HasBaseReg. 13896 break; 13897 case 1: 13898 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13899 return false; 13900 // Otherwise we have r+r or r+i. 13901 break; 13902 case 2: 13903 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13904 return false; 13905 // Allow 2*r as r+r. 13906 break; 13907 default: 13908 // No other scales are supported. 13909 return false; 13910 } 13911 13912 return true; 13913 } 13914 13915 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13916 SelectionDAG &DAG) const { 13917 MachineFunction &MF = DAG.getMachineFunction(); 13918 MachineFrameInfo &MFI = MF.getFrameInfo(); 13919 MFI.setReturnAddressIsTaken(true); 13920 13921 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13922 return SDValue(); 13923 13924 SDLoc dl(Op); 13925 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13926 13927 // Make sure the function does not optimize away the store of the RA to 13928 // the stack. 13929 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13930 FuncInfo->setLRStoreRequired(); 13931 bool isPPC64 = Subtarget.isPPC64(); 13932 auto PtrVT = getPointerTy(MF.getDataLayout()); 13933 13934 if (Depth > 0) { 13935 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13936 SDValue Offset = 13937 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13938 isPPC64 ? MVT::i64 : MVT::i32); 13939 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13940 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13941 MachinePointerInfo()); 13942 } 13943 13944 // Just load the return address off the stack. 13945 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13946 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13947 MachinePointerInfo()); 13948 } 13949 13950 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13951 SelectionDAG &DAG) const { 13952 SDLoc dl(Op); 13953 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13954 13955 MachineFunction &MF = DAG.getMachineFunction(); 13956 MachineFrameInfo &MFI = MF.getFrameInfo(); 13957 MFI.setFrameAddressIsTaken(true); 13958 13959 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13960 bool isPPC64 = PtrVT == MVT::i64; 13961 13962 // Naked functions never have a frame pointer, and so we use r1. For all 13963 // other functions, this decision must be delayed until during PEI. 13964 unsigned FrameReg; 13965 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13966 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13967 else 13968 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13969 13970 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13971 PtrVT); 13972 while (Depth--) 13973 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13974 FrameAddr, MachinePointerInfo()); 13975 return FrameAddr; 13976 } 13977 13978 // FIXME? Maybe this could be a TableGen attribute on some registers and 13979 // this table could be generated automatically from RegInfo. 13980 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13981 SelectionDAG &DAG) const { 13982 bool isPPC64 = Subtarget.isPPC64(); 13983 bool isDarwinABI = Subtarget.isDarwinABI(); 13984 13985 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13986 (!isPPC64 && VT != MVT::i32)) 13987 report_fatal_error("Invalid register global variable type"); 13988 13989 bool is64Bit = isPPC64 && VT == MVT::i64; 13990 unsigned Reg = StringSwitch<unsigned>(RegName) 13991 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13992 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13993 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13994 (is64Bit ? PPC::X13 : PPC::R13)) 13995 .Default(0); 13996 13997 if (Reg) 13998 return Reg; 13999 report_fatal_error("Invalid register name global variable"); 14000 } 14001 14002 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14003 // 32-bit SVR4 ABI access everything as got-indirect. 14004 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14005 return true; 14006 14007 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14008 // If it is small or large code model, module locals are accessed 14009 // indirectly by loading their address from .toc/.got. The difference 14010 // is that for large code model we have ADDISTocHa + LDtocL and for 14011 // small code model we simply have LDtoc. 14012 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14013 return true; 14014 14015 // JumpTable and BlockAddress are accessed as got-indirect. 14016 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14017 return true; 14018 14019 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14020 const GlobalValue *GV = G->getGlobal(); 14021 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14022 // The NLP flag indicates that a global access has to use an 14023 // extra indirection. 14024 if (GVFlags & PPCII::MO_NLP_FLAG) 14025 return true; 14026 } 14027 14028 return false; 14029 } 14030 14031 bool 14032 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14033 // The PowerPC target isn't yet aware of offsets. 14034 return false; 14035 } 14036 14037 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14038 const CallInst &I, 14039 MachineFunction &MF, 14040 unsigned Intrinsic) const { 14041 switch (Intrinsic) { 14042 case Intrinsic::ppc_qpx_qvlfd: 14043 case Intrinsic::ppc_qpx_qvlfs: 14044 case Intrinsic::ppc_qpx_qvlfcd: 14045 case Intrinsic::ppc_qpx_qvlfcs: 14046 case Intrinsic::ppc_qpx_qvlfiwa: 14047 case Intrinsic::ppc_qpx_qvlfiwz: 14048 case Intrinsic::ppc_altivec_lvx: 14049 case Intrinsic::ppc_altivec_lvxl: 14050 case Intrinsic::ppc_altivec_lvebx: 14051 case Intrinsic::ppc_altivec_lvehx: 14052 case Intrinsic::ppc_altivec_lvewx: 14053 case Intrinsic::ppc_vsx_lxvd2x: 14054 case Intrinsic::ppc_vsx_lxvw4x: { 14055 EVT VT; 14056 switch (Intrinsic) { 14057 case Intrinsic::ppc_altivec_lvebx: 14058 VT = MVT::i8; 14059 break; 14060 case Intrinsic::ppc_altivec_lvehx: 14061 VT = MVT::i16; 14062 break; 14063 case Intrinsic::ppc_altivec_lvewx: 14064 VT = MVT::i32; 14065 break; 14066 case Intrinsic::ppc_vsx_lxvd2x: 14067 VT = MVT::v2f64; 14068 break; 14069 case Intrinsic::ppc_qpx_qvlfd: 14070 VT = MVT::v4f64; 14071 break; 14072 case Intrinsic::ppc_qpx_qvlfs: 14073 VT = MVT::v4f32; 14074 break; 14075 case Intrinsic::ppc_qpx_qvlfcd: 14076 VT = MVT::v2f64; 14077 break; 14078 case Intrinsic::ppc_qpx_qvlfcs: 14079 VT = MVT::v2f32; 14080 break; 14081 default: 14082 VT = MVT::v4i32; 14083 break; 14084 } 14085 14086 Info.opc = ISD::INTRINSIC_W_CHAIN; 14087 Info.memVT = VT; 14088 Info.ptrVal = I.getArgOperand(0); 14089 Info.offset = -VT.getStoreSize()+1; 14090 Info.size = 2*VT.getStoreSize()-1; 14091 Info.align = 1; 14092 Info.flags = MachineMemOperand::MOLoad; 14093 return true; 14094 } 14095 case Intrinsic::ppc_qpx_qvlfda: 14096 case Intrinsic::ppc_qpx_qvlfsa: 14097 case Intrinsic::ppc_qpx_qvlfcda: 14098 case Intrinsic::ppc_qpx_qvlfcsa: 14099 case Intrinsic::ppc_qpx_qvlfiwaa: 14100 case Intrinsic::ppc_qpx_qvlfiwza: { 14101 EVT VT; 14102 switch (Intrinsic) { 14103 case Intrinsic::ppc_qpx_qvlfda: 14104 VT = MVT::v4f64; 14105 break; 14106 case Intrinsic::ppc_qpx_qvlfsa: 14107 VT = MVT::v4f32; 14108 break; 14109 case Intrinsic::ppc_qpx_qvlfcda: 14110 VT = MVT::v2f64; 14111 break; 14112 case Intrinsic::ppc_qpx_qvlfcsa: 14113 VT = MVT::v2f32; 14114 break; 14115 default: 14116 VT = MVT::v4i32; 14117 break; 14118 } 14119 14120 Info.opc = ISD::INTRINSIC_W_CHAIN; 14121 Info.memVT = VT; 14122 Info.ptrVal = I.getArgOperand(0); 14123 Info.offset = 0; 14124 Info.size = VT.getStoreSize(); 14125 Info.align = 1; 14126 Info.flags = MachineMemOperand::MOLoad; 14127 return true; 14128 } 14129 case Intrinsic::ppc_qpx_qvstfd: 14130 case Intrinsic::ppc_qpx_qvstfs: 14131 case Intrinsic::ppc_qpx_qvstfcd: 14132 case Intrinsic::ppc_qpx_qvstfcs: 14133 case Intrinsic::ppc_qpx_qvstfiw: 14134 case Intrinsic::ppc_altivec_stvx: 14135 case Intrinsic::ppc_altivec_stvxl: 14136 case Intrinsic::ppc_altivec_stvebx: 14137 case Intrinsic::ppc_altivec_stvehx: 14138 case Intrinsic::ppc_altivec_stvewx: 14139 case Intrinsic::ppc_vsx_stxvd2x: 14140 case Intrinsic::ppc_vsx_stxvw4x: { 14141 EVT VT; 14142 switch (Intrinsic) { 14143 case Intrinsic::ppc_altivec_stvebx: 14144 VT = MVT::i8; 14145 break; 14146 case Intrinsic::ppc_altivec_stvehx: 14147 VT = MVT::i16; 14148 break; 14149 case Intrinsic::ppc_altivec_stvewx: 14150 VT = MVT::i32; 14151 break; 14152 case Intrinsic::ppc_vsx_stxvd2x: 14153 VT = MVT::v2f64; 14154 break; 14155 case Intrinsic::ppc_qpx_qvstfd: 14156 VT = MVT::v4f64; 14157 break; 14158 case Intrinsic::ppc_qpx_qvstfs: 14159 VT = MVT::v4f32; 14160 break; 14161 case Intrinsic::ppc_qpx_qvstfcd: 14162 VT = MVT::v2f64; 14163 break; 14164 case Intrinsic::ppc_qpx_qvstfcs: 14165 VT = MVT::v2f32; 14166 break; 14167 default: 14168 VT = MVT::v4i32; 14169 break; 14170 } 14171 14172 Info.opc = ISD::INTRINSIC_VOID; 14173 Info.memVT = VT; 14174 Info.ptrVal = I.getArgOperand(1); 14175 Info.offset = -VT.getStoreSize()+1; 14176 Info.size = 2*VT.getStoreSize()-1; 14177 Info.align = 1; 14178 Info.flags = MachineMemOperand::MOStore; 14179 return true; 14180 } 14181 case Intrinsic::ppc_qpx_qvstfda: 14182 case Intrinsic::ppc_qpx_qvstfsa: 14183 case Intrinsic::ppc_qpx_qvstfcda: 14184 case Intrinsic::ppc_qpx_qvstfcsa: 14185 case Intrinsic::ppc_qpx_qvstfiwa: { 14186 EVT VT; 14187 switch (Intrinsic) { 14188 case Intrinsic::ppc_qpx_qvstfda: 14189 VT = MVT::v4f64; 14190 break; 14191 case Intrinsic::ppc_qpx_qvstfsa: 14192 VT = MVT::v4f32; 14193 break; 14194 case Intrinsic::ppc_qpx_qvstfcda: 14195 VT = MVT::v2f64; 14196 break; 14197 case Intrinsic::ppc_qpx_qvstfcsa: 14198 VT = MVT::v2f32; 14199 break; 14200 default: 14201 VT = MVT::v4i32; 14202 break; 14203 } 14204 14205 Info.opc = ISD::INTRINSIC_VOID; 14206 Info.memVT = VT; 14207 Info.ptrVal = I.getArgOperand(1); 14208 Info.offset = 0; 14209 Info.size = VT.getStoreSize(); 14210 Info.align = 1; 14211 Info.flags = MachineMemOperand::MOStore; 14212 return true; 14213 } 14214 default: 14215 break; 14216 } 14217 14218 return false; 14219 } 14220 14221 /// getOptimalMemOpType - Returns the target specific optimal type for load 14222 /// and store operations as a result of memset, memcpy, and memmove 14223 /// lowering. If DstAlign is zero that means it's safe to destination 14224 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14225 /// means there isn't a need to check it against alignment requirement, 14226 /// probably because the source does not need to be loaded. If 'IsMemset' is 14227 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14228 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14229 /// source is constant so it does not need to be loaded. 14230 /// It returns EVT::Other if the type should be determined using generic 14231 /// target-independent logic. 14232 EVT PPCTargetLowering::getOptimalMemOpType( 14233 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14234 bool ZeroMemset, bool MemcpyStrSrc, 14235 const AttributeList &FuncAttributes) const { 14236 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14237 // When expanding a memset, require at least two QPX instructions to cover 14238 // the cost of loading the value to be stored from the constant pool. 14239 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14240 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14241 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14242 return MVT::v4f64; 14243 } 14244 14245 // We should use Altivec/VSX loads and stores when available. For unaligned 14246 // addresses, unaligned VSX loads are only fast starting with the P8. 14247 if (Subtarget.hasAltivec() && Size >= 16 && 14248 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14249 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14250 return MVT::v4i32; 14251 } 14252 14253 if (Subtarget.isPPC64()) { 14254 return MVT::i64; 14255 } 14256 14257 return MVT::i32; 14258 } 14259 14260 /// Returns true if it is beneficial to convert a load of a constant 14261 /// to just the constant itself. 14262 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14263 Type *Ty) const { 14264 assert(Ty->isIntegerTy()); 14265 14266 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14267 return !(BitSize == 0 || BitSize > 64); 14268 } 14269 14270 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14271 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14272 return false; 14273 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14274 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14275 return NumBits1 == 64 && NumBits2 == 32; 14276 } 14277 14278 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14279 if (!VT1.isInteger() || !VT2.isInteger()) 14280 return false; 14281 unsigned NumBits1 = VT1.getSizeInBits(); 14282 unsigned NumBits2 = VT2.getSizeInBits(); 14283 return NumBits1 == 64 && NumBits2 == 32; 14284 } 14285 14286 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14287 // Generally speaking, zexts are not free, but they are free when they can be 14288 // folded with other operations. 14289 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14290 EVT MemVT = LD->getMemoryVT(); 14291 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14292 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14293 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14294 LD->getExtensionType() == ISD::ZEXTLOAD)) 14295 return true; 14296 } 14297 14298 // FIXME: Add other cases... 14299 // - 32-bit shifts with a zext to i64 14300 // - zext after ctlz, bswap, etc. 14301 // - zext after and by a constant mask 14302 14303 return TargetLowering::isZExtFree(Val, VT2); 14304 } 14305 14306 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14307 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14308 "invalid fpext types"); 14309 // Extending to float128 is not free. 14310 if (DestVT == MVT::f128) 14311 return false; 14312 return true; 14313 } 14314 14315 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14316 return isInt<16>(Imm) || isUInt<16>(Imm); 14317 } 14318 14319 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14320 return isInt<16>(Imm) || isUInt<16>(Imm); 14321 } 14322 14323 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14324 unsigned, 14325 unsigned, 14326 bool *Fast) const { 14327 if (DisablePPCUnaligned) 14328 return false; 14329 14330 // PowerPC supports unaligned memory access for simple non-vector types. 14331 // Although accessing unaligned addresses is not as efficient as accessing 14332 // aligned addresses, it is generally more efficient than manual expansion, 14333 // and generally only traps for software emulation when crossing page 14334 // boundaries. 14335 14336 if (!VT.isSimple()) 14337 return false; 14338 14339 if (VT.getSimpleVT().isVector()) { 14340 if (Subtarget.hasVSX()) { 14341 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14342 VT != MVT::v4f32 && VT != MVT::v4i32) 14343 return false; 14344 } else { 14345 return false; 14346 } 14347 } 14348 14349 if (VT == MVT::ppcf128) 14350 return false; 14351 14352 if (Fast) 14353 *Fast = true; 14354 14355 return true; 14356 } 14357 14358 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14359 VT = VT.getScalarType(); 14360 14361 if (!VT.isSimple()) 14362 return false; 14363 14364 switch (VT.getSimpleVT().SimpleTy) { 14365 case MVT::f32: 14366 case MVT::f64: 14367 return true; 14368 case MVT::f128: 14369 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14370 default: 14371 break; 14372 } 14373 14374 return false; 14375 } 14376 14377 const MCPhysReg * 14378 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14379 // LR is a callee-save register, but we must treat it as clobbered by any call 14380 // site. Hence we include LR in the scratch registers, which are in turn added 14381 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14382 // to CTR, which is used by any indirect call. 14383 static const MCPhysReg ScratchRegs[] = { 14384 PPC::X12, PPC::LR8, PPC::CTR8, 0 14385 }; 14386 14387 return ScratchRegs; 14388 } 14389 14390 unsigned PPCTargetLowering::getExceptionPointerRegister( 14391 const Constant *PersonalityFn) const { 14392 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14393 } 14394 14395 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14396 const Constant *PersonalityFn) const { 14397 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14398 } 14399 14400 bool 14401 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14402 EVT VT , unsigned DefinedValues) const { 14403 if (VT == MVT::v2i64) 14404 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14405 14406 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14407 return true; 14408 14409 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14410 } 14411 14412 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14413 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14414 return TargetLowering::getSchedulingPreference(N); 14415 14416 return Sched::ILP; 14417 } 14418 14419 // Create a fast isel object. 14420 FastISel * 14421 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14422 const TargetLibraryInfo *LibInfo) const { 14423 return PPC::createFastISel(FuncInfo, LibInfo); 14424 } 14425 14426 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14427 if (Subtarget.isDarwinABI()) return; 14428 if (!Subtarget.isPPC64()) return; 14429 14430 // Update IsSplitCSR in PPCFunctionInfo 14431 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14432 PFI->setIsSplitCSR(true); 14433 } 14434 14435 void PPCTargetLowering::insertCopiesSplitCSR( 14436 MachineBasicBlock *Entry, 14437 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14438 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14439 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14440 if (!IStart) 14441 return; 14442 14443 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14444 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14445 MachineBasicBlock::iterator MBBI = Entry->begin(); 14446 for (const MCPhysReg *I = IStart; *I; ++I) { 14447 const TargetRegisterClass *RC = nullptr; 14448 if (PPC::G8RCRegClass.contains(*I)) 14449 RC = &PPC::G8RCRegClass; 14450 else if (PPC::F8RCRegClass.contains(*I)) 14451 RC = &PPC::F8RCRegClass; 14452 else if (PPC::CRRCRegClass.contains(*I)) 14453 RC = &PPC::CRRCRegClass; 14454 else if (PPC::VRRCRegClass.contains(*I)) 14455 RC = &PPC::VRRCRegClass; 14456 else 14457 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14458 14459 unsigned NewVR = MRI->createVirtualRegister(RC); 14460 // Create copy from CSR to a virtual register. 14461 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14462 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14463 // nounwind. If we want to generalize this later, we may need to emit 14464 // CFI pseudo-instructions. 14465 assert(Entry->getParent()->getFunction().hasFnAttribute( 14466 Attribute::NoUnwind) && 14467 "Function should be nounwind in insertCopiesSplitCSR!"); 14468 Entry->addLiveIn(*I); 14469 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14470 .addReg(*I); 14471 14472 // Insert the copy-back instructions right before the terminator. 14473 for (auto *Exit : Exits) 14474 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14475 TII->get(TargetOpcode::COPY), *I) 14476 .addReg(NewVR); 14477 } 14478 } 14479 14480 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14481 bool PPCTargetLowering::useLoadStackGuardNode() const { 14482 if (!Subtarget.isTargetLinux()) 14483 return TargetLowering::useLoadStackGuardNode(); 14484 return true; 14485 } 14486 14487 // Override to disable global variable loading on Linux. 14488 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14489 if (!Subtarget.isTargetLinux()) 14490 return TargetLowering::insertSSPDeclarations(M); 14491 } 14492 14493 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14494 bool ForCodeSize) const { 14495 if (!VT.isSimple() || !Subtarget.hasVSX()) 14496 return false; 14497 14498 switch(VT.getSimpleVT().SimpleTy) { 14499 default: 14500 // For FP types that are currently not supported by PPC backend, return 14501 // false. Examples: f16, f80. 14502 return false; 14503 case MVT::f32: 14504 case MVT::f64: 14505 case MVT::ppcf128: 14506 return Imm.isPosZero(); 14507 } 14508 } 14509 14510 // For vector shift operation op, fold 14511 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14512 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14513 SelectionDAG &DAG) { 14514 SDValue N0 = N->getOperand(0); 14515 SDValue N1 = N->getOperand(1); 14516 EVT VT = N0.getValueType(); 14517 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14518 unsigned Opcode = N->getOpcode(); 14519 unsigned TargetOpcode; 14520 14521 switch (Opcode) { 14522 default: 14523 llvm_unreachable("Unexpected shift operation"); 14524 case ISD::SHL: 14525 TargetOpcode = PPCISD::SHL; 14526 break; 14527 case ISD::SRL: 14528 TargetOpcode = PPCISD::SRL; 14529 break; 14530 case ISD::SRA: 14531 TargetOpcode = PPCISD::SRA; 14532 break; 14533 } 14534 14535 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14536 N1->getOpcode() == ISD::AND) 14537 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14538 if (Mask->getZExtValue() == OpSizeInBits - 1) 14539 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14540 14541 return SDValue(); 14542 } 14543 14544 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14545 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14546 return Value; 14547 14548 SDValue N0 = N->getOperand(0); 14549 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14550 if (!Subtarget.isISA3_0() || 14551 N0.getOpcode() != ISD::SIGN_EXTEND || 14552 N0.getOperand(0).getValueType() != MVT::i32 || 14553 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14554 return SDValue(); 14555 14556 // We can't save an operation here if the value is already extended, and 14557 // the existing shift is easier to combine. 14558 SDValue ExtsSrc = N0.getOperand(0); 14559 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14560 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14561 return SDValue(); 14562 14563 SDLoc DL(N0); 14564 SDValue ShiftBy = SDValue(CN1, 0); 14565 // We want the shift amount to be i32 on the extswli, but the shift could 14566 // have an i64. 14567 if (ShiftBy.getValueType() == MVT::i64) 14568 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14569 14570 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14571 ShiftBy); 14572 } 14573 14574 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14575 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14576 return Value; 14577 14578 return SDValue(); 14579 } 14580 14581 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14582 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14583 return Value; 14584 14585 return SDValue(); 14586 } 14587 14588 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14589 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14590 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14591 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14592 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14593 const PPCSubtarget &Subtarget) { 14594 if (!Subtarget.isPPC64()) 14595 return SDValue(); 14596 14597 SDValue LHS = N->getOperand(0); 14598 SDValue RHS = N->getOperand(1); 14599 14600 auto isZextOfCompareWithConstant = [](SDValue Op) { 14601 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14602 Op.getValueType() != MVT::i64) 14603 return false; 14604 14605 SDValue Cmp = Op.getOperand(0); 14606 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14607 Cmp.getOperand(0).getValueType() != MVT::i64) 14608 return false; 14609 14610 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14611 int64_t NegConstant = 0 - Constant->getSExtValue(); 14612 // Due to the limitations of the addi instruction, 14613 // -C is required to be [-32768, 32767]. 14614 return isInt<16>(NegConstant); 14615 } 14616 14617 return false; 14618 }; 14619 14620 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14621 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14622 14623 // If there is a pattern, canonicalize a zext operand to the RHS. 14624 if (LHSHasPattern && !RHSHasPattern) 14625 std::swap(LHS, RHS); 14626 else if (!LHSHasPattern && !RHSHasPattern) 14627 return SDValue(); 14628 14629 SDLoc DL(N); 14630 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14631 SDValue Cmp = RHS.getOperand(0); 14632 SDValue Z = Cmp.getOperand(0); 14633 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14634 14635 assert(Constant && "Constant Should not be a null pointer."); 14636 int64_t NegConstant = 0 - Constant->getSExtValue(); 14637 14638 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14639 default: break; 14640 case ISD::SETNE: { 14641 // when C == 0 14642 // --> addze X, (addic Z, -1).carry 14643 // / 14644 // add X, (zext(setne Z, C))-- 14645 // \ when -32768 <= -C <= 32767 && C != 0 14646 // --> addze X, (addic (addi Z, -C), -1).carry 14647 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14648 DAG.getConstant(NegConstant, DL, MVT::i64)); 14649 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14650 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14651 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14652 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14653 SDValue(Addc.getNode(), 1)); 14654 } 14655 case ISD::SETEQ: { 14656 // when C == 0 14657 // --> addze X, (subfic Z, 0).carry 14658 // / 14659 // add X, (zext(sete Z, C))-- 14660 // \ when -32768 <= -C <= 32767 && C != 0 14661 // --> addze X, (subfic (addi Z, -C), 0).carry 14662 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14663 DAG.getConstant(NegConstant, DL, MVT::i64)); 14664 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14665 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14666 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14667 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14668 SDValue(Subc.getNode(), 1)); 14669 } 14670 } 14671 14672 return SDValue(); 14673 } 14674 14675 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14676 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14677 return Value; 14678 14679 return SDValue(); 14680 } 14681 14682 // Detect TRUNCATE operations on bitcasts of float128 values. 14683 // What we are looking for here is the situtation where we extract a subset 14684 // of bits from a 128 bit float. 14685 // This can be of two forms: 14686 // 1) BITCAST of f128 feeding TRUNCATE 14687 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14688 // The reason this is required is because we do not have a legal i128 type 14689 // and so we want to prevent having to store the f128 and then reload part 14690 // of it. 14691 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14692 DAGCombinerInfo &DCI) const { 14693 // If we are using CRBits then try that first. 14694 if (Subtarget.useCRBits()) { 14695 // Check if CRBits did anything and return that if it did. 14696 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14697 return CRTruncValue; 14698 } 14699 14700 SDLoc dl(N); 14701 SDValue Op0 = N->getOperand(0); 14702 14703 // Looking for a truncate of i128 to i64. 14704 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14705 return SDValue(); 14706 14707 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14708 14709 // SRL feeding TRUNCATE. 14710 if (Op0.getOpcode() == ISD::SRL) { 14711 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14712 // The right shift has to be by 64 bits. 14713 if (!ConstNode || ConstNode->getZExtValue() != 64) 14714 return SDValue(); 14715 14716 // Switch the element number to extract. 14717 EltToExtract = EltToExtract ? 0 : 1; 14718 // Update Op0 past the SRL. 14719 Op0 = Op0.getOperand(0); 14720 } 14721 14722 // BITCAST feeding a TRUNCATE possibly via SRL. 14723 if (Op0.getOpcode() == ISD::BITCAST && 14724 Op0.getValueType() == MVT::i128 && 14725 Op0.getOperand(0).getValueType() == MVT::f128) { 14726 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14727 return DCI.DAG.getNode( 14728 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14729 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14730 } 14731 return SDValue(); 14732 } 14733 14734 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 14735 SelectionDAG &DAG = DCI.DAG; 14736 14737 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 14738 if (!ConstOpOrElement) 14739 return SDValue(); 14740 14741 // An imul is usually smaller than the alternative sequence for legal type. 14742 if (DAG.getMachineFunction().getFunction().hasMinSize() && 14743 isOperationLegal(ISD::MUL, N->getValueType(0))) 14744 return SDValue(); 14745 14746 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 14747 switch (this->Subtarget.getDarwinDirective()) { 14748 default: 14749 // TODO: enhance the condition for subtarget before pwr8 14750 return false; 14751 case PPC::DIR_PWR8: 14752 // type mul add shl 14753 // scalar 4 1 1 14754 // vector 7 2 2 14755 return true; 14756 case PPC::DIR_PWR9: 14757 // type mul add shl 14758 // scalar 5 2 2 14759 // vector 7 2 2 14760 14761 // The cycle RATIO of related operations are showed as a table above. 14762 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 14763 // scalar and vector type. For 2 instrs patterns, add/sub + shl 14764 // are 4, it is always profitable; but for 3 instrs patterns 14765 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 14766 // So we should only do it for vector type. 14767 return IsAddOne && IsNeg ? VT.isVector() : true; 14768 } 14769 }; 14770 14771 EVT VT = N->getValueType(0); 14772 SDLoc DL(N); 14773 14774 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 14775 bool IsNeg = MulAmt.isNegative(); 14776 APInt MulAmtAbs = MulAmt.abs(); 14777 14778 if ((MulAmtAbs - 1).isPowerOf2()) { 14779 // (mul x, 2^N + 1) => (add (shl x, N), x) 14780 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 14781 14782 if (!IsProfitable(IsNeg, true, VT)) 14783 return SDValue(); 14784 14785 SDValue Op0 = N->getOperand(0); 14786 SDValue Op1 = 14787 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14788 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 14789 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 14790 14791 if (!IsNeg) 14792 return Res; 14793 14794 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 14795 } else if ((MulAmtAbs + 1).isPowerOf2()) { 14796 // (mul x, 2^N - 1) => (sub (shl x, N), x) 14797 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 14798 14799 if (!IsProfitable(IsNeg, false, VT)) 14800 return SDValue(); 14801 14802 SDValue Op0 = N->getOperand(0); 14803 SDValue Op1 = 14804 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14805 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 14806 14807 if (!IsNeg) 14808 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 14809 else 14810 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 14811 14812 } else { 14813 return SDValue(); 14814 } 14815 } 14816 14817 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14818 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14819 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14820 return false; 14821 14822 // If not a tail call then no need to proceed. 14823 if (!CI->isTailCall()) 14824 return false; 14825 14826 // If tail calls are disabled for the caller then we are done. 14827 const Function *Caller = CI->getParent()->getParent(); 14828 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14829 if (Attr.getValueAsString() == "true") 14830 return false; 14831 14832 // If sibling calls have been disabled and tail-calls aren't guaranteed 14833 // there is no reason to duplicate. 14834 auto &TM = getTargetMachine(); 14835 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14836 return false; 14837 14838 // Can't tail call a function called indirectly, or if it has variadic args. 14839 const Function *Callee = CI->getCalledFunction(); 14840 if (!Callee || Callee->isVarArg()) 14841 return false; 14842 14843 // Make sure the callee and caller calling conventions are eligible for tco. 14844 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14845 CI->getCallingConv())) 14846 return false; 14847 14848 // If the function is local then we have a good chance at tail-calling it 14849 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14850 } 14851 14852 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14853 if (!Subtarget.hasVSX()) 14854 return false; 14855 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14856 return true; 14857 return VT == MVT::f32 || VT == MVT::f64 || 14858 VT == MVT::v4f32 || VT == MVT::v2f64; 14859 } 14860 14861 bool PPCTargetLowering:: 14862 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14863 const Value *Mask = AndI.getOperand(1); 14864 // If the mask is suitable for andi. or andis. we should sink the and. 14865 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14866 // Can't handle constants wider than 64-bits. 14867 if (CI->getBitWidth() > 64) 14868 return false; 14869 int64_t ConstVal = CI->getZExtValue(); 14870 return isUInt<16>(ConstVal) || 14871 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14872 } 14873 14874 // For non-constant masks, we can always use the record-form and. 14875 return true; 14876 } 14877 14878 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 14879 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 14880 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 14881 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 14882 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 14883 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 14884 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 14885 assert(Subtarget.hasP9Altivec() && 14886 "Only combine this when P9 altivec supported!"); 14887 EVT VT = N->getValueType(0); 14888 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14889 return SDValue(); 14890 14891 SelectionDAG &DAG = DCI.DAG; 14892 SDLoc dl(N); 14893 if (N->getOperand(0).getOpcode() == ISD::SUB) { 14894 // Even for signed integers, if it's known to be positive (as signed 14895 // integer) due to zero-extended inputs. 14896 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 14897 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 14898 if ((SubOpcd0 == ISD::ZERO_EXTEND || 14899 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 14900 (SubOpcd1 == ISD::ZERO_EXTEND || 14901 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 14902 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14903 N->getOperand(0)->getOperand(0), 14904 N->getOperand(0)->getOperand(1), 14905 DAG.getTargetConstant(0, dl, MVT::i32)); 14906 } 14907 14908 // For type v4i32, it can be optimized with xvnegsp + vabsduw 14909 if (N->getOperand(0).getValueType() == MVT::v4i32 && 14910 N->getOperand(0).hasOneUse()) { 14911 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14912 N->getOperand(0)->getOperand(0), 14913 N->getOperand(0)->getOperand(1), 14914 DAG.getTargetConstant(1, dl, MVT::i32)); 14915 } 14916 } 14917 14918 return SDValue(); 14919 } 14920 14921 // For type v4i32/v8ii16/v16i8, transform 14922 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 14923 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 14924 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 14925 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 14926 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 14927 DAGCombinerInfo &DCI) const { 14928 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 14929 assert(Subtarget.hasP9Altivec() && 14930 "Only combine this when P9 altivec supported!"); 14931 14932 SelectionDAG &DAG = DCI.DAG; 14933 SDLoc dl(N); 14934 SDValue Cond = N->getOperand(0); 14935 SDValue TrueOpnd = N->getOperand(1); 14936 SDValue FalseOpnd = N->getOperand(2); 14937 EVT VT = N->getOperand(1).getValueType(); 14938 14939 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 14940 FalseOpnd.getOpcode() != ISD::SUB) 14941 return SDValue(); 14942 14943 // ABSD only available for type v4i32/v8i16/v16i8 14944 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14945 return SDValue(); 14946 14947 // At least to save one more dependent computation 14948 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 14949 return SDValue(); 14950 14951 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14952 14953 // Can only handle unsigned comparison here 14954 switch (CC) { 14955 default: 14956 return SDValue(); 14957 case ISD::SETUGT: 14958 case ISD::SETUGE: 14959 break; 14960 case ISD::SETULT: 14961 case ISD::SETULE: 14962 std::swap(TrueOpnd, FalseOpnd); 14963 break; 14964 } 14965 14966 SDValue CmpOpnd1 = Cond.getOperand(0); 14967 SDValue CmpOpnd2 = Cond.getOperand(1); 14968 14969 // SETCC CmpOpnd1 CmpOpnd2 cond 14970 // TrueOpnd = CmpOpnd1 - CmpOpnd2 14971 // FalseOpnd = CmpOpnd2 - CmpOpnd1 14972 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 14973 TrueOpnd.getOperand(1) == CmpOpnd2 && 14974 FalseOpnd.getOperand(0) == CmpOpnd2 && 14975 FalseOpnd.getOperand(1) == CmpOpnd1) { 14976 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 14977 CmpOpnd1, CmpOpnd2, 14978 DAG.getTargetConstant(0, dl, MVT::i32)); 14979 } 14980 14981 return SDValue(); 14982 } 14983