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) { 2432 if (!N->hasOneUse()) 2433 return false; 2434 2435 // If there are any other uses other than scalar to vector, then we should 2436 // keep it as a scalar load -> direct move pattern to prevent multiple 2437 // loads. Currently, only check for i64 since we have lxsd/lfd to do this 2438 // efficiently, but no update equivalent. 2439 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2440 EVT MemVT = LD->getMemoryVT(); 2441 if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) { 2442 SDNode *User = *(LD->use_begin()); 2443 if (User->getOpcode() == ISD::SCALAR_TO_VECTOR) 2444 return true; 2445 } 2446 } 2447 2448 return false; 2449 } 2450 2451 /// getPreIndexedAddressParts - returns true by value, base pointer and 2452 /// offset pointer and addressing mode by reference if the node's address 2453 /// can be legally represented as pre-indexed load / store address. 2454 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2455 SDValue &Offset, 2456 ISD::MemIndexedMode &AM, 2457 SelectionDAG &DAG) const { 2458 if (DisablePPCPreinc) return false; 2459 2460 bool isLoad = true; 2461 SDValue Ptr; 2462 EVT VT; 2463 unsigned Alignment; 2464 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2465 Ptr = LD->getBasePtr(); 2466 VT = LD->getMemoryVT(); 2467 Alignment = LD->getAlignment(); 2468 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2469 Ptr = ST->getBasePtr(); 2470 VT = ST->getMemoryVT(); 2471 Alignment = ST->getAlignment(); 2472 isLoad = false; 2473 } else 2474 return false; 2475 2476 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2477 // instructions because we can fold these into a more efficient instruction 2478 // instead, (such as LXSD). 2479 if (isLoad && usePartialVectorLoads(N)) { 2480 return false; 2481 } 2482 2483 // PowerPC doesn't have preinc load/store instructions for vectors (except 2484 // for QPX, which does have preinc r+r forms). 2485 if (VT.isVector()) { 2486 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2487 return false; 2488 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2489 AM = ISD::PRE_INC; 2490 return true; 2491 } 2492 } 2493 2494 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2495 // Common code will reject creating a pre-inc form if the base pointer 2496 // is a frame index, or if N is a store and the base pointer is either 2497 // the same as or a predecessor of the value being stored. Check for 2498 // those situations here, and try with swapped Base/Offset instead. 2499 bool Swap = false; 2500 2501 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2502 Swap = true; 2503 else if (!isLoad) { 2504 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2505 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2506 Swap = true; 2507 } 2508 2509 if (Swap) 2510 std::swap(Base, Offset); 2511 2512 AM = ISD::PRE_INC; 2513 return true; 2514 } 2515 2516 // LDU/STU can only handle immediates that are a multiple of 4. 2517 if (VT != MVT::i64) { 2518 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2519 return false; 2520 } else { 2521 // LDU/STU need an address with at least 4-byte alignment. 2522 if (Alignment < 4) 2523 return false; 2524 2525 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2526 return false; 2527 } 2528 2529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2530 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2531 // sext i32 to i64 when addr mode is r+i. 2532 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2533 LD->getExtensionType() == ISD::SEXTLOAD && 2534 isa<ConstantSDNode>(Offset)) 2535 return false; 2536 } 2537 2538 AM = ISD::PRE_INC; 2539 return true; 2540 } 2541 2542 //===----------------------------------------------------------------------===// 2543 // LowerOperation implementation 2544 //===----------------------------------------------------------------------===// 2545 2546 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2547 /// and LoOpFlags to the target MO flags. 2548 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2549 unsigned &HiOpFlags, unsigned &LoOpFlags, 2550 const GlobalValue *GV = nullptr) { 2551 HiOpFlags = PPCII::MO_HA; 2552 LoOpFlags = PPCII::MO_LO; 2553 2554 // Don't use the pic base if not in PIC relocation model. 2555 if (IsPIC) { 2556 HiOpFlags |= PPCII::MO_PIC_FLAG; 2557 LoOpFlags |= PPCII::MO_PIC_FLAG; 2558 } 2559 2560 // If this is a reference to a global value that requires a non-lazy-ptr, make 2561 // sure that instruction lowering adds it. 2562 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2563 HiOpFlags |= PPCII::MO_NLP_FLAG; 2564 LoOpFlags |= PPCII::MO_NLP_FLAG; 2565 2566 if (GV->hasHiddenVisibility()) { 2567 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2568 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2569 } 2570 } 2571 } 2572 2573 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2574 SelectionDAG &DAG) { 2575 SDLoc DL(HiPart); 2576 EVT PtrVT = HiPart.getValueType(); 2577 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2578 2579 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2580 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2581 2582 // With PIC, the first instruction is actually "GR+hi(&G)". 2583 if (isPIC) 2584 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2585 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2586 2587 // Generate non-pic code that has direct accesses to the constant pool. 2588 // The address of the global is just (hi(&g)+lo(&g)). 2589 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2590 } 2591 2592 static void setUsesTOCBasePtr(MachineFunction &MF) { 2593 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2594 FuncInfo->setUsesTOCBasePtr(); 2595 } 2596 2597 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2598 setUsesTOCBasePtr(DAG.getMachineFunction()); 2599 } 2600 2601 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2602 SDValue GA) { 2603 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2604 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2605 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2606 2607 SDValue Ops[] = { GA, Reg }; 2608 return DAG.getMemIntrinsicNode( 2609 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2610 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2611 MachineMemOperand::MOLoad); 2612 } 2613 2614 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2615 SelectionDAG &DAG) const { 2616 EVT PtrVT = Op.getValueType(); 2617 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2618 const Constant *C = CP->getConstVal(); 2619 2620 // 64-bit SVR4 ABI code is always position-independent. 2621 // The actual address of the GlobalValue is stored in the TOC. 2622 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2623 setUsesTOCBasePtr(DAG); 2624 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2625 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2626 } 2627 2628 unsigned MOHiFlag, MOLoFlag; 2629 bool IsPIC = isPositionIndependent(); 2630 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2631 2632 if (IsPIC && Subtarget.isSVR4ABI()) { 2633 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2634 PPCII::MO_PIC_FLAG); 2635 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2636 } 2637 2638 SDValue CPIHi = 2639 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2640 SDValue CPILo = 2641 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2642 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2643 } 2644 2645 // For 64-bit PowerPC, prefer the more compact relative encodings. 2646 // This trades 32 bits per jump table entry for one or two instructions 2647 // on the jump site. 2648 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2649 if (isJumpTableRelative()) 2650 return MachineJumpTableInfo::EK_LabelDifference32; 2651 2652 return TargetLowering::getJumpTableEncoding(); 2653 } 2654 2655 bool PPCTargetLowering::isJumpTableRelative() const { 2656 if (Subtarget.isPPC64()) 2657 return true; 2658 return TargetLowering::isJumpTableRelative(); 2659 } 2660 2661 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2662 SelectionDAG &DAG) const { 2663 if (!Subtarget.isPPC64()) 2664 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2665 2666 switch (getTargetMachine().getCodeModel()) { 2667 case CodeModel::Small: 2668 case CodeModel::Medium: 2669 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2670 default: 2671 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2672 getPointerTy(DAG.getDataLayout())); 2673 } 2674 } 2675 2676 const MCExpr * 2677 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2678 unsigned JTI, 2679 MCContext &Ctx) const { 2680 if (!Subtarget.isPPC64()) 2681 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2682 2683 switch (getTargetMachine().getCodeModel()) { 2684 case CodeModel::Small: 2685 case CodeModel::Medium: 2686 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2687 default: 2688 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2689 } 2690 } 2691 2692 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2693 EVT PtrVT = Op.getValueType(); 2694 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2695 2696 // 64-bit SVR4 ABI code is always position-independent. 2697 // The actual address of the GlobalValue is stored in the TOC. 2698 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2699 setUsesTOCBasePtr(DAG); 2700 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2701 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2702 } 2703 2704 unsigned MOHiFlag, MOLoFlag; 2705 bool IsPIC = isPositionIndependent(); 2706 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2707 2708 if (IsPIC && Subtarget.isSVR4ABI()) { 2709 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2710 PPCII::MO_PIC_FLAG); 2711 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2712 } 2713 2714 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2715 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2716 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2717 } 2718 2719 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2720 SelectionDAG &DAG) const { 2721 EVT PtrVT = Op.getValueType(); 2722 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2723 const BlockAddress *BA = BASDN->getBlockAddress(); 2724 2725 // 64-bit SVR4 ABI code is always position-independent. 2726 // The actual BlockAddress is stored in the TOC. 2727 if (Subtarget.isSVR4ABI() && 2728 (Subtarget.isPPC64() || isPositionIndependent())) { 2729 if (Subtarget.isPPC64()) 2730 setUsesTOCBasePtr(DAG); 2731 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2732 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2733 } 2734 2735 unsigned MOHiFlag, MOLoFlag; 2736 bool IsPIC = isPositionIndependent(); 2737 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2738 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2739 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2740 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2741 } 2742 2743 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2744 SelectionDAG &DAG) const { 2745 // FIXME: TLS addresses currently use medium model code sequences, 2746 // which is the most useful form. Eventually support for small and 2747 // large models could be added if users need it, at the cost of 2748 // additional complexity. 2749 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2750 if (DAG.getTarget().useEmulatedTLS()) 2751 return LowerToTLSEmulatedModel(GA, DAG); 2752 2753 SDLoc dl(GA); 2754 const GlobalValue *GV = GA->getGlobal(); 2755 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2756 bool is64bit = Subtarget.isPPC64(); 2757 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2758 PICLevel::Level picLevel = M->getPICLevel(); 2759 2760 const TargetMachine &TM = getTargetMachine(); 2761 TLSModel::Model Model = TM.getTLSModel(GV); 2762 2763 if (Model == TLSModel::LocalExec) { 2764 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2765 PPCII::MO_TPREL_HA); 2766 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2767 PPCII::MO_TPREL_LO); 2768 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2769 : DAG.getRegister(PPC::R2, MVT::i32); 2770 2771 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2772 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2773 } 2774 2775 if (Model == TLSModel::InitialExec) { 2776 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2777 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2778 PPCII::MO_TLS); 2779 SDValue GOTPtr; 2780 if (is64bit) { 2781 setUsesTOCBasePtr(DAG); 2782 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2783 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2784 PtrVT, GOTReg, TGA); 2785 } else { 2786 if (!TM.isPositionIndependent()) 2787 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2788 else if (picLevel == PICLevel::SmallPIC) 2789 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2790 else 2791 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2792 } 2793 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2794 PtrVT, TGA, GOTPtr); 2795 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2796 } 2797 2798 if (Model == TLSModel::GeneralDynamic) { 2799 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2800 SDValue GOTPtr; 2801 if (is64bit) { 2802 setUsesTOCBasePtr(DAG); 2803 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2804 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2805 GOTReg, TGA); 2806 } else { 2807 if (picLevel == PICLevel::SmallPIC) 2808 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2809 else 2810 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2811 } 2812 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2813 GOTPtr, TGA, TGA); 2814 } 2815 2816 if (Model == TLSModel::LocalDynamic) { 2817 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2818 SDValue GOTPtr; 2819 if (is64bit) { 2820 setUsesTOCBasePtr(DAG); 2821 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2822 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2823 GOTReg, TGA); 2824 } else { 2825 if (picLevel == PICLevel::SmallPIC) 2826 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2827 else 2828 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2829 } 2830 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2831 PtrVT, GOTPtr, TGA, TGA); 2832 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2833 PtrVT, TLSAddr, TGA); 2834 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2835 } 2836 2837 llvm_unreachable("Unknown TLS model!"); 2838 } 2839 2840 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2841 SelectionDAG &DAG) const { 2842 EVT PtrVT = Op.getValueType(); 2843 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2844 SDLoc DL(GSDN); 2845 const GlobalValue *GV = GSDN->getGlobal(); 2846 2847 // 64-bit SVR4 ABI code is always position-independent. 2848 // The actual address of the GlobalValue is stored in the TOC. 2849 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2850 setUsesTOCBasePtr(DAG); 2851 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2852 return getTOCEntry(DAG, DL, true, GA); 2853 } 2854 2855 unsigned MOHiFlag, MOLoFlag; 2856 bool IsPIC = isPositionIndependent(); 2857 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2858 2859 if (IsPIC && Subtarget.isSVR4ABI()) { 2860 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2861 GSDN->getOffset(), 2862 PPCII::MO_PIC_FLAG); 2863 return getTOCEntry(DAG, DL, false, GA); 2864 } 2865 2866 SDValue GAHi = 2867 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2868 SDValue GALo = 2869 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2870 2871 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2872 2873 // If the global reference is actually to a non-lazy-pointer, we have to do an 2874 // extra load to get the address of the global. 2875 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2876 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2877 return Ptr; 2878 } 2879 2880 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2881 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2882 SDLoc dl(Op); 2883 2884 if (Op.getValueType() == MVT::v2i64) { 2885 // When the operands themselves are v2i64 values, we need to do something 2886 // special because VSX has no underlying comparison operations for these. 2887 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2888 // Equality can be handled by casting to the legal type for Altivec 2889 // comparisons, everything else needs to be expanded. 2890 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2891 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2892 DAG.getSetCC(dl, MVT::v4i32, 2893 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2894 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2895 CC)); 2896 } 2897 2898 return SDValue(); 2899 } 2900 2901 // We handle most of these in the usual way. 2902 return Op; 2903 } 2904 2905 // If we're comparing for equality to zero, expose the fact that this is 2906 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2907 // fold the new nodes. 2908 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2909 return V; 2910 2911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2912 // Leave comparisons against 0 and -1 alone for now, since they're usually 2913 // optimized. FIXME: revisit this when we can custom lower all setcc 2914 // optimizations. 2915 if (C->isAllOnesValue() || C->isNullValue()) 2916 return SDValue(); 2917 } 2918 2919 // If we have an integer seteq/setne, turn it into a compare against zero 2920 // by xor'ing the rhs with the lhs, which is faster than setting a 2921 // condition register, reading it back out, and masking the correct bit. The 2922 // normal approach here uses sub to do this instead of xor. Using xor exposes 2923 // the result to other bit-twiddling opportunities. 2924 EVT LHSVT = Op.getOperand(0).getValueType(); 2925 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2926 EVT VT = Op.getValueType(); 2927 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2928 Op.getOperand(1)); 2929 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2930 } 2931 return SDValue(); 2932 } 2933 2934 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2935 SDNode *Node = Op.getNode(); 2936 EVT VT = Node->getValueType(0); 2937 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2938 SDValue InChain = Node->getOperand(0); 2939 SDValue VAListPtr = Node->getOperand(1); 2940 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2941 SDLoc dl(Node); 2942 2943 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2944 2945 // gpr_index 2946 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2947 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2948 InChain = GprIndex.getValue(1); 2949 2950 if (VT == MVT::i64) { 2951 // Check if GprIndex is even 2952 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2953 DAG.getConstant(1, dl, MVT::i32)); 2954 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2955 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2956 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2957 DAG.getConstant(1, dl, MVT::i32)); 2958 // Align GprIndex to be even if it isn't 2959 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2960 GprIndex); 2961 } 2962 2963 // fpr index is 1 byte after gpr 2964 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2965 DAG.getConstant(1, dl, MVT::i32)); 2966 2967 // fpr 2968 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2969 FprPtr, MachinePointerInfo(SV), MVT::i8); 2970 InChain = FprIndex.getValue(1); 2971 2972 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2973 DAG.getConstant(8, dl, MVT::i32)); 2974 2975 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2976 DAG.getConstant(4, dl, MVT::i32)); 2977 2978 // areas 2979 SDValue OverflowArea = 2980 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2981 InChain = OverflowArea.getValue(1); 2982 2983 SDValue RegSaveArea = 2984 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2985 InChain = RegSaveArea.getValue(1); 2986 2987 // select overflow_area if index > 8 2988 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2989 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2990 2991 // adjustment constant gpr_index * 4/8 2992 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2993 VT.isInteger() ? GprIndex : FprIndex, 2994 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2995 MVT::i32)); 2996 2997 // OurReg = RegSaveArea + RegConstant 2998 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2999 RegConstant); 3000 3001 // Floating types are 32 bytes into RegSaveArea 3002 if (VT.isFloatingPoint()) 3003 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3004 DAG.getConstant(32, dl, MVT::i32)); 3005 3006 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3007 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3008 VT.isInteger() ? GprIndex : FprIndex, 3009 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3010 MVT::i32)); 3011 3012 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3013 VT.isInteger() ? VAListPtr : FprPtr, 3014 MachinePointerInfo(SV), MVT::i8); 3015 3016 // determine if we should load from reg_save_area or overflow_area 3017 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3018 3019 // increase overflow_area by 4/8 if gpr/fpr > 8 3020 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3021 DAG.getConstant(VT.isInteger() ? 4 : 8, 3022 dl, MVT::i32)); 3023 3024 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3025 OverflowAreaPlusN); 3026 3027 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3028 MachinePointerInfo(), MVT::i32); 3029 3030 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3031 } 3032 3033 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3034 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3035 3036 // We have to copy the entire va_list struct: 3037 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3038 return DAG.getMemcpy(Op.getOperand(0), Op, 3039 Op.getOperand(1), Op.getOperand(2), 3040 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3041 false, MachinePointerInfo(), MachinePointerInfo()); 3042 } 3043 3044 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3045 SelectionDAG &DAG) const { 3046 return Op.getOperand(0); 3047 } 3048 3049 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3050 SelectionDAG &DAG) const { 3051 SDValue Chain = Op.getOperand(0); 3052 SDValue Trmp = Op.getOperand(1); // trampoline 3053 SDValue FPtr = Op.getOperand(2); // nested function 3054 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3055 SDLoc dl(Op); 3056 3057 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3058 bool isPPC64 = (PtrVT == MVT::i64); 3059 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3060 3061 TargetLowering::ArgListTy Args; 3062 TargetLowering::ArgListEntry Entry; 3063 3064 Entry.Ty = IntPtrTy; 3065 Entry.Node = Trmp; Args.push_back(Entry); 3066 3067 // TrampSize == (isPPC64 ? 48 : 40); 3068 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3069 isPPC64 ? MVT::i64 : MVT::i32); 3070 Args.push_back(Entry); 3071 3072 Entry.Node = FPtr; Args.push_back(Entry); 3073 Entry.Node = Nest; Args.push_back(Entry); 3074 3075 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3076 TargetLowering::CallLoweringInfo CLI(DAG); 3077 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3078 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3079 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3080 3081 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3082 return CallResult.second; 3083 } 3084 3085 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3086 MachineFunction &MF = DAG.getMachineFunction(); 3087 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3088 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3089 3090 SDLoc dl(Op); 3091 3092 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3093 // vastart just stores the address of the VarArgsFrameIndex slot into the 3094 // memory location argument. 3095 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3096 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3097 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3098 MachinePointerInfo(SV)); 3099 } 3100 3101 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3102 // We suppose the given va_list is already allocated. 3103 // 3104 // typedef struct { 3105 // char gpr; /* index into the array of 8 GPRs 3106 // * stored in the register save area 3107 // * gpr=0 corresponds to r3, 3108 // * gpr=1 to r4, etc. 3109 // */ 3110 // char fpr; /* index into the array of 8 FPRs 3111 // * stored in the register save area 3112 // * fpr=0 corresponds to f1, 3113 // * fpr=1 to f2, etc. 3114 // */ 3115 // char *overflow_arg_area; 3116 // /* location on stack that holds 3117 // * the next overflow argument 3118 // */ 3119 // char *reg_save_area; 3120 // /* where r3:r10 and f1:f8 (if saved) 3121 // * are stored 3122 // */ 3123 // } va_list[1]; 3124 3125 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3126 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3127 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3128 PtrVT); 3129 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3130 PtrVT); 3131 3132 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3133 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3134 3135 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3136 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3137 3138 uint64_t FPROffset = 1; 3139 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3140 3141 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3142 3143 // Store first byte : number of int regs 3144 SDValue firstStore = 3145 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3146 MachinePointerInfo(SV), MVT::i8); 3147 uint64_t nextOffset = FPROffset; 3148 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3149 ConstFPROffset); 3150 3151 // Store second byte : number of float regs 3152 SDValue secondStore = 3153 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3154 MachinePointerInfo(SV, nextOffset), MVT::i8); 3155 nextOffset += StackOffset; 3156 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3157 3158 // Store second word : arguments given on stack 3159 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3160 MachinePointerInfo(SV, nextOffset)); 3161 nextOffset += FrameOffset; 3162 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3163 3164 // Store third word : arguments given in registers 3165 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3166 MachinePointerInfo(SV, nextOffset)); 3167 } 3168 3169 /// FPR - The set of FP registers that should be allocated for arguments, 3170 /// on Darwin. 3171 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3172 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3173 PPC::F11, PPC::F12, PPC::F13}; 3174 3175 /// QFPR - The set of QPX registers that should be allocated for arguments. 3176 static const MCPhysReg QFPR[] = { 3177 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3178 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3179 3180 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3181 /// the stack. 3182 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3183 unsigned PtrByteSize) { 3184 unsigned ArgSize = ArgVT.getStoreSize(); 3185 if (Flags.isByVal()) 3186 ArgSize = Flags.getByValSize(); 3187 3188 // Round up to multiples of the pointer size, except for array members, 3189 // which are always packed. 3190 if (!Flags.isInConsecutiveRegs()) 3191 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3192 3193 return ArgSize; 3194 } 3195 3196 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3197 /// on the stack. 3198 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3199 ISD::ArgFlagsTy Flags, 3200 unsigned PtrByteSize) { 3201 unsigned Align = PtrByteSize; 3202 3203 // Altivec parameters are padded to a 16 byte boundary. 3204 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3205 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3206 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3207 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3208 Align = 16; 3209 // QPX vector types stored in double-precision are padded to a 32 byte 3210 // boundary. 3211 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3212 Align = 32; 3213 3214 // ByVal parameters are aligned as requested. 3215 if (Flags.isByVal()) { 3216 unsigned BVAlign = Flags.getByValAlign(); 3217 if (BVAlign > PtrByteSize) { 3218 if (BVAlign % PtrByteSize != 0) 3219 llvm_unreachable( 3220 "ByVal alignment is not a multiple of the pointer size"); 3221 3222 Align = BVAlign; 3223 } 3224 } 3225 3226 // Array members are always packed to their original alignment. 3227 if (Flags.isInConsecutiveRegs()) { 3228 // If the array member was split into multiple registers, the first 3229 // needs to be aligned to the size of the full type. (Except for 3230 // ppcf128, which is only aligned as its f64 components.) 3231 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3232 Align = OrigVT.getStoreSize(); 3233 else 3234 Align = ArgVT.getStoreSize(); 3235 } 3236 3237 return Align; 3238 } 3239 3240 /// CalculateStackSlotUsed - Return whether this argument will use its 3241 /// stack slot (instead of being passed in registers). ArgOffset, 3242 /// AvailableFPRs, and AvailableVRs must hold the current argument 3243 /// position, and will be updated to account for this argument. 3244 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3245 ISD::ArgFlagsTy Flags, 3246 unsigned PtrByteSize, 3247 unsigned LinkageSize, 3248 unsigned ParamAreaSize, 3249 unsigned &ArgOffset, 3250 unsigned &AvailableFPRs, 3251 unsigned &AvailableVRs, bool HasQPX) { 3252 bool UseMemory = false; 3253 3254 // Respect alignment of argument on the stack. 3255 unsigned Align = 3256 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3257 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3258 // If there's no space left in the argument save area, we must 3259 // use memory (this check also catches zero-sized arguments). 3260 if (ArgOffset >= LinkageSize + ParamAreaSize) 3261 UseMemory = true; 3262 3263 // Allocate argument on the stack. 3264 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3265 if (Flags.isInConsecutiveRegsLast()) 3266 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3267 // If we overran the argument save area, we must use memory 3268 // (this check catches arguments passed partially in memory) 3269 if (ArgOffset > LinkageSize + ParamAreaSize) 3270 UseMemory = true; 3271 3272 // However, if the argument is actually passed in an FPR or a VR, 3273 // we don't use memory after all. 3274 if (!Flags.isByVal()) { 3275 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3276 // QPX registers overlap with the scalar FP registers. 3277 (HasQPX && (ArgVT == MVT::v4f32 || 3278 ArgVT == MVT::v4f64 || 3279 ArgVT == MVT::v4i1))) 3280 if (AvailableFPRs > 0) { 3281 --AvailableFPRs; 3282 return false; 3283 } 3284 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3285 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3286 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3287 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3288 if (AvailableVRs > 0) { 3289 --AvailableVRs; 3290 return false; 3291 } 3292 } 3293 3294 return UseMemory; 3295 } 3296 3297 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3298 /// ensure minimum alignment required for target. 3299 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3300 unsigned NumBytes) { 3301 unsigned TargetAlign = Lowering->getStackAlignment(); 3302 unsigned AlignMask = TargetAlign - 1; 3303 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3304 return NumBytes; 3305 } 3306 3307 SDValue PPCTargetLowering::LowerFormalArguments( 3308 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3309 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3310 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3311 if (Subtarget.isSVR4ABI()) { 3312 if (Subtarget.isPPC64()) 3313 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3314 dl, DAG, InVals); 3315 else 3316 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3317 dl, DAG, InVals); 3318 } else { 3319 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3320 dl, DAG, InVals); 3321 } 3322 } 3323 3324 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3325 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3326 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3327 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3328 3329 // 32-bit SVR4 ABI Stack Frame Layout: 3330 // +-----------------------------------+ 3331 // +--> | Back chain | 3332 // | +-----------------------------------+ 3333 // | | Floating-point register save area | 3334 // | +-----------------------------------+ 3335 // | | General register save area | 3336 // | +-----------------------------------+ 3337 // | | CR save word | 3338 // | +-----------------------------------+ 3339 // | | VRSAVE save word | 3340 // | +-----------------------------------+ 3341 // | | Alignment padding | 3342 // | +-----------------------------------+ 3343 // | | Vector register save area | 3344 // | +-----------------------------------+ 3345 // | | Local variable space | 3346 // | +-----------------------------------+ 3347 // | | Parameter list area | 3348 // | +-----------------------------------+ 3349 // | | LR save word | 3350 // | +-----------------------------------+ 3351 // SP--> +--- | Back chain | 3352 // +-----------------------------------+ 3353 // 3354 // Specifications: 3355 // System V Application Binary Interface PowerPC Processor Supplement 3356 // AltiVec Technology Programming Interface Manual 3357 3358 MachineFunction &MF = DAG.getMachineFunction(); 3359 MachineFrameInfo &MFI = MF.getFrameInfo(); 3360 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3361 3362 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3363 // Potential tail calls could cause overwriting of argument stack slots. 3364 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3365 (CallConv == CallingConv::Fast)); 3366 unsigned PtrByteSize = 4; 3367 3368 // Assign locations to all of the incoming arguments. 3369 SmallVector<CCValAssign, 16> ArgLocs; 3370 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3371 *DAG.getContext()); 3372 3373 // Reserve space for the linkage area on the stack. 3374 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3375 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3376 if (useSoftFloat() || hasSPE()) 3377 CCInfo.PreAnalyzeFormalArguments(Ins); 3378 3379 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3380 CCInfo.clearWasPPCF128(); 3381 3382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3383 CCValAssign &VA = ArgLocs[i]; 3384 3385 // Arguments stored in registers. 3386 if (VA.isRegLoc()) { 3387 const TargetRegisterClass *RC; 3388 EVT ValVT = VA.getValVT(); 3389 3390 switch (ValVT.getSimpleVT().SimpleTy) { 3391 default: 3392 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3393 case MVT::i1: 3394 case MVT::i32: 3395 RC = &PPC::GPRCRegClass; 3396 break; 3397 case MVT::f32: 3398 if (Subtarget.hasP8Vector()) 3399 RC = &PPC::VSSRCRegClass; 3400 else if (Subtarget.hasSPE()) 3401 RC = &PPC::SPE4RCRegClass; 3402 else 3403 RC = &PPC::F4RCRegClass; 3404 break; 3405 case MVT::f64: 3406 if (Subtarget.hasVSX()) 3407 RC = &PPC::VSFRCRegClass; 3408 else if (Subtarget.hasSPE()) 3409 RC = &PPC::SPERCRegClass; 3410 else 3411 RC = &PPC::F8RCRegClass; 3412 break; 3413 case MVT::v16i8: 3414 case MVT::v8i16: 3415 case MVT::v4i32: 3416 RC = &PPC::VRRCRegClass; 3417 break; 3418 case MVT::v4f32: 3419 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3420 break; 3421 case MVT::v2f64: 3422 case MVT::v2i64: 3423 RC = &PPC::VRRCRegClass; 3424 break; 3425 case MVT::v4f64: 3426 RC = &PPC::QFRCRegClass; 3427 break; 3428 case MVT::v4i1: 3429 RC = &PPC::QBRCRegClass; 3430 break; 3431 } 3432 3433 // Transform the arguments stored in physical registers into virtual ones. 3434 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3435 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3436 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3437 3438 if (ValVT == MVT::i1) 3439 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3440 3441 InVals.push_back(ArgValue); 3442 } else { 3443 // Argument stored in memory. 3444 assert(VA.isMemLoc()); 3445 3446 // Get the extended size of the argument type in stack 3447 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3448 // Get the actual size of the argument type 3449 unsigned ObjSize = VA.getValVT().getStoreSize(); 3450 unsigned ArgOffset = VA.getLocMemOffset(); 3451 // Stack objects in PPC32 are right justified. 3452 ArgOffset += ArgSize - ObjSize; 3453 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3454 3455 // Create load nodes to retrieve arguments from the stack. 3456 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3457 InVals.push_back( 3458 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3459 } 3460 } 3461 3462 // Assign locations to all of the incoming aggregate by value arguments. 3463 // Aggregates passed by value are stored in the local variable space of the 3464 // caller's stack frame, right above the parameter list area. 3465 SmallVector<CCValAssign, 16> ByValArgLocs; 3466 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3467 ByValArgLocs, *DAG.getContext()); 3468 3469 // Reserve stack space for the allocations in CCInfo. 3470 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3471 3472 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3473 3474 // Area that is at least reserved in the caller of this function. 3475 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3476 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3477 3478 // Set the size that is at least reserved in caller of this function. Tail 3479 // call optimized function's reserved stack space needs to be aligned so that 3480 // taking the difference between two stack areas will result in an aligned 3481 // stack. 3482 MinReservedArea = 3483 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3484 FuncInfo->setMinReservedArea(MinReservedArea); 3485 3486 SmallVector<SDValue, 8> MemOps; 3487 3488 // If the function takes variable number of arguments, make a frame index for 3489 // the start of the first vararg value... for expansion of llvm.va_start. 3490 if (isVarArg) { 3491 static const MCPhysReg GPArgRegs[] = { 3492 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3493 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3494 }; 3495 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3496 3497 static const MCPhysReg FPArgRegs[] = { 3498 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3499 PPC::F8 3500 }; 3501 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3502 3503 if (useSoftFloat() || hasSPE()) 3504 NumFPArgRegs = 0; 3505 3506 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3507 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3508 3509 // Make room for NumGPArgRegs and NumFPArgRegs. 3510 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3511 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3512 3513 FuncInfo->setVarArgsStackOffset( 3514 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3515 CCInfo.getNextStackOffset(), true)); 3516 3517 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3518 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3519 3520 // The fixed integer arguments of a variadic function are stored to the 3521 // VarArgsFrameIndex on the stack so that they may be loaded by 3522 // dereferencing the result of va_next. 3523 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3524 // Get an existing live-in vreg, or add a new one. 3525 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3526 if (!VReg) 3527 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3528 3529 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3530 SDValue Store = 3531 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3532 MemOps.push_back(Store); 3533 // Increment the address by four for the next argument to store 3534 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3535 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3536 } 3537 3538 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3539 // is set. 3540 // The double arguments are stored to the VarArgsFrameIndex 3541 // on the stack. 3542 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3543 // Get an existing live-in vreg, or add a new one. 3544 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3545 if (!VReg) 3546 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3547 3548 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3549 SDValue Store = 3550 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3551 MemOps.push_back(Store); 3552 // Increment the address by eight for the next argument to store 3553 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3554 PtrVT); 3555 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3556 } 3557 } 3558 3559 if (!MemOps.empty()) 3560 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3561 3562 return Chain; 3563 } 3564 3565 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3566 // value to MVT::i64 and then truncate to the correct register size. 3567 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3568 EVT ObjectVT, SelectionDAG &DAG, 3569 SDValue ArgVal, 3570 const SDLoc &dl) const { 3571 if (Flags.isSExt()) 3572 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3573 DAG.getValueType(ObjectVT)); 3574 else if (Flags.isZExt()) 3575 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3576 DAG.getValueType(ObjectVT)); 3577 3578 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3579 } 3580 3581 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3582 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3583 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3584 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3585 // TODO: add description of PPC stack frame format, or at least some docs. 3586 // 3587 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3588 bool isLittleEndian = Subtarget.isLittleEndian(); 3589 MachineFunction &MF = DAG.getMachineFunction(); 3590 MachineFrameInfo &MFI = MF.getFrameInfo(); 3591 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3592 3593 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3594 "fastcc not supported on varargs functions"); 3595 3596 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3597 // Potential tail calls could cause overwriting of argument stack slots. 3598 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3599 (CallConv == CallingConv::Fast)); 3600 unsigned PtrByteSize = 8; 3601 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3602 3603 static const MCPhysReg GPR[] = { 3604 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3605 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3606 }; 3607 static const MCPhysReg VR[] = { 3608 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3609 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3610 }; 3611 3612 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3613 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3614 const unsigned Num_VR_Regs = array_lengthof(VR); 3615 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3616 3617 // Do a first pass over the arguments to determine whether the ABI 3618 // guarantees that our caller has allocated the parameter save area 3619 // on its stack frame. In the ELFv1 ABI, this is always the case; 3620 // in the ELFv2 ABI, it is true if this is a vararg function or if 3621 // any parameter is located in a stack slot. 3622 3623 bool HasParameterArea = !isELFv2ABI || isVarArg; 3624 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3625 unsigned NumBytes = LinkageSize; 3626 unsigned AvailableFPRs = Num_FPR_Regs; 3627 unsigned AvailableVRs = Num_VR_Regs; 3628 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3629 if (Ins[i].Flags.isNest()) 3630 continue; 3631 3632 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3633 PtrByteSize, LinkageSize, ParamAreaSize, 3634 NumBytes, AvailableFPRs, AvailableVRs, 3635 Subtarget.hasQPX())) 3636 HasParameterArea = true; 3637 } 3638 3639 // Add DAG nodes to load the arguments or copy them out of registers. On 3640 // entry to a function on PPC, the arguments start after the linkage area, 3641 // although the first ones are often in registers. 3642 3643 unsigned ArgOffset = LinkageSize; 3644 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3645 unsigned &QFPR_idx = FPR_idx; 3646 SmallVector<SDValue, 8> MemOps; 3647 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3648 unsigned CurArgIdx = 0; 3649 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3650 SDValue ArgVal; 3651 bool needsLoad = false; 3652 EVT ObjectVT = Ins[ArgNo].VT; 3653 EVT OrigVT = Ins[ArgNo].ArgVT; 3654 unsigned ObjSize = ObjectVT.getStoreSize(); 3655 unsigned ArgSize = ObjSize; 3656 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3657 if (Ins[ArgNo].isOrigArg()) { 3658 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3659 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3660 } 3661 // We re-align the argument offset for each argument, except when using the 3662 // fast calling convention, when we need to make sure we do that only when 3663 // we'll actually use a stack slot. 3664 unsigned CurArgOffset, Align; 3665 auto ComputeArgOffset = [&]() { 3666 /* Respect alignment of argument on the stack. */ 3667 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3668 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3669 CurArgOffset = ArgOffset; 3670 }; 3671 3672 if (CallConv != CallingConv::Fast) { 3673 ComputeArgOffset(); 3674 3675 /* Compute GPR index associated with argument offset. */ 3676 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3677 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3678 } 3679 3680 // FIXME the codegen can be much improved in some cases. 3681 // We do not have to keep everything in memory. 3682 if (Flags.isByVal()) { 3683 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3684 3685 if (CallConv == CallingConv::Fast) 3686 ComputeArgOffset(); 3687 3688 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3689 ObjSize = Flags.getByValSize(); 3690 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3691 // Empty aggregate parameters do not take up registers. Examples: 3692 // struct { } a; 3693 // union { } b; 3694 // int c[0]; 3695 // etc. However, we have to provide a place-holder in InVals, so 3696 // pretend we have an 8-byte item at the current address for that 3697 // purpose. 3698 if (!ObjSize) { 3699 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3700 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3701 InVals.push_back(FIN); 3702 continue; 3703 } 3704 3705 // Create a stack object covering all stack doublewords occupied 3706 // by the argument. If the argument is (fully or partially) on 3707 // the stack, or if the argument is fully in registers but the 3708 // caller has allocated the parameter save anyway, we can refer 3709 // directly to the caller's stack frame. Otherwise, create a 3710 // local copy in our own frame. 3711 int FI; 3712 if (HasParameterArea || 3713 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3714 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3715 else 3716 FI = MFI.CreateStackObject(ArgSize, Align, false); 3717 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3718 3719 // Handle aggregates smaller than 8 bytes. 3720 if (ObjSize < PtrByteSize) { 3721 // The value of the object is its address, which differs from the 3722 // address of the enclosing doubleword on big-endian systems. 3723 SDValue Arg = FIN; 3724 if (!isLittleEndian) { 3725 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3726 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3727 } 3728 InVals.push_back(Arg); 3729 3730 if (GPR_idx != Num_GPR_Regs) { 3731 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3732 FuncInfo->addLiveInAttr(VReg, Flags); 3733 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3734 SDValue Store; 3735 3736 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3737 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3738 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3739 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3740 MachinePointerInfo(&*FuncArg), ObjType); 3741 } else { 3742 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3743 // store the whole register as-is to the parameter save area 3744 // slot. 3745 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3746 MachinePointerInfo(&*FuncArg)); 3747 } 3748 3749 MemOps.push_back(Store); 3750 } 3751 // Whether we copied from a register or not, advance the offset 3752 // into the parameter save area by a full doubleword. 3753 ArgOffset += PtrByteSize; 3754 continue; 3755 } 3756 3757 // The value of the object is its address, which is the address of 3758 // its first stack doubleword. 3759 InVals.push_back(FIN); 3760 3761 // Store whatever pieces of the object are in registers to memory. 3762 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3763 if (GPR_idx == Num_GPR_Regs) 3764 break; 3765 3766 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3767 FuncInfo->addLiveInAttr(VReg, Flags); 3768 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3769 SDValue Addr = FIN; 3770 if (j) { 3771 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3772 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3773 } 3774 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3775 MachinePointerInfo(&*FuncArg, j)); 3776 MemOps.push_back(Store); 3777 ++GPR_idx; 3778 } 3779 ArgOffset += ArgSize; 3780 continue; 3781 } 3782 3783 switch (ObjectVT.getSimpleVT().SimpleTy) { 3784 default: llvm_unreachable("Unhandled argument type!"); 3785 case MVT::i1: 3786 case MVT::i32: 3787 case MVT::i64: 3788 if (Flags.isNest()) { 3789 // The 'nest' parameter, if any, is passed in R11. 3790 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3791 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3792 3793 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3794 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3795 3796 break; 3797 } 3798 3799 // These can be scalar arguments or elements of an integer array type 3800 // passed directly. Clang may use those instead of "byval" aggregate 3801 // types to avoid forcing arguments to memory unnecessarily. 3802 if (GPR_idx != Num_GPR_Regs) { 3803 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3804 FuncInfo->addLiveInAttr(VReg, Flags); 3805 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3806 3807 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3808 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3809 // value to MVT::i64 and then truncate to the correct register size. 3810 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3811 } else { 3812 if (CallConv == CallingConv::Fast) 3813 ComputeArgOffset(); 3814 3815 needsLoad = true; 3816 ArgSize = PtrByteSize; 3817 } 3818 if (CallConv != CallingConv::Fast || needsLoad) 3819 ArgOffset += 8; 3820 break; 3821 3822 case MVT::f32: 3823 case MVT::f64: 3824 // These can be scalar arguments or elements of a float array type 3825 // passed directly. The latter are used to implement ELFv2 homogenous 3826 // float aggregates. 3827 if (FPR_idx != Num_FPR_Regs) { 3828 unsigned VReg; 3829 3830 if (ObjectVT == MVT::f32) 3831 VReg = MF.addLiveIn(FPR[FPR_idx], 3832 Subtarget.hasP8Vector() 3833 ? &PPC::VSSRCRegClass 3834 : &PPC::F4RCRegClass); 3835 else 3836 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3837 ? &PPC::VSFRCRegClass 3838 : &PPC::F8RCRegClass); 3839 3840 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3841 ++FPR_idx; 3842 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3843 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3844 // once we support fp <-> gpr moves. 3845 3846 // This can only ever happen in the presence of f32 array types, 3847 // since otherwise we never run out of FPRs before running out 3848 // of GPRs. 3849 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3850 FuncInfo->addLiveInAttr(VReg, Flags); 3851 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3852 3853 if (ObjectVT == MVT::f32) { 3854 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3855 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3856 DAG.getConstant(32, dl, MVT::i32)); 3857 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3858 } 3859 3860 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3861 } else { 3862 if (CallConv == CallingConv::Fast) 3863 ComputeArgOffset(); 3864 3865 needsLoad = true; 3866 } 3867 3868 // When passing an array of floats, the array occupies consecutive 3869 // space in the argument area; only round up to the next doubleword 3870 // at the end of the array. Otherwise, each float takes 8 bytes. 3871 if (CallConv != CallingConv::Fast || needsLoad) { 3872 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3873 ArgOffset += ArgSize; 3874 if (Flags.isInConsecutiveRegsLast()) 3875 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3876 } 3877 break; 3878 case MVT::v4f32: 3879 case MVT::v4i32: 3880 case MVT::v8i16: 3881 case MVT::v16i8: 3882 case MVT::v2f64: 3883 case MVT::v2i64: 3884 case MVT::v1i128: 3885 case MVT::f128: 3886 if (!Subtarget.hasQPX()) { 3887 // These can be scalar arguments or elements of a vector array type 3888 // passed directly. The latter are used to implement ELFv2 homogenous 3889 // vector aggregates. 3890 if (VR_idx != Num_VR_Regs) { 3891 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3892 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3893 ++VR_idx; 3894 } else { 3895 if (CallConv == CallingConv::Fast) 3896 ComputeArgOffset(); 3897 needsLoad = true; 3898 } 3899 if (CallConv != CallingConv::Fast || needsLoad) 3900 ArgOffset += 16; 3901 break; 3902 } // not QPX 3903 3904 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3905 "Invalid QPX parameter type"); 3906 LLVM_FALLTHROUGH; 3907 3908 case MVT::v4f64: 3909 case MVT::v4i1: 3910 // QPX vectors are treated like their scalar floating-point subregisters 3911 // (except that they're larger). 3912 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3913 if (QFPR_idx != Num_QFPR_Regs) { 3914 const TargetRegisterClass *RC; 3915 switch (ObjectVT.getSimpleVT().SimpleTy) { 3916 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3917 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3918 default: RC = &PPC::QBRCRegClass; break; 3919 } 3920 3921 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3922 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3923 ++QFPR_idx; 3924 } else { 3925 if (CallConv == CallingConv::Fast) 3926 ComputeArgOffset(); 3927 needsLoad = true; 3928 } 3929 if (CallConv != CallingConv::Fast || needsLoad) 3930 ArgOffset += Sz; 3931 break; 3932 } 3933 3934 // We need to load the argument to a virtual register if we determined 3935 // above that we ran out of physical registers of the appropriate type. 3936 if (needsLoad) { 3937 if (ObjSize < ArgSize && !isLittleEndian) 3938 CurArgOffset += ArgSize - ObjSize; 3939 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3940 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3941 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3942 } 3943 3944 InVals.push_back(ArgVal); 3945 } 3946 3947 // Area that is at least reserved in the caller of this function. 3948 unsigned MinReservedArea; 3949 if (HasParameterArea) 3950 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3951 else 3952 MinReservedArea = LinkageSize; 3953 3954 // Set the size that is at least reserved in caller of this function. Tail 3955 // call optimized functions' reserved stack space needs to be aligned so that 3956 // taking the difference between two stack areas will result in an aligned 3957 // stack. 3958 MinReservedArea = 3959 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3960 FuncInfo->setMinReservedArea(MinReservedArea); 3961 3962 // If the function takes variable number of arguments, make a frame index for 3963 // the start of the first vararg value... for expansion of llvm.va_start. 3964 if (isVarArg) { 3965 int Depth = ArgOffset; 3966 3967 FuncInfo->setVarArgsFrameIndex( 3968 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3969 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3970 3971 // If this function is vararg, store any remaining integer argument regs 3972 // to their spots on the stack so that they may be loaded by dereferencing 3973 // the result of va_next. 3974 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3975 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3976 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3977 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3978 SDValue Store = 3979 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3980 MemOps.push_back(Store); 3981 // Increment the address by four for the next argument to store 3982 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3983 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3984 } 3985 } 3986 3987 if (!MemOps.empty()) 3988 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3989 3990 return Chain; 3991 } 3992 3993 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3994 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3995 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3996 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3997 // TODO: add description of PPC stack frame format, or at least some docs. 3998 // 3999 MachineFunction &MF = DAG.getMachineFunction(); 4000 MachineFrameInfo &MFI = MF.getFrameInfo(); 4001 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4002 4003 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4004 bool isPPC64 = PtrVT == MVT::i64; 4005 // Potential tail calls could cause overwriting of argument stack slots. 4006 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4007 (CallConv == CallingConv::Fast)); 4008 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4009 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4010 unsigned ArgOffset = LinkageSize; 4011 // Area that is at least reserved in caller of this function. 4012 unsigned MinReservedArea = ArgOffset; 4013 4014 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4015 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4016 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4017 }; 4018 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4019 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4020 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4021 }; 4022 static const MCPhysReg VR[] = { 4023 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4024 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4025 }; 4026 4027 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4028 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4029 const unsigned Num_VR_Regs = array_lengthof( VR); 4030 4031 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4032 4033 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4034 4035 // In 32-bit non-varargs functions, the stack space for vectors is after the 4036 // stack space for non-vectors. We do not use this space unless we have 4037 // too many vectors to fit in registers, something that only occurs in 4038 // constructed examples:), but we have to walk the arglist to figure 4039 // that out...for the pathological case, compute VecArgOffset as the 4040 // start of the vector parameter area. Computing VecArgOffset is the 4041 // entire point of the following loop. 4042 unsigned VecArgOffset = ArgOffset; 4043 if (!isVarArg && !isPPC64) { 4044 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4045 ++ArgNo) { 4046 EVT ObjectVT = Ins[ArgNo].VT; 4047 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4048 4049 if (Flags.isByVal()) { 4050 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4051 unsigned ObjSize = Flags.getByValSize(); 4052 unsigned ArgSize = 4053 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4054 VecArgOffset += ArgSize; 4055 continue; 4056 } 4057 4058 switch(ObjectVT.getSimpleVT().SimpleTy) { 4059 default: llvm_unreachable("Unhandled argument type!"); 4060 case MVT::i1: 4061 case MVT::i32: 4062 case MVT::f32: 4063 VecArgOffset += 4; 4064 break; 4065 case MVT::i64: // PPC64 4066 case MVT::f64: 4067 // FIXME: We are guaranteed to be !isPPC64 at this point. 4068 // Does MVT::i64 apply? 4069 VecArgOffset += 8; 4070 break; 4071 case MVT::v4f32: 4072 case MVT::v4i32: 4073 case MVT::v8i16: 4074 case MVT::v16i8: 4075 // Nothing to do, we're only looking at Nonvector args here. 4076 break; 4077 } 4078 } 4079 } 4080 // We've found where the vector parameter area in memory is. Skip the 4081 // first 12 parameters; these don't use that memory. 4082 VecArgOffset = ((VecArgOffset+15)/16)*16; 4083 VecArgOffset += 12*16; 4084 4085 // Add DAG nodes to load the arguments or copy them out of registers. On 4086 // entry to a function on PPC, the arguments start after the linkage area, 4087 // although the first ones are often in registers. 4088 4089 SmallVector<SDValue, 8> MemOps; 4090 unsigned nAltivecParamsAtEnd = 0; 4091 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4092 unsigned CurArgIdx = 0; 4093 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4094 SDValue ArgVal; 4095 bool needsLoad = false; 4096 EVT ObjectVT = Ins[ArgNo].VT; 4097 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4098 unsigned ArgSize = ObjSize; 4099 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4100 if (Ins[ArgNo].isOrigArg()) { 4101 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4102 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4103 } 4104 unsigned CurArgOffset = ArgOffset; 4105 4106 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4107 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4108 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4109 if (isVarArg || isPPC64) { 4110 MinReservedArea = ((MinReservedArea+15)/16)*16; 4111 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4112 Flags, 4113 PtrByteSize); 4114 } else nAltivecParamsAtEnd++; 4115 } else 4116 // Calculate min reserved area. 4117 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4118 Flags, 4119 PtrByteSize); 4120 4121 // FIXME the codegen can be much improved in some cases. 4122 // We do not have to keep everything in memory. 4123 if (Flags.isByVal()) { 4124 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4125 4126 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4127 ObjSize = Flags.getByValSize(); 4128 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4129 // Objects of size 1 and 2 are right justified, everything else is 4130 // left justified. This means the memory address is adjusted forwards. 4131 if (ObjSize==1 || ObjSize==2) { 4132 CurArgOffset = CurArgOffset + (4 - ObjSize); 4133 } 4134 // The value of the object is its address. 4135 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4136 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4137 InVals.push_back(FIN); 4138 if (ObjSize==1 || ObjSize==2) { 4139 if (GPR_idx != Num_GPR_Regs) { 4140 unsigned VReg; 4141 if (isPPC64) 4142 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4143 else 4144 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4145 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4146 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4147 SDValue Store = 4148 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4149 MachinePointerInfo(&*FuncArg), ObjType); 4150 MemOps.push_back(Store); 4151 ++GPR_idx; 4152 } 4153 4154 ArgOffset += PtrByteSize; 4155 4156 continue; 4157 } 4158 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4159 // Store whatever pieces of the object are in registers 4160 // to memory. ArgOffset will be the address of the beginning 4161 // of the object. 4162 if (GPR_idx != Num_GPR_Regs) { 4163 unsigned VReg; 4164 if (isPPC64) 4165 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4166 else 4167 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4168 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4169 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4170 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4171 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4172 MachinePointerInfo(&*FuncArg, j)); 4173 MemOps.push_back(Store); 4174 ++GPR_idx; 4175 ArgOffset += PtrByteSize; 4176 } else { 4177 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4178 break; 4179 } 4180 } 4181 continue; 4182 } 4183 4184 switch (ObjectVT.getSimpleVT().SimpleTy) { 4185 default: llvm_unreachable("Unhandled argument type!"); 4186 case MVT::i1: 4187 case MVT::i32: 4188 if (!isPPC64) { 4189 if (GPR_idx != Num_GPR_Regs) { 4190 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4191 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4192 4193 if (ObjectVT == MVT::i1) 4194 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4195 4196 ++GPR_idx; 4197 } else { 4198 needsLoad = true; 4199 ArgSize = PtrByteSize; 4200 } 4201 // All int arguments reserve stack space in the Darwin ABI. 4202 ArgOffset += PtrByteSize; 4203 break; 4204 } 4205 LLVM_FALLTHROUGH; 4206 case MVT::i64: // PPC64 4207 if (GPR_idx != Num_GPR_Regs) { 4208 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4209 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4210 4211 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4212 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4213 // value to MVT::i64 and then truncate to the correct register size. 4214 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4215 4216 ++GPR_idx; 4217 } else { 4218 needsLoad = true; 4219 ArgSize = PtrByteSize; 4220 } 4221 // All int arguments reserve stack space in the Darwin ABI. 4222 ArgOffset += 8; 4223 break; 4224 4225 case MVT::f32: 4226 case MVT::f64: 4227 // Every 4 bytes of argument space consumes one of the GPRs available for 4228 // argument passing. 4229 if (GPR_idx != Num_GPR_Regs) { 4230 ++GPR_idx; 4231 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4232 ++GPR_idx; 4233 } 4234 if (FPR_idx != Num_FPR_Regs) { 4235 unsigned VReg; 4236 4237 if (ObjectVT == MVT::f32) 4238 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4239 else 4240 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4241 4242 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4243 ++FPR_idx; 4244 } else { 4245 needsLoad = true; 4246 } 4247 4248 // All FP arguments reserve stack space in the Darwin ABI. 4249 ArgOffset += isPPC64 ? 8 : ObjSize; 4250 break; 4251 case MVT::v4f32: 4252 case MVT::v4i32: 4253 case MVT::v8i16: 4254 case MVT::v16i8: 4255 // Note that vector arguments in registers don't reserve stack space, 4256 // except in varargs functions. 4257 if (VR_idx != Num_VR_Regs) { 4258 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4259 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4260 if (isVarArg) { 4261 while ((ArgOffset % 16) != 0) { 4262 ArgOffset += PtrByteSize; 4263 if (GPR_idx != Num_GPR_Regs) 4264 GPR_idx++; 4265 } 4266 ArgOffset += 16; 4267 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4268 } 4269 ++VR_idx; 4270 } else { 4271 if (!isVarArg && !isPPC64) { 4272 // Vectors go after all the nonvectors. 4273 CurArgOffset = VecArgOffset; 4274 VecArgOffset += 16; 4275 } else { 4276 // Vectors are aligned. 4277 ArgOffset = ((ArgOffset+15)/16)*16; 4278 CurArgOffset = ArgOffset; 4279 ArgOffset += 16; 4280 } 4281 needsLoad = true; 4282 } 4283 break; 4284 } 4285 4286 // We need to load the argument to a virtual register if we determined above 4287 // that we ran out of physical registers of the appropriate type. 4288 if (needsLoad) { 4289 int FI = MFI.CreateFixedObject(ObjSize, 4290 CurArgOffset + (ArgSize - ObjSize), 4291 isImmutable); 4292 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4293 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4294 } 4295 4296 InVals.push_back(ArgVal); 4297 } 4298 4299 // Allow for Altivec parameters at the end, if needed. 4300 if (nAltivecParamsAtEnd) { 4301 MinReservedArea = ((MinReservedArea+15)/16)*16; 4302 MinReservedArea += 16*nAltivecParamsAtEnd; 4303 } 4304 4305 // Area that is at least reserved in the caller of this function. 4306 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4307 4308 // Set the size that is at least reserved in caller of this function. Tail 4309 // call optimized functions' reserved stack space needs to be aligned so that 4310 // taking the difference between two stack areas will result in an aligned 4311 // stack. 4312 MinReservedArea = 4313 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4314 FuncInfo->setMinReservedArea(MinReservedArea); 4315 4316 // If the function takes variable number of arguments, make a frame index for 4317 // the start of the first vararg value... for expansion of llvm.va_start. 4318 if (isVarArg) { 4319 int Depth = ArgOffset; 4320 4321 FuncInfo->setVarArgsFrameIndex( 4322 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4323 Depth, true)); 4324 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4325 4326 // If this function is vararg, store any remaining integer argument regs 4327 // to their spots on the stack so that they may be loaded by dereferencing 4328 // the result of va_next. 4329 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4330 unsigned VReg; 4331 4332 if (isPPC64) 4333 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4334 else 4335 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4336 4337 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4338 SDValue Store = 4339 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4340 MemOps.push_back(Store); 4341 // Increment the address by four for the next argument to store 4342 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4343 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4344 } 4345 } 4346 4347 if (!MemOps.empty()) 4348 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4349 4350 return Chain; 4351 } 4352 4353 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4354 /// adjusted to accommodate the arguments for the tailcall. 4355 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4356 unsigned ParamSize) { 4357 4358 if (!isTailCall) return 0; 4359 4360 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4361 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4362 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4363 // Remember only if the new adjustment is bigger. 4364 if (SPDiff < FI->getTailCallSPDelta()) 4365 FI->setTailCallSPDelta(SPDiff); 4366 4367 return SPDiff; 4368 } 4369 4370 static bool isFunctionGlobalAddress(SDValue Callee); 4371 4372 static bool 4373 callsShareTOCBase(const Function *Caller, SDValue Callee, 4374 const TargetMachine &TM) { 4375 // If !G, Callee can be an external symbol. 4376 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4377 if (!G) 4378 return false; 4379 4380 // The medium and large code models are expected to provide a sufficiently 4381 // large TOC to provide all data addressing needs of a module with a 4382 // single TOC. Since each module will be addressed with a single TOC then we 4383 // only need to check that caller and callee don't cross dso boundaries. 4384 if (CodeModel::Medium == TM.getCodeModel() || 4385 CodeModel::Large == TM.getCodeModel()) 4386 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4387 4388 // Otherwise we need to ensure callee and caller are in the same section, 4389 // since the linker may allocate multiple TOCs, and we don't know which 4390 // sections will belong to the same TOC base. 4391 4392 const GlobalValue *GV = G->getGlobal(); 4393 if (!GV->isStrongDefinitionForLinker()) 4394 return false; 4395 4396 // Any explicitly-specified sections and section prefixes must also match. 4397 // Also, if we're using -ffunction-sections, then each function is always in 4398 // a different section (the same is true for COMDAT functions). 4399 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4400 GV->getSection() != Caller->getSection()) 4401 return false; 4402 if (const auto *F = dyn_cast<Function>(GV)) { 4403 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4404 return false; 4405 } 4406 4407 // If the callee might be interposed, then we can't assume the ultimate call 4408 // target will be in the same section. Even in cases where we can assume that 4409 // interposition won't happen, in any case where the linker might insert a 4410 // stub to allow for interposition, we must generate code as though 4411 // interposition might occur. To understand why this matters, consider a 4412 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4413 // in the same section, but a is in a different module (i.e. has a different 4414 // TOC base pointer). If the linker allows for interposition between b and c, 4415 // then it will generate a stub for the call edge between b and c which will 4416 // save the TOC pointer into the designated stack slot allocated by b. If we 4417 // return true here, and therefore allow a tail call between b and c, that 4418 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4419 // pointer into the stack slot allocated by a (where the a -> b stub saved 4420 // a's TOC base pointer). If we're not considering a tail call, but rather, 4421 // whether a nop is needed after the call instruction in b, because the linker 4422 // will insert a stub, it might complain about a missing nop if we omit it 4423 // (although many don't complain in this case). 4424 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4425 return false; 4426 4427 return true; 4428 } 4429 4430 static bool 4431 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4432 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4433 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4434 4435 const unsigned PtrByteSize = 8; 4436 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4437 4438 static const MCPhysReg GPR[] = { 4439 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4440 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4441 }; 4442 static const MCPhysReg VR[] = { 4443 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4444 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4445 }; 4446 4447 const unsigned NumGPRs = array_lengthof(GPR); 4448 const unsigned NumFPRs = 13; 4449 const unsigned NumVRs = array_lengthof(VR); 4450 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4451 4452 unsigned NumBytes = LinkageSize; 4453 unsigned AvailableFPRs = NumFPRs; 4454 unsigned AvailableVRs = NumVRs; 4455 4456 for (const ISD::OutputArg& Param : Outs) { 4457 if (Param.Flags.isNest()) continue; 4458 4459 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4460 PtrByteSize, LinkageSize, ParamAreaSize, 4461 NumBytes, AvailableFPRs, AvailableVRs, 4462 Subtarget.hasQPX())) 4463 return true; 4464 } 4465 return false; 4466 } 4467 4468 static bool 4469 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4470 if (CS.arg_size() != CallerFn->arg_size()) 4471 return false; 4472 4473 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4474 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4475 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4476 4477 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4478 const Value* CalleeArg = *CalleeArgIter; 4479 const Value* CallerArg = &(*CallerArgIter); 4480 if (CalleeArg == CallerArg) 4481 continue; 4482 4483 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4484 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4485 // } 4486 // 1st argument of callee is undef and has the same type as caller. 4487 if (CalleeArg->getType() == CallerArg->getType() && 4488 isa<UndefValue>(CalleeArg)) 4489 continue; 4490 4491 return false; 4492 } 4493 4494 return true; 4495 } 4496 4497 // Returns true if TCO is possible between the callers and callees 4498 // calling conventions. 4499 static bool 4500 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4501 CallingConv::ID CalleeCC) { 4502 // Tail calls are possible with fastcc and ccc. 4503 auto isTailCallableCC = [] (CallingConv::ID CC){ 4504 return CC == CallingConv::C || CC == CallingConv::Fast; 4505 }; 4506 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4507 return false; 4508 4509 // We can safely tail call both fastcc and ccc callees from a c calling 4510 // convention caller. If the caller is fastcc, we may have less stack space 4511 // than a non-fastcc caller with the same signature so disable tail-calls in 4512 // that case. 4513 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4514 } 4515 4516 bool 4517 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4518 SDValue Callee, 4519 CallingConv::ID CalleeCC, 4520 ImmutableCallSite CS, 4521 bool isVarArg, 4522 const SmallVectorImpl<ISD::OutputArg> &Outs, 4523 const SmallVectorImpl<ISD::InputArg> &Ins, 4524 SelectionDAG& DAG) const { 4525 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4526 4527 if (DisableSCO && !TailCallOpt) return false; 4528 4529 // Variadic argument functions are not supported. 4530 if (isVarArg) return false; 4531 4532 auto &Caller = DAG.getMachineFunction().getFunction(); 4533 // Check that the calling conventions are compatible for tco. 4534 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4535 return false; 4536 4537 // Caller contains any byval parameter is not supported. 4538 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4539 return false; 4540 4541 // Callee contains any byval parameter is not supported, too. 4542 // Note: This is a quick work around, because in some cases, e.g. 4543 // caller's stack size > callee's stack size, we are still able to apply 4544 // sibling call optimization. For example, gcc is able to do SCO for caller1 4545 // in the following example, but not for caller2. 4546 // struct test { 4547 // long int a; 4548 // char ary[56]; 4549 // } gTest; 4550 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4551 // b->a = v.a; 4552 // return 0; 4553 // } 4554 // void caller1(struct test a, struct test c, struct test *b) { 4555 // callee(gTest, b); } 4556 // void caller2(struct test *b) { callee(gTest, b); } 4557 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4558 return false; 4559 4560 // If callee and caller use different calling conventions, we cannot pass 4561 // parameters on stack since offsets for the parameter area may be different. 4562 if (Caller.getCallingConv() != CalleeCC && 4563 needStackSlotPassParameters(Subtarget, Outs)) 4564 return false; 4565 4566 // No TCO/SCO on indirect call because Caller have to restore its TOC 4567 if (!isFunctionGlobalAddress(Callee) && 4568 !isa<ExternalSymbolSDNode>(Callee)) 4569 return false; 4570 4571 // If the caller and callee potentially have different TOC bases then we 4572 // cannot tail call since we need to restore the TOC pointer after the call. 4573 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4574 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4575 return false; 4576 4577 // TCO allows altering callee ABI, so we don't have to check further. 4578 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4579 return true; 4580 4581 if (DisableSCO) return false; 4582 4583 // If callee use the same argument list that caller is using, then we can 4584 // apply SCO on this case. If it is not, then we need to check if callee needs 4585 // stack for passing arguments. 4586 if (!hasSameArgumentList(&Caller, CS) && 4587 needStackSlotPassParameters(Subtarget, Outs)) { 4588 return false; 4589 } 4590 4591 return true; 4592 } 4593 4594 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4595 /// for tail call optimization. Targets which want to do tail call 4596 /// optimization should implement this function. 4597 bool 4598 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4599 CallingConv::ID CalleeCC, 4600 bool isVarArg, 4601 const SmallVectorImpl<ISD::InputArg> &Ins, 4602 SelectionDAG& DAG) const { 4603 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4604 return false; 4605 4606 // Variable argument functions are not supported. 4607 if (isVarArg) 4608 return false; 4609 4610 MachineFunction &MF = DAG.getMachineFunction(); 4611 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4612 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4613 // Functions containing by val parameters are not supported. 4614 for (unsigned i = 0; i != Ins.size(); i++) { 4615 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4616 if (Flags.isByVal()) return false; 4617 } 4618 4619 // Non-PIC/GOT tail calls are supported. 4620 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4621 return true; 4622 4623 // At the moment we can only do local tail calls (in same module, hidden 4624 // or protected) if we are generating PIC. 4625 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4626 return G->getGlobal()->hasHiddenVisibility() 4627 || G->getGlobal()->hasProtectedVisibility(); 4628 } 4629 4630 return false; 4631 } 4632 4633 /// isCallCompatibleAddress - Return the immediate to use if the specified 4634 /// 32-bit value is representable in the immediate field of a BxA instruction. 4635 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4636 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4637 if (!C) return nullptr; 4638 4639 int Addr = C->getZExtValue(); 4640 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4641 SignExtend32<26>(Addr) != Addr) 4642 return nullptr; // Top 6 bits have to be sext of immediate. 4643 4644 return DAG 4645 .getConstant( 4646 (int)C->getZExtValue() >> 2, SDLoc(Op), 4647 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4648 .getNode(); 4649 } 4650 4651 namespace { 4652 4653 struct TailCallArgumentInfo { 4654 SDValue Arg; 4655 SDValue FrameIdxOp; 4656 int FrameIdx = 0; 4657 4658 TailCallArgumentInfo() = default; 4659 }; 4660 4661 } // end anonymous namespace 4662 4663 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4664 static void StoreTailCallArgumentsToStackSlot( 4665 SelectionDAG &DAG, SDValue Chain, 4666 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4667 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4668 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4669 SDValue Arg = TailCallArgs[i].Arg; 4670 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4671 int FI = TailCallArgs[i].FrameIdx; 4672 // Store relative to framepointer. 4673 MemOpChains.push_back(DAG.getStore( 4674 Chain, dl, Arg, FIN, 4675 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4676 } 4677 } 4678 4679 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4680 /// the appropriate stack slot for the tail call optimized function call. 4681 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4682 SDValue OldRetAddr, SDValue OldFP, 4683 int SPDiff, const SDLoc &dl) { 4684 if (SPDiff) { 4685 // Calculate the new stack slot for the return address. 4686 MachineFunction &MF = DAG.getMachineFunction(); 4687 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4688 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4689 bool isPPC64 = Subtarget.isPPC64(); 4690 int SlotSize = isPPC64 ? 8 : 4; 4691 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4692 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4693 NewRetAddrLoc, true); 4694 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4695 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4696 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4697 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4698 4699 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4700 // slot as the FP is never overwritten. 4701 if (Subtarget.isDarwinABI()) { 4702 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4703 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4704 true); 4705 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4706 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4707 MachinePointerInfo::getFixedStack( 4708 DAG.getMachineFunction(), NewFPIdx)); 4709 } 4710 } 4711 return Chain; 4712 } 4713 4714 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4715 /// the position of the argument. 4716 static void 4717 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4718 SDValue Arg, int SPDiff, unsigned ArgOffset, 4719 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4720 int Offset = ArgOffset + SPDiff; 4721 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4722 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4723 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4724 SDValue FIN = DAG.getFrameIndex(FI, VT); 4725 TailCallArgumentInfo Info; 4726 Info.Arg = Arg; 4727 Info.FrameIdxOp = FIN; 4728 Info.FrameIdx = FI; 4729 TailCallArguments.push_back(Info); 4730 } 4731 4732 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4733 /// stack slot. Returns the chain as result and the loaded frame pointers in 4734 /// LROpOut/FPOpout. Used when tail calling. 4735 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4736 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4737 SDValue &FPOpOut, const SDLoc &dl) const { 4738 if (SPDiff) { 4739 // Load the LR and FP stack slot for later adjusting. 4740 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4741 LROpOut = getReturnAddrFrameIndex(DAG); 4742 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4743 Chain = SDValue(LROpOut.getNode(), 1); 4744 4745 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4746 // slot as the FP is never overwritten. 4747 if (Subtarget.isDarwinABI()) { 4748 FPOpOut = getFramePointerFrameIndex(DAG); 4749 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4750 Chain = SDValue(FPOpOut.getNode(), 1); 4751 } 4752 } 4753 return Chain; 4754 } 4755 4756 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4757 /// by "Src" to address "Dst" of size "Size". Alignment information is 4758 /// specified by the specific parameter attribute. The copy will be passed as 4759 /// a byval function parameter. 4760 /// Sometimes what we are copying is the end of a larger object, the part that 4761 /// does not fit in registers. 4762 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4763 SDValue Chain, ISD::ArgFlagsTy Flags, 4764 SelectionDAG &DAG, const SDLoc &dl) { 4765 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4766 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4767 false, false, false, MachinePointerInfo(), 4768 MachinePointerInfo()); 4769 } 4770 4771 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4772 /// tail calls. 4773 static void LowerMemOpCallTo( 4774 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4775 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4776 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4777 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4778 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4779 if (!isTailCall) { 4780 if (isVector) { 4781 SDValue StackPtr; 4782 if (isPPC64) 4783 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4784 else 4785 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4786 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4787 DAG.getConstant(ArgOffset, dl, PtrVT)); 4788 } 4789 MemOpChains.push_back( 4790 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4791 // Calculate and remember argument location. 4792 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4793 TailCallArguments); 4794 } 4795 4796 static void 4797 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4798 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4799 SDValue FPOp, 4800 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4801 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4802 // might overwrite each other in case of tail call optimization. 4803 SmallVector<SDValue, 8> MemOpChains2; 4804 // Do not flag preceding copytoreg stuff together with the following stuff. 4805 InFlag = SDValue(); 4806 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4807 MemOpChains2, dl); 4808 if (!MemOpChains2.empty()) 4809 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4810 4811 // Store the return address to the appropriate stack slot. 4812 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4813 4814 // Emit callseq_end just before tailcall node. 4815 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4816 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4817 InFlag = Chain.getValue(1); 4818 } 4819 4820 // Is this global address that of a function that can be called by name? (as 4821 // opposed to something that must hold a descriptor for an indirect call). 4822 static bool isFunctionGlobalAddress(SDValue Callee) { 4823 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4824 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4825 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4826 return false; 4827 4828 return G->getGlobal()->getValueType()->isFunctionTy(); 4829 } 4830 4831 return false; 4832 } 4833 4834 static unsigned 4835 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4836 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4837 bool isPatchPoint, bool hasNest, 4838 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4839 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4840 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4841 bool isPPC64 = Subtarget.isPPC64(); 4842 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4843 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4844 4845 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4846 NodeTys.push_back(MVT::Other); // Returns a chain 4847 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4848 4849 unsigned CallOpc = PPCISD::CALL; 4850 4851 bool needIndirectCall = true; 4852 if (!isSVR4ABI || !isPPC64) 4853 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4854 // If this is an absolute destination address, use the munged value. 4855 Callee = SDValue(Dest, 0); 4856 needIndirectCall = false; 4857 } 4858 4859 // PC-relative references to external symbols should go through $stub, unless 4860 // we're building with the leopard linker or later, which automatically 4861 // synthesizes these stubs. 4862 const TargetMachine &TM = DAG.getTarget(); 4863 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4864 const GlobalValue *GV = nullptr; 4865 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4866 GV = G->getGlobal(); 4867 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4868 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4869 4870 if (isFunctionGlobalAddress(Callee)) { 4871 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4872 // A call to a TLS address is actually an indirect call to a 4873 // thread-specific pointer. 4874 unsigned OpFlags = 0; 4875 if (UsePlt) 4876 OpFlags = PPCII::MO_PLT; 4877 4878 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4879 // every direct call is) turn it into a TargetGlobalAddress / 4880 // TargetExternalSymbol node so that legalize doesn't hack it. 4881 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4882 Callee.getValueType(), 0, OpFlags); 4883 needIndirectCall = false; 4884 } 4885 4886 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4887 unsigned char OpFlags = 0; 4888 4889 if (UsePlt) 4890 OpFlags = PPCII::MO_PLT; 4891 4892 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4893 OpFlags); 4894 needIndirectCall = false; 4895 } 4896 4897 if (isPatchPoint) { 4898 // We'll form an invalid direct call when lowering a patchpoint; the full 4899 // sequence for an indirect call is complicated, and many of the 4900 // instructions introduced might have side effects (and, thus, can't be 4901 // removed later). The call itself will be removed as soon as the 4902 // argument/return lowering is complete, so the fact that it has the wrong 4903 // kind of operands should not really matter. 4904 needIndirectCall = false; 4905 } 4906 4907 if (needIndirectCall) { 4908 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4909 // to do the call, we can't use PPCISD::CALL. 4910 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4911 4912 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4913 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4914 // entry point, but to the function descriptor (the function entry point 4915 // address is part of the function descriptor though). 4916 // The function descriptor is a three doubleword structure with the 4917 // following fields: function entry point, TOC base address and 4918 // environment pointer. 4919 // Thus for a call through a function pointer, the following actions need 4920 // to be performed: 4921 // 1. Save the TOC of the caller in the TOC save area of its stack 4922 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4923 // 2. Load the address of the function entry point from the function 4924 // descriptor. 4925 // 3. Load the TOC of the callee from the function descriptor into r2. 4926 // 4. Load the environment pointer from the function descriptor into 4927 // r11. 4928 // 5. Branch to the function entry point address. 4929 // 6. On return of the callee, the TOC of the caller needs to be 4930 // restored (this is done in FinishCall()). 4931 // 4932 // The loads are scheduled at the beginning of the call sequence, and the 4933 // register copies are flagged together to ensure that no other 4934 // operations can be scheduled in between. E.g. without flagging the 4935 // copies together, a TOC access in the caller could be scheduled between 4936 // the assignment of the callee TOC and the branch to the callee, which 4937 // results in the TOC access going through the TOC of the callee instead 4938 // of going through the TOC of the caller, which leads to incorrect code. 4939 4940 // Load the address of the function entry point from the function 4941 // descriptor. 4942 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4943 if (LDChain.getValueType() == MVT::Glue) 4944 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4945 4946 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4947 ? (MachineMemOperand::MODereferenceable | 4948 MachineMemOperand::MOInvariant) 4949 : MachineMemOperand::MONone; 4950 4951 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4952 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4953 /* Alignment = */ 8, MMOFlags); 4954 4955 // Load environment pointer into r11. 4956 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4957 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4958 SDValue LoadEnvPtr = 4959 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4960 /* Alignment = */ 8, MMOFlags); 4961 4962 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4963 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4964 SDValue TOCPtr = 4965 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4966 /* Alignment = */ 8, MMOFlags); 4967 4968 setUsesTOCBasePtr(DAG); 4969 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4970 InFlag); 4971 Chain = TOCVal.getValue(0); 4972 InFlag = TOCVal.getValue(1); 4973 4974 // If the function call has an explicit 'nest' parameter, it takes the 4975 // place of the environment pointer. 4976 if (!hasNest) { 4977 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4978 InFlag); 4979 4980 Chain = EnvVal.getValue(0); 4981 InFlag = EnvVal.getValue(1); 4982 } 4983 4984 MTCTROps[0] = Chain; 4985 MTCTROps[1] = LoadFuncPtr; 4986 MTCTROps[2] = InFlag; 4987 } 4988 4989 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4990 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4991 InFlag = Chain.getValue(1); 4992 4993 NodeTys.clear(); 4994 NodeTys.push_back(MVT::Other); 4995 NodeTys.push_back(MVT::Glue); 4996 Ops.push_back(Chain); 4997 CallOpc = PPCISD::BCTRL; 4998 Callee.setNode(nullptr); 4999 // Add use of X11 (holding environment pointer) 5000 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5001 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5002 // Add CTR register as callee so a bctr can be emitted later. 5003 if (isTailCall) 5004 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5005 } 5006 5007 // If this is a direct call, pass the chain and the callee. 5008 if (Callee.getNode()) { 5009 Ops.push_back(Chain); 5010 Ops.push_back(Callee); 5011 } 5012 // If this is a tail call add stack pointer delta. 5013 if (isTailCall) 5014 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5015 5016 // Add argument registers to the end of the list so that they are known live 5017 // into the call. 5018 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5019 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5020 RegsToPass[i].second.getValueType())); 5021 5022 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5023 // into the call. 5024 // We do need to reserve X2 to appease the verifier for the PATCHPOINT. 5025 if (isSVR4ABI && isPPC64) { 5026 setUsesTOCBasePtr(DAG); 5027 5028 // We cannot add X2 as an operand here for PATCHPOINT, because there is no 5029 // way to mark dependencies as implicit here. We will add the X2 dependency 5030 // in EmitInstrWithCustomInserter. 5031 if (!isPatchPoint) 5032 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5033 } 5034 5035 return CallOpc; 5036 } 5037 5038 SDValue PPCTargetLowering::LowerCallResult( 5039 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5040 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5041 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5042 SmallVector<CCValAssign, 16> RVLocs; 5043 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5044 *DAG.getContext()); 5045 5046 CCRetInfo.AnalyzeCallResult( 5047 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5048 ? RetCC_PPC_Cold 5049 : RetCC_PPC); 5050 5051 // Copy all of the result registers out of their specified physreg. 5052 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5053 CCValAssign &VA = RVLocs[i]; 5054 assert(VA.isRegLoc() && "Can only return in registers!"); 5055 5056 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5057 VA.getLocReg(), VA.getLocVT(), InFlag); 5058 Chain = Val.getValue(1); 5059 InFlag = Val.getValue(2); 5060 5061 switch (VA.getLocInfo()) { 5062 default: llvm_unreachable("Unknown loc info!"); 5063 case CCValAssign::Full: break; 5064 case CCValAssign::AExt: 5065 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5066 break; 5067 case CCValAssign::ZExt: 5068 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5069 DAG.getValueType(VA.getValVT())); 5070 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5071 break; 5072 case CCValAssign::SExt: 5073 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5074 DAG.getValueType(VA.getValVT())); 5075 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5076 break; 5077 } 5078 5079 InVals.push_back(Val); 5080 } 5081 5082 return Chain; 5083 } 5084 5085 SDValue PPCTargetLowering::FinishCall( 5086 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5087 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5088 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5089 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5090 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5091 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5092 std::vector<EVT> NodeTys; 5093 SmallVector<SDValue, 8> Ops; 5094 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5095 SPDiff, isTailCall, isPatchPoint, hasNest, 5096 RegsToPass, Ops, NodeTys, CS, Subtarget); 5097 5098 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5099 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5100 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5101 5102 // When performing tail call optimization the callee pops its arguments off 5103 // the stack. Account for this here so these bytes can be pushed back on in 5104 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5105 int BytesCalleePops = 5106 (CallConv == CallingConv::Fast && 5107 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5108 5109 // Add a register mask operand representing the call-preserved registers. 5110 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5111 const uint32_t *Mask = 5112 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5113 assert(Mask && "Missing call preserved mask for calling convention"); 5114 Ops.push_back(DAG.getRegisterMask(Mask)); 5115 5116 if (InFlag.getNode()) 5117 Ops.push_back(InFlag); 5118 5119 // Emit tail call. 5120 if (isTailCall) { 5121 assert(((Callee.getOpcode() == ISD::Register && 5122 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5123 Callee.getOpcode() == ISD::TargetExternalSymbol || 5124 Callee.getOpcode() == ISD::TargetGlobalAddress || 5125 isa<ConstantSDNode>(Callee)) && 5126 "Expecting an global address, external symbol, absolute value or register"); 5127 5128 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5129 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5130 } 5131 5132 // Add a NOP immediately after the branch instruction when using the 64-bit 5133 // SVR4 ABI. At link time, if caller and callee are in a different module and 5134 // thus have a different TOC, the call will be replaced with a call to a stub 5135 // function which saves the current TOC, loads the TOC of the callee and 5136 // branches to the callee. The NOP will be replaced with a load instruction 5137 // which restores the TOC of the caller from the TOC save slot of the current 5138 // stack frame. If caller and callee belong to the same module (and have the 5139 // same TOC), the NOP will remain unchanged. 5140 5141 MachineFunction &MF = DAG.getMachineFunction(); 5142 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5143 !isPatchPoint) { 5144 if (CallOpc == PPCISD::BCTRL) { 5145 // This is a call through a function pointer. 5146 // Restore the caller TOC from the save area into R2. 5147 // See PrepareCall() for more information about calls through function 5148 // pointers in the 64-bit SVR4 ABI. 5149 // We are using a target-specific load with r2 hard coded, because the 5150 // result of a target-independent load would never go directly into r2, 5151 // since r2 is a reserved register (which prevents the register allocator 5152 // from allocating it), resulting in an additional register being 5153 // allocated and an unnecessary move instruction being generated. 5154 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5155 5156 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5157 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5158 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5159 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5160 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5161 5162 // The address needs to go after the chain input but before the flag (or 5163 // any other variadic arguments). 5164 Ops.insert(std::next(Ops.begin()), AddTOC); 5165 } else if (CallOpc == PPCISD::CALL && 5166 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5167 // Otherwise insert NOP for non-local calls. 5168 CallOpc = PPCISD::CALL_NOP; 5169 } 5170 } 5171 5172 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5173 InFlag = Chain.getValue(1); 5174 5175 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5176 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5177 InFlag, dl); 5178 if (!Ins.empty()) 5179 InFlag = Chain.getValue(1); 5180 5181 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5182 Ins, dl, DAG, InVals); 5183 } 5184 5185 SDValue 5186 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5187 SmallVectorImpl<SDValue> &InVals) const { 5188 SelectionDAG &DAG = CLI.DAG; 5189 SDLoc &dl = CLI.DL; 5190 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5191 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5192 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5193 SDValue Chain = CLI.Chain; 5194 SDValue Callee = CLI.Callee; 5195 bool &isTailCall = CLI.IsTailCall; 5196 CallingConv::ID CallConv = CLI.CallConv; 5197 bool isVarArg = CLI.IsVarArg; 5198 bool isPatchPoint = CLI.IsPatchPoint; 5199 ImmutableCallSite CS = CLI.CS; 5200 5201 if (isTailCall) { 5202 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5203 isTailCall = false; 5204 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5205 isTailCall = 5206 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5207 isVarArg, Outs, Ins, DAG); 5208 else 5209 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5210 Ins, DAG); 5211 if (isTailCall) { 5212 ++NumTailCalls; 5213 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5214 ++NumSiblingCalls; 5215 5216 assert(isa<GlobalAddressSDNode>(Callee) && 5217 "Callee should be an llvm::Function object."); 5218 LLVM_DEBUG( 5219 const GlobalValue *GV = 5220 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5221 const unsigned Width = 5222 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5223 dbgs() << "TCO caller: " 5224 << left_justify(DAG.getMachineFunction().getName(), Width) 5225 << ", callee linkage: " << GV->getVisibility() << ", " 5226 << GV->getLinkage() << "\n"); 5227 } 5228 } 5229 5230 if (!isTailCall && CS && CS.isMustTailCall()) 5231 report_fatal_error("failed to perform tail call elimination on a call " 5232 "site marked musttail"); 5233 5234 // When long calls (i.e. indirect calls) are always used, calls are always 5235 // made via function pointer. If we have a function name, first translate it 5236 // into a pointer. 5237 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5238 !isTailCall) 5239 Callee = LowerGlobalAddress(Callee, DAG); 5240 5241 if (Subtarget.isSVR4ABI()) { 5242 if (Subtarget.isPPC64()) 5243 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5244 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5245 dl, DAG, InVals, CS); 5246 else 5247 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5248 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5249 dl, DAG, InVals, CS); 5250 } 5251 5252 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5253 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5254 dl, DAG, InVals, CS); 5255 } 5256 5257 SDValue PPCTargetLowering::LowerCall_32SVR4( 5258 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5259 bool isTailCall, bool isPatchPoint, 5260 const SmallVectorImpl<ISD::OutputArg> &Outs, 5261 const SmallVectorImpl<SDValue> &OutVals, 5262 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5263 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5264 ImmutableCallSite CS) const { 5265 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5266 // of the 32-bit SVR4 ABI stack frame layout. 5267 5268 assert((CallConv == CallingConv::C || 5269 CallConv == CallingConv::Cold || 5270 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5271 5272 unsigned PtrByteSize = 4; 5273 5274 MachineFunction &MF = DAG.getMachineFunction(); 5275 5276 // Mark this function as potentially containing a function that contains a 5277 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5278 // and restoring the callers stack pointer in this functions epilog. This is 5279 // done because by tail calling the called function might overwrite the value 5280 // in this function's (MF) stack pointer stack slot 0(SP). 5281 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5282 CallConv == CallingConv::Fast) 5283 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5284 5285 // Count how many bytes are to be pushed on the stack, including the linkage 5286 // area, parameter list area and the part of the local variable space which 5287 // contains copies of aggregates which are passed by value. 5288 5289 // Assign locations to all of the outgoing arguments. 5290 SmallVector<CCValAssign, 16> ArgLocs; 5291 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5292 5293 // Reserve space for the linkage area on the stack. 5294 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5295 PtrByteSize); 5296 if (useSoftFloat()) 5297 CCInfo.PreAnalyzeCallOperands(Outs); 5298 5299 if (isVarArg) { 5300 // Handle fixed and variable vector arguments differently. 5301 // Fixed vector arguments go into registers as long as registers are 5302 // available. Variable vector arguments always go into memory. 5303 unsigned NumArgs = Outs.size(); 5304 5305 for (unsigned i = 0; i != NumArgs; ++i) { 5306 MVT ArgVT = Outs[i].VT; 5307 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5308 bool Result; 5309 5310 if (Outs[i].IsFixed) { 5311 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5312 CCInfo); 5313 } else { 5314 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5315 ArgFlags, CCInfo); 5316 } 5317 5318 if (Result) { 5319 #ifndef NDEBUG 5320 errs() << "Call operand #" << i << " has unhandled type " 5321 << EVT(ArgVT).getEVTString() << "\n"; 5322 #endif 5323 llvm_unreachable(nullptr); 5324 } 5325 } 5326 } else { 5327 // All arguments are treated the same. 5328 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5329 } 5330 CCInfo.clearWasPPCF128(); 5331 5332 // Assign locations to all of the outgoing aggregate by value arguments. 5333 SmallVector<CCValAssign, 16> ByValArgLocs; 5334 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5335 5336 // Reserve stack space for the allocations in CCInfo. 5337 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5338 5339 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5340 5341 // Size of the linkage area, parameter list area and the part of the local 5342 // space variable where copies of aggregates which are passed by value are 5343 // stored. 5344 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5345 5346 // Calculate by how many bytes the stack has to be adjusted in case of tail 5347 // call optimization. 5348 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5349 5350 // Adjust the stack pointer for the new arguments... 5351 // These operations are automatically eliminated by the prolog/epilog pass 5352 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5353 SDValue CallSeqStart = Chain; 5354 5355 // Load the return address and frame pointer so it can be moved somewhere else 5356 // later. 5357 SDValue LROp, FPOp; 5358 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5359 5360 // Set up a copy of the stack pointer for use loading and storing any 5361 // arguments that may not fit in the registers available for argument 5362 // passing. 5363 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5364 5365 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5366 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5367 SmallVector<SDValue, 8> MemOpChains; 5368 5369 bool seenFloatArg = false; 5370 // Walk the register/memloc assignments, inserting copies/loads. 5371 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5372 i != e; 5373 ++i) { 5374 CCValAssign &VA = ArgLocs[i]; 5375 SDValue Arg = OutVals[i]; 5376 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5377 5378 if (Flags.isByVal()) { 5379 // Argument is an aggregate which is passed by value, thus we need to 5380 // create a copy of it in the local variable space of the current stack 5381 // frame (which is the stack frame of the caller) and pass the address of 5382 // this copy to the callee. 5383 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5384 CCValAssign &ByValVA = ByValArgLocs[j++]; 5385 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5386 5387 // Memory reserved in the local variable space of the callers stack frame. 5388 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5389 5390 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5391 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5392 StackPtr, PtrOff); 5393 5394 // Create a copy of the argument in the local area of the current 5395 // stack frame. 5396 SDValue MemcpyCall = 5397 CreateCopyOfByValArgument(Arg, PtrOff, 5398 CallSeqStart.getNode()->getOperand(0), 5399 Flags, DAG, dl); 5400 5401 // This must go outside the CALLSEQ_START..END. 5402 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5403 SDLoc(MemcpyCall)); 5404 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5405 NewCallSeqStart.getNode()); 5406 Chain = CallSeqStart = NewCallSeqStart; 5407 5408 // Pass the address of the aggregate copy on the stack either in a 5409 // physical register or in the parameter list area of the current stack 5410 // frame to the callee. 5411 Arg = PtrOff; 5412 } 5413 5414 // When useCRBits() is true, there can be i1 arguments. 5415 // It is because getRegisterType(MVT::i1) => MVT::i1, 5416 // and for other integer types getRegisterType() => MVT::i32. 5417 // Extend i1 and ensure callee will get i32. 5418 if (Arg.getValueType() == MVT::i1) 5419 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5420 dl, MVT::i32, Arg); 5421 5422 if (VA.isRegLoc()) { 5423 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5424 // Put argument in a physical register. 5425 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5426 } else { 5427 // Put argument in the parameter list area of the current stack frame. 5428 assert(VA.isMemLoc()); 5429 unsigned LocMemOffset = VA.getLocMemOffset(); 5430 5431 if (!isTailCall) { 5432 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5433 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5434 StackPtr, PtrOff); 5435 5436 MemOpChains.push_back( 5437 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5438 } else { 5439 // Calculate and remember argument location. 5440 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5441 TailCallArguments); 5442 } 5443 } 5444 } 5445 5446 if (!MemOpChains.empty()) 5447 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5448 5449 // Build a sequence of copy-to-reg nodes chained together with token chain 5450 // and flag operands which copy the outgoing args into the appropriate regs. 5451 SDValue InFlag; 5452 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5453 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5454 RegsToPass[i].second, InFlag); 5455 InFlag = Chain.getValue(1); 5456 } 5457 5458 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5459 // registers. 5460 if (isVarArg) { 5461 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5462 SDValue Ops[] = { Chain, InFlag }; 5463 5464 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5465 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5466 5467 InFlag = Chain.getValue(1); 5468 } 5469 5470 if (isTailCall) 5471 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5472 TailCallArguments); 5473 5474 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5475 /* unused except on PPC64 ELFv1 */ false, DAG, 5476 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5477 NumBytes, Ins, InVals, CS); 5478 } 5479 5480 // Copy an argument into memory, being careful to do this outside the 5481 // call sequence for the call to which the argument belongs. 5482 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5483 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5484 SelectionDAG &DAG, const SDLoc &dl) const { 5485 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5486 CallSeqStart.getNode()->getOperand(0), 5487 Flags, DAG, dl); 5488 // The MEMCPY must go outside the CALLSEQ_START..END. 5489 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5490 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5491 SDLoc(MemcpyCall)); 5492 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5493 NewCallSeqStart.getNode()); 5494 return NewCallSeqStart; 5495 } 5496 5497 SDValue PPCTargetLowering::LowerCall_64SVR4( 5498 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5499 bool isTailCall, bool isPatchPoint, 5500 const SmallVectorImpl<ISD::OutputArg> &Outs, 5501 const SmallVectorImpl<SDValue> &OutVals, 5502 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5503 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5504 ImmutableCallSite CS) const { 5505 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5506 bool isLittleEndian = Subtarget.isLittleEndian(); 5507 unsigned NumOps = Outs.size(); 5508 bool hasNest = false; 5509 bool IsSibCall = false; 5510 5511 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5512 unsigned PtrByteSize = 8; 5513 5514 MachineFunction &MF = DAG.getMachineFunction(); 5515 5516 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5517 IsSibCall = true; 5518 5519 // Mark this function as potentially containing a function that contains a 5520 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5521 // and restoring the callers stack pointer in this functions epilog. This is 5522 // done because by tail calling the called function might overwrite the value 5523 // in this function's (MF) stack pointer stack slot 0(SP). 5524 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5525 CallConv == CallingConv::Fast) 5526 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5527 5528 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5529 "fastcc not supported on varargs functions"); 5530 5531 // Count how many bytes are to be pushed on the stack, including the linkage 5532 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5533 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5534 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5535 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5536 unsigned NumBytes = LinkageSize; 5537 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5538 unsigned &QFPR_idx = FPR_idx; 5539 5540 static const MCPhysReg GPR[] = { 5541 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5542 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5543 }; 5544 static const MCPhysReg VR[] = { 5545 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5546 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5547 }; 5548 5549 const unsigned NumGPRs = array_lengthof(GPR); 5550 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5551 const unsigned NumVRs = array_lengthof(VR); 5552 const unsigned NumQFPRs = NumFPRs; 5553 5554 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5555 // can be passed to the callee in registers. 5556 // For the fast calling convention, there is another check below. 5557 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5558 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5559 if (!HasParameterArea) { 5560 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5561 unsigned AvailableFPRs = NumFPRs; 5562 unsigned AvailableVRs = NumVRs; 5563 unsigned NumBytesTmp = NumBytes; 5564 for (unsigned i = 0; i != NumOps; ++i) { 5565 if (Outs[i].Flags.isNest()) continue; 5566 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5567 PtrByteSize, LinkageSize, ParamAreaSize, 5568 NumBytesTmp, AvailableFPRs, AvailableVRs, 5569 Subtarget.hasQPX())) 5570 HasParameterArea = true; 5571 } 5572 } 5573 5574 // When using the fast calling convention, we don't provide backing for 5575 // arguments that will be in registers. 5576 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5577 5578 // Avoid allocating parameter area for fastcc functions if all the arguments 5579 // can be passed in the registers. 5580 if (CallConv == CallingConv::Fast) 5581 HasParameterArea = false; 5582 5583 // Add up all the space actually used. 5584 for (unsigned i = 0; i != NumOps; ++i) { 5585 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5586 EVT ArgVT = Outs[i].VT; 5587 EVT OrigVT = Outs[i].ArgVT; 5588 5589 if (Flags.isNest()) 5590 continue; 5591 5592 if (CallConv == CallingConv::Fast) { 5593 if (Flags.isByVal()) { 5594 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5595 if (NumGPRsUsed > NumGPRs) 5596 HasParameterArea = true; 5597 } else { 5598 switch (ArgVT.getSimpleVT().SimpleTy) { 5599 default: llvm_unreachable("Unexpected ValueType for argument!"); 5600 case MVT::i1: 5601 case MVT::i32: 5602 case MVT::i64: 5603 if (++NumGPRsUsed <= NumGPRs) 5604 continue; 5605 break; 5606 case MVT::v4i32: 5607 case MVT::v8i16: 5608 case MVT::v16i8: 5609 case MVT::v2f64: 5610 case MVT::v2i64: 5611 case MVT::v1i128: 5612 case MVT::f128: 5613 if (++NumVRsUsed <= NumVRs) 5614 continue; 5615 break; 5616 case MVT::v4f32: 5617 // When using QPX, this is handled like a FP register, otherwise, it 5618 // is an Altivec register. 5619 if (Subtarget.hasQPX()) { 5620 if (++NumFPRsUsed <= NumFPRs) 5621 continue; 5622 } else { 5623 if (++NumVRsUsed <= NumVRs) 5624 continue; 5625 } 5626 break; 5627 case MVT::f32: 5628 case MVT::f64: 5629 case MVT::v4f64: // QPX 5630 case MVT::v4i1: // QPX 5631 if (++NumFPRsUsed <= NumFPRs) 5632 continue; 5633 break; 5634 } 5635 HasParameterArea = true; 5636 } 5637 } 5638 5639 /* Respect alignment of argument on the stack. */ 5640 unsigned Align = 5641 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5642 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5643 5644 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5645 if (Flags.isInConsecutiveRegsLast()) 5646 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5647 } 5648 5649 unsigned NumBytesActuallyUsed = NumBytes; 5650 5651 // In the old ELFv1 ABI, 5652 // the prolog code of the callee may store up to 8 GPR argument registers to 5653 // the stack, allowing va_start to index over them in memory if its varargs. 5654 // Because we cannot tell if this is needed on the caller side, we have to 5655 // conservatively assume that it is needed. As such, make sure we have at 5656 // least enough stack space for the caller to store the 8 GPRs. 5657 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5658 // really requires memory operands, e.g. a vararg function. 5659 if (HasParameterArea) 5660 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5661 else 5662 NumBytes = LinkageSize; 5663 5664 // Tail call needs the stack to be aligned. 5665 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5666 CallConv == CallingConv::Fast) 5667 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5668 5669 int SPDiff = 0; 5670 5671 // Calculate by how many bytes the stack has to be adjusted in case of tail 5672 // call optimization. 5673 if (!IsSibCall) 5674 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5675 5676 // To protect arguments on the stack from being clobbered in a tail call, 5677 // force all the loads to happen before doing any other lowering. 5678 if (isTailCall) 5679 Chain = DAG.getStackArgumentTokenFactor(Chain); 5680 5681 // Adjust the stack pointer for the new arguments... 5682 // These operations are automatically eliminated by the prolog/epilog pass 5683 if (!IsSibCall) 5684 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5685 SDValue CallSeqStart = Chain; 5686 5687 // Load the return address and frame pointer so it can be move somewhere else 5688 // later. 5689 SDValue LROp, FPOp; 5690 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5691 5692 // Set up a copy of the stack pointer for use loading and storing any 5693 // arguments that may not fit in the registers available for argument 5694 // passing. 5695 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5696 5697 // Figure out which arguments are going to go in registers, and which in 5698 // memory. Also, if this is a vararg function, floating point operations 5699 // must be stored to our stack, and loaded into integer regs as well, if 5700 // any integer regs are available for argument passing. 5701 unsigned ArgOffset = LinkageSize; 5702 5703 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5704 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5705 5706 SmallVector<SDValue, 8> MemOpChains; 5707 for (unsigned i = 0; i != NumOps; ++i) { 5708 SDValue Arg = OutVals[i]; 5709 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5710 EVT ArgVT = Outs[i].VT; 5711 EVT OrigVT = Outs[i].ArgVT; 5712 5713 // PtrOff will be used to store the current argument to the stack if a 5714 // register cannot be found for it. 5715 SDValue PtrOff; 5716 5717 // We re-align the argument offset for each argument, except when using the 5718 // fast calling convention, when we need to make sure we do that only when 5719 // we'll actually use a stack slot. 5720 auto ComputePtrOff = [&]() { 5721 /* Respect alignment of argument on the stack. */ 5722 unsigned Align = 5723 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5724 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5725 5726 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5727 5728 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5729 }; 5730 5731 if (CallConv != CallingConv::Fast) { 5732 ComputePtrOff(); 5733 5734 /* Compute GPR index associated with argument offset. */ 5735 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5736 GPR_idx = std::min(GPR_idx, NumGPRs); 5737 } 5738 5739 // Promote integers to 64-bit values. 5740 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5741 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5742 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5743 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5744 } 5745 5746 // FIXME memcpy is used way more than necessary. Correctness first. 5747 // Note: "by value" is code for passing a structure by value, not 5748 // basic types. 5749 if (Flags.isByVal()) { 5750 // Note: Size includes alignment padding, so 5751 // struct x { short a; char b; } 5752 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5753 // These are the proper values we need for right-justifying the 5754 // aggregate in a parameter register. 5755 unsigned Size = Flags.getByValSize(); 5756 5757 // An empty aggregate parameter takes up no storage and no 5758 // registers. 5759 if (Size == 0) 5760 continue; 5761 5762 if (CallConv == CallingConv::Fast) 5763 ComputePtrOff(); 5764 5765 // All aggregates smaller than 8 bytes must be passed right-justified. 5766 if (Size==1 || Size==2 || Size==4) { 5767 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5768 if (GPR_idx != NumGPRs) { 5769 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5770 MachinePointerInfo(), VT); 5771 MemOpChains.push_back(Load.getValue(1)); 5772 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5773 5774 ArgOffset += PtrByteSize; 5775 continue; 5776 } 5777 } 5778 5779 if (GPR_idx == NumGPRs && Size < 8) { 5780 SDValue AddPtr = PtrOff; 5781 if (!isLittleEndian) { 5782 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5783 PtrOff.getValueType()); 5784 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5785 } 5786 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5787 CallSeqStart, 5788 Flags, DAG, dl); 5789 ArgOffset += PtrByteSize; 5790 continue; 5791 } 5792 // Copy entire object into memory. There are cases where gcc-generated 5793 // code assumes it is there, even if it could be put entirely into 5794 // registers. (This is not what the doc says.) 5795 5796 // FIXME: The above statement is likely due to a misunderstanding of the 5797 // documents. All arguments must be copied into the parameter area BY 5798 // THE CALLEE in the event that the callee takes the address of any 5799 // formal argument. That has not yet been implemented. However, it is 5800 // reasonable to use the stack area as a staging area for the register 5801 // load. 5802 5803 // Skip this for small aggregates, as we will use the same slot for a 5804 // right-justified copy, below. 5805 if (Size >= 8) 5806 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5807 CallSeqStart, 5808 Flags, DAG, dl); 5809 5810 // When a register is available, pass a small aggregate right-justified. 5811 if (Size < 8 && GPR_idx != NumGPRs) { 5812 // The easiest way to get this right-justified in a register 5813 // is to copy the structure into the rightmost portion of a 5814 // local variable slot, then load the whole slot into the 5815 // register. 5816 // FIXME: The memcpy seems to produce pretty awful code for 5817 // small aggregates, particularly for packed ones. 5818 // FIXME: It would be preferable to use the slot in the 5819 // parameter save area instead of a new local variable. 5820 SDValue AddPtr = PtrOff; 5821 if (!isLittleEndian) { 5822 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5823 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5824 } 5825 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5826 CallSeqStart, 5827 Flags, DAG, dl); 5828 5829 // Load the slot into the register. 5830 SDValue Load = 5831 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5832 MemOpChains.push_back(Load.getValue(1)); 5833 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5834 5835 // Done with this argument. 5836 ArgOffset += PtrByteSize; 5837 continue; 5838 } 5839 5840 // For aggregates larger than PtrByteSize, copy the pieces of the 5841 // object that fit into registers from the parameter save area. 5842 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5843 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5844 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5845 if (GPR_idx != NumGPRs) { 5846 SDValue Load = 5847 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5848 MemOpChains.push_back(Load.getValue(1)); 5849 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5850 ArgOffset += PtrByteSize; 5851 } else { 5852 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5853 break; 5854 } 5855 } 5856 continue; 5857 } 5858 5859 switch (Arg.getSimpleValueType().SimpleTy) { 5860 default: llvm_unreachable("Unexpected ValueType for argument!"); 5861 case MVT::i1: 5862 case MVT::i32: 5863 case MVT::i64: 5864 if (Flags.isNest()) { 5865 // The 'nest' parameter, if any, is passed in R11. 5866 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5867 hasNest = true; 5868 break; 5869 } 5870 5871 // These can be scalar arguments or elements of an integer array type 5872 // passed directly. Clang may use those instead of "byval" aggregate 5873 // types to avoid forcing arguments to memory unnecessarily. 5874 if (GPR_idx != NumGPRs) { 5875 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5876 } else { 5877 if (CallConv == CallingConv::Fast) 5878 ComputePtrOff(); 5879 5880 assert(HasParameterArea && 5881 "Parameter area must exist to pass an argument in memory."); 5882 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5883 true, isTailCall, false, MemOpChains, 5884 TailCallArguments, dl); 5885 if (CallConv == CallingConv::Fast) 5886 ArgOffset += PtrByteSize; 5887 } 5888 if (CallConv != CallingConv::Fast) 5889 ArgOffset += PtrByteSize; 5890 break; 5891 case MVT::f32: 5892 case MVT::f64: { 5893 // These can be scalar arguments or elements of a float array type 5894 // passed directly. The latter are used to implement ELFv2 homogenous 5895 // float aggregates. 5896 5897 // Named arguments go into FPRs first, and once they overflow, the 5898 // remaining arguments go into GPRs and then the parameter save area. 5899 // Unnamed arguments for vararg functions always go to GPRs and 5900 // then the parameter save area. For now, put all arguments to vararg 5901 // routines always in both locations (FPR *and* GPR or stack slot). 5902 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5903 bool NeededLoad = false; 5904 5905 // First load the argument into the next available FPR. 5906 if (FPR_idx != NumFPRs) 5907 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5908 5909 // Next, load the argument into GPR or stack slot if needed. 5910 if (!NeedGPROrStack) 5911 ; 5912 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5913 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5914 // once we support fp <-> gpr moves. 5915 5916 // In the non-vararg case, this can only ever happen in the 5917 // presence of f32 array types, since otherwise we never run 5918 // out of FPRs before running out of GPRs. 5919 SDValue ArgVal; 5920 5921 // Double values are always passed in a single GPR. 5922 if (Arg.getValueType() != MVT::f32) { 5923 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5924 5925 // Non-array float values are extended and passed in a GPR. 5926 } else if (!Flags.isInConsecutiveRegs()) { 5927 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5928 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5929 5930 // If we have an array of floats, we collect every odd element 5931 // together with its predecessor into one GPR. 5932 } else if (ArgOffset % PtrByteSize != 0) { 5933 SDValue Lo, Hi; 5934 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5935 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5936 if (!isLittleEndian) 5937 std::swap(Lo, Hi); 5938 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5939 5940 // The final element, if even, goes into the first half of a GPR. 5941 } else if (Flags.isInConsecutiveRegsLast()) { 5942 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5943 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5944 if (!isLittleEndian) 5945 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5946 DAG.getConstant(32, dl, MVT::i32)); 5947 5948 // Non-final even elements are skipped; they will be handled 5949 // together the with subsequent argument on the next go-around. 5950 } else 5951 ArgVal = SDValue(); 5952 5953 if (ArgVal.getNode()) 5954 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5955 } else { 5956 if (CallConv == CallingConv::Fast) 5957 ComputePtrOff(); 5958 5959 // Single-precision floating-point values are mapped to the 5960 // second (rightmost) word of the stack doubleword. 5961 if (Arg.getValueType() == MVT::f32 && 5962 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5963 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5964 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5965 } 5966 5967 assert(HasParameterArea && 5968 "Parameter area must exist to pass an argument in memory."); 5969 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5970 true, isTailCall, false, MemOpChains, 5971 TailCallArguments, dl); 5972 5973 NeededLoad = true; 5974 } 5975 // When passing an array of floats, the array occupies consecutive 5976 // space in the argument area; only round up to the next doubleword 5977 // at the end of the array. Otherwise, each float takes 8 bytes. 5978 if (CallConv != CallingConv::Fast || NeededLoad) { 5979 ArgOffset += (Arg.getValueType() == MVT::f32 && 5980 Flags.isInConsecutiveRegs()) ? 4 : 8; 5981 if (Flags.isInConsecutiveRegsLast()) 5982 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5983 } 5984 break; 5985 } 5986 case MVT::v4f32: 5987 case MVT::v4i32: 5988 case MVT::v8i16: 5989 case MVT::v16i8: 5990 case MVT::v2f64: 5991 case MVT::v2i64: 5992 case MVT::v1i128: 5993 case MVT::f128: 5994 if (!Subtarget.hasQPX()) { 5995 // These can be scalar arguments or elements of a vector array type 5996 // passed directly. The latter are used to implement ELFv2 homogenous 5997 // vector aggregates. 5998 5999 // For a varargs call, named arguments go into VRs or on the stack as 6000 // usual; unnamed arguments always go to the stack or the corresponding 6001 // GPRs when within range. For now, we always put the value in both 6002 // locations (or even all three). 6003 if (isVarArg) { 6004 assert(HasParameterArea && 6005 "Parameter area must exist if we have a varargs call."); 6006 // We could elide this store in the case where the object fits 6007 // entirely in R registers. Maybe later. 6008 SDValue Store = 6009 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6010 MemOpChains.push_back(Store); 6011 if (VR_idx != NumVRs) { 6012 SDValue Load = 6013 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6014 MemOpChains.push_back(Load.getValue(1)); 6015 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6016 } 6017 ArgOffset += 16; 6018 for (unsigned i=0; i<16; i+=PtrByteSize) { 6019 if (GPR_idx == NumGPRs) 6020 break; 6021 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6022 DAG.getConstant(i, dl, PtrVT)); 6023 SDValue Load = 6024 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6025 MemOpChains.push_back(Load.getValue(1)); 6026 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6027 } 6028 break; 6029 } 6030 6031 // Non-varargs Altivec params go into VRs or on the stack. 6032 if (VR_idx != NumVRs) { 6033 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6034 } else { 6035 if (CallConv == CallingConv::Fast) 6036 ComputePtrOff(); 6037 6038 assert(HasParameterArea && 6039 "Parameter area must exist to pass an argument in memory."); 6040 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6041 true, isTailCall, true, MemOpChains, 6042 TailCallArguments, dl); 6043 if (CallConv == CallingConv::Fast) 6044 ArgOffset += 16; 6045 } 6046 6047 if (CallConv != CallingConv::Fast) 6048 ArgOffset += 16; 6049 break; 6050 } // not QPX 6051 6052 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6053 "Invalid QPX parameter type"); 6054 6055 LLVM_FALLTHROUGH; 6056 case MVT::v4f64: 6057 case MVT::v4i1: { 6058 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6059 if (isVarArg) { 6060 assert(HasParameterArea && 6061 "Parameter area must exist if we have a varargs call."); 6062 // We could elide this store in the case where the object fits 6063 // entirely in R registers. Maybe later. 6064 SDValue Store = 6065 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6066 MemOpChains.push_back(Store); 6067 if (QFPR_idx != NumQFPRs) { 6068 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6069 PtrOff, MachinePointerInfo()); 6070 MemOpChains.push_back(Load.getValue(1)); 6071 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6072 } 6073 ArgOffset += (IsF32 ? 16 : 32); 6074 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6075 if (GPR_idx == NumGPRs) 6076 break; 6077 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6078 DAG.getConstant(i, dl, PtrVT)); 6079 SDValue Load = 6080 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6081 MemOpChains.push_back(Load.getValue(1)); 6082 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6083 } 6084 break; 6085 } 6086 6087 // Non-varargs QPX params go into registers or on the stack. 6088 if (QFPR_idx != NumQFPRs) { 6089 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6090 } else { 6091 if (CallConv == CallingConv::Fast) 6092 ComputePtrOff(); 6093 6094 assert(HasParameterArea && 6095 "Parameter area must exist to pass an argument in memory."); 6096 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6097 true, isTailCall, true, MemOpChains, 6098 TailCallArguments, dl); 6099 if (CallConv == CallingConv::Fast) 6100 ArgOffset += (IsF32 ? 16 : 32); 6101 } 6102 6103 if (CallConv != CallingConv::Fast) 6104 ArgOffset += (IsF32 ? 16 : 32); 6105 break; 6106 } 6107 } 6108 } 6109 6110 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6111 "mismatch in size of parameter area"); 6112 (void)NumBytesActuallyUsed; 6113 6114 if (!MemOpChains.empty()) 6115 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6116 6117 // Check if this is an indirect call (MTCTR/BCTRL). 6118 // See PrepareCall() for more information about calls through function 6119 // pointers in the 64-bit SVR4 ABI. 6120 if (!isTailCall && !isPatchPoint && 6121 !isFunctionGlobalAddress(Callee) && 6122 !isa<ExternalSymbolSDNode>(Callee)) { 6123 // Load r2 into a virtual register and store it to the TOC save area. 6124 setUsesTOCBasePtr(DAG); 6125 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6126 // TOC save area offset. 6127 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6128 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6129 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6130 Chain = DAG.getStore( 6131 Val.getValue(1), dl, Val, AddPtr, 6132 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6133 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6134 // This does not mean the MTCTR instruction must use R12; it's easier 6135 // to model this as an extra parameter, so do that. 6136 if (isELFv2ABI && !isPatchPoint) 6137 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6138 } 6139 6140 // Build a sequence of copy-to-reg nodes chained together with token chain 6141 // and flag operands which copy the outgoing args into the appropriate regs. 6142 SDValue InFlag; 6143 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6144 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6145 RegsToPass[i].second, InFlag); 6146 InFlag = Chain.getValue(1); 6147 } 6148 6149 if (isTailCall && !IsSibCall) 6150 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6151 TailCallArguments); 6152 6153 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6154 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6155 SPDiff, NumBytes, Ins, InVals, CS); 6156 } 6157 6158 SDValue PPCTargetLowering::LowerCall_Darwin( 6159 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6160 bool isTailCall, bool isPatchPoint, 6161 const SmallVectorImpl<ISD::OutputArg> &Outs, 6162 const SmallVectorImpl<SDValue> &OutVals, 6163 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6164 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6165 ImmutableCallSite CS) const { 6166 unsigned NumOps = Outs.size(); 6167 6168 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6169 bool isPPC64 = PtrVT == MVT::i64; 6170 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6171 6172 MachineFunction &MF = DAG.getMachineFunction(); 6173 6174 // Mark this function as potentially containing a function that contains a 6175 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6176 // and restoring the callers stack pointer in this functions epilog. This is 6177 // done because by tail calling the called function might overwrite the value 6178 // in this function's (MF) stack pointer stack slot 0(SP). 6179 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6180 CallConv == CallingConv::Fast) 6181 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6182 6183 // Count how many bytes are to be pushed on the stack, including the linkage 6184 // area, and parameter passing area. We start with 24/48 bytes, which is 6185 // prereserved space for [SP][CR][LR][3 x unused]. 6186 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6187 unsigned NumBytes = LinkageSize; 6188 6189 // Add up all the space actually used. 6190 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6191 // they all go in registers, but we must reserve stack space for them for 6192 // possible use by the caller. In varargs or 64-bit calls, parameters are 6193 // assigned stack space in order, with padding so Altivec parameters are 6194 // 16-byte aligned. 6195 unsigned nAltivecParamsAtEnd = 0; 6196 for (unsigned i = 0; i != NumOps; ++i) { 6197 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6198 EVT ArgVT = Outs[i].VT; 6199 // Varargs Altivec parameters are padded to a 16 byte boundary. 6200 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6201 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6202 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6203 if (!isVarArg && !isPPC64) { 6204 // Non-varargs Altivec parameters go after all the non-Altivec 6205 // parameters; handle those later so we know how much padding we need. 6206 nAltivecParamsAtEnd++; 6207 continue; 6208 } 6209 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6210 NumBytes = ((NumBytes+15)/16)*16; 6211 } 6212 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6213 } 6214 6215 // Allow for Altivec parameters at the end, if needed. 6216 if (nAltivecParamsAtEnd) { 6217 NumBytes = ((NumBytes+15)/16)*16; 6218 NumBytes += 16*nAltivecParamsAtEnd; 6219 } 6220 6221 // The prolog code of the callee may store up to 8 GPR argument registers to 6222 // the stack, allowing va_start to index over them in memory if its varargs. 6223 // Because we cannot tell if this is needed on the caller side, we have to 6224 // conservatively assume that it is needed. As such, make sure we have at 6225 // least enough stack space for the caller to store the 8 GPRs. 6226 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6227 6228 // Tail call needs the stack to be aligned. 6229 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6230 CallConv == CallingConv::Fast) 6231 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6232 6233 // Calculate by how many bytes the stack has to be adjusted in case of tail 6234 // call optimization. 6235 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6236 6237 // To protect arguments on the stack from being clobbered in a tail call, 6238 // force all the loads to happen before doing any other lowering. 6239 if (isTailCall) 6240 Chain = DAG.getStackArgumentTokenFactor(Chain); 6241 6242 // Adjust the stack pointer for the new arguments... 6243 // These operations are automatically eliminated by the prolog/epilog pass 6244 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6245 SDValue CallSeqStart = Chain; 6246 6247 // Load the return address and frame pointer so it can be move somewhere else 6248 // later. 6249 SDValue LROp, FPOp; 6250 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6251 6252 // Set up a copy of the stack pointer for use loading and storing any 6253 // arguments that may not fit in the registers available for argument 6254 // passing. 6255 SDValue StackPtr; 6256 if (isPPC64) 6257 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6258 else 6259 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6260 6261 // Figure out which arguments are going to go in registers, and which in 6262 // memory. Also, if this is a vararg function, floating point operations 6263 // must be stored to our stack, and loaded into integer regs as well, if 6264 // any integer regs are available for argument passing. 6265 unsigned ArgOffset = LinkageSize; 6266 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6267 6268 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6269 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6270 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6271 }; 6272 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6273 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6274 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6275 }; 6276 static const MCPhysReg VR[] = { 6277 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6278 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6279 }; 6280 const unsigned NumGPRs = array_lengthof(GPR_32); 6281 const unsigned NumFPRs = 13; 6282 const unsigned NumVRs = array_lengthof(VR); 6283 6284 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6285 6286 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6287 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6288 6289 SmallVector<SDValue, 8> MemOpChains; 6290 for (unsigned i = 0; i != NumOps; ++i) { 6291 SDValue Arg = OutVals[i]; 6292 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6293 6294 // PtrOff will be used to store the current argument to the stack if a 6295 // register cannot be found for it. 6296 SDValue PtrOff; 6297 6298 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6299 6300 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6301 6302 // On PPC64, promote integers to 64-bit values. 6303 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6304 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6305 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6306 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6307 } 6308 6309 // FIXME memcpy is used way more than necessary. Correctness first. 6310 // Note: "by value" is code for passing a structure by value, not 6311 // basic types. 6312 if (Flags.isByVal()) { 6313 unsigned Size = Flags.getByValSize(); 6314 // Very small objects are passed right-justified. Everything else is 6315 // passed left-justified. 6316 if (Size==1 || Size==2) { 6317 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6318 if (GPR_idx != NumGPRs) { 6319 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6320 MachinePointerInfo(), VT); 6321 MemOpChains.push_back(Load.getValue(1)); 6322 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6323 6324 ArgOffset += PtrByteSize; 6325 } else { 6326 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6327 PtrOff.getValueType()); 6328 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6329 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6330 CallSeqStart, 6331 Flags, DAG, dl); 6332 ArgOffset += PtrByteSize; 6333 } 6334 continue; 6335 } 6336 // Copy entire object into memory. There are cases where gcc-generated 6337 // code assumes it is there, even if it could be put entirely into 6338 // registers. (This is not what the doc says.) 6339 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6340 CallSeqStart, 6341 Flags, DAG, dl); 6342 6343 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6344 // copy the pieces of the object that fit into registers from the 6345 // parameter save area. 6346 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6347 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6348 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6349 if (GPR_idx != NumGPRs) { 6350 SDValue Load = 6351 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6352 MemOpChains.push_back(Load.getValue(1)); 6353 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6354 ArgOffset += PtrByteSize; 6355 } else { 6356 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6357 break; 6358 } 6359 } 6360 continue; 6361 } 6362 6363 switch (Arg.getSimpleValueType().SimpleTy) { 6364 default: llvm_unreachable("Unexpected ValueType for argument!"); 6365 case MVT::i1: 6366 case MVT::i32: 6367 case MVT::i64: 6368 if (GPR_idx != NumGPRs) { 6369 if (Arg.getValueType() == MVT::i1) 6370 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6371 6372 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6373 } else { 6374 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6375 isPPC64, isTailCall, false, MemOpChains, 6376 TailCallArguments, dl); 6377 } 6378 ArgOffset += PtrByteSize; 6379 break; 6380 case MVT::f32: 6381 case MVT::f64: 6382 if (FPR_idx != NumFPRs) { 6383 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6384 6385 if (isVarArg) { 6386 SDValue Store = 6387 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6388 MemOpChains.push_back(Store); 6389 6390 // Float varargs are always shadowed in available integer registers 6391 if (GPR_idx != NumGPRs) { 6392 SDValue Load = 6393 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6394 MemOpChains.push_back(Load.getValue(1)); 6395 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6396 } 6397 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6398 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6399 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6400 SDValue Load = 6401 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6402 MemOpChains.push_back(Load.getValue(1)); 6403 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6404 } 6405 } else { 6406 // If we have any FPRs remaining, we may also have GPRs remaining. 6407 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6408 // GPRs. 6409 if (GPR_idx != NumGPRs) 6410 ++GPR_idx; 6411 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6412 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6413 ++GPR_idx; 6414 } 6415 } else 6416 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6417 isPPC64, isTailCall, false, MemOpChains, 6418 TailCallArguments, dl); 6419 if (isPPC64) 6420 ArgOffset += 8; 6421 else 6422 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6423 break; 6424 case MVT::v4f32: 6425 case MVT::v4i32: 6426 case MVT::v8i16: 6427 case MVT::v16i8: 6428 if (isVarArg) { 6429 // These go aligned on the stack, or in the corresponding R registers 6430 // when within range. The Darwin PPC ABI doc claims they also go in 6431 // V registers; in fact gcc does this only for arguments that are 6432 // prototyped, not for those that match the ... We do it for all 6433 // arguments, seems to work. 6434 while (ArgOffset % 16 !=0) { 6435 ArgOffset += PtrByteSize; 6436 if (GPR_idx != NumGPRs) 6437 GPR_idx++; 6438 } 6439 // We could elide this store in the case where the object fits 6440 // entirely in R registers. Maybe later. 6441 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6442 DAG.getConstant(ArgOffset, dl, PtrVT)); 6443 SDValue Store = 6444 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6445 MemOpChains.push_back(Store); 6446 if (VR_idx != NumVRs) { 6447 SDValue Load = 6448 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6449 MemOpChains.push_back(Load.getValue(1)); 6450 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6451 } 6452 ArgOffset += 16; 6453 for (unsigned i=0; i<16; i+=PtrByteSize) { 6454 if (GPR_idx == NumGPRs) 6455 break; 6456 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6457 DAG.getConstant(i, dl, PtrVT)); 6458 SDValue Load = 6459 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6460 MemOpChains.push_back(Load.getValue(1)); 6461 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6462 } 6463 break; 6464 } 6465 6466 // Non-varargs Altivec params generally go in registers, but have 6467 // stack space allocated at the end. 6468 if (VR_idx != NumVRs) { 6469 // Doesn't have GPR space allocated. 6470 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6471 } else if (nAltivecParamsAtEnd==0) { 6472 // We are emitting Altivec params in order. 6473 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6474 isPPC64, isTailCall, true, MemOpChains, 6475 TailCallArguments, dl); 6476 ArgOffset += 16; 6477 } 6478 break; 6479 } 6480 } 6481 // If all Altivec parameters fit in registers, as they usually do, 6482 // they get stack space following the non-Altivec parameters. We 6483 // don't track this here because nobody below needs it. 6484 // If there are more Altivec parameters than fit in registers emit 6485 // the stores here. 6486 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6487 unsigned j = 0; 6488 // Offset is aligned; skip 1st 12 params which go in V registers. 6489 ArgOffset = ((ArgOffset+15)/16)*16; 6490 ArgOffset += 12*16; 6491 for (unsigned i = 0; i != NumOps; ++i) { 6492 SDValue Arg = OutVals[i]; 6493 EVT ArgType = Outs[i].VT; 6494 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6495 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6496 if (++j > NumVRs) { 6497 SDValue PtrOff; 6498 // We are emitting Altivec params in order. 6499 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6500 isPPC64, isTailCall, true, MemOpChains, 6501 TailCallArguments, dl); 6502 ArgOffset += 16; 6503 } 6504 } 6505 } 6506 } 6507 6508 if (!MemOpChains.empty()) 6509 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6510 6511 // On Darwin, R12 must contain the address of an indirect callee. This does 6512 // not mean the MTCTR instruction must use R12; it's easier to model this as 6513 // an extra parameter, so do that. 6514 if (!isTailCall && 6515 !isFunctionGlobalAddress(Callee) && 6516 !isa<ExternalSymbolSDNode>(Callee) && 6517 !isBLACompatibleAddress(Callee, DAG)) 6518 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6519 PPC::R12), Callee)); 6520 6521 // Build a sequence of copy-to-reg nodes chained together with token chain 6522 // and flag operands which copy the outgoing args into the appropriate regs. 6523 SDValue InFlag; 6524 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6525 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6526 RegsToPass[i].second, InFlag); 6527 InFlag = Chain.getValue(1); 6528 } 6529 6530 if (isTailCall) 6531 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6532 TailCallArguments); 6533 6534 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6535 /* unused except on PPC64 ELFv1 */ false, DAG, 6536 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6537 NumBytes, Ins, InVals, CS); 6538 } 6539 6540 bool 6541 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6542 MachineFunction &MF, bool isVarArg, 6543 const SmallVectorImpl<ISD::OutputArg> &Outs, 6544 LLVMContext &Context) const { 6545 SmallVector<CCValAssign, 16> RVLocs; 6546 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6547 return CCInfo.CheckReturn( 6548 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6549 ? RetCC_PPC_Cold 6550 : RetCC_PPC); 6551 } 6552 6553 SDValue 6554 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6555 bool isVarArg, 6556 const SmallVectorImpl<ISD::OutputArg> &Outs, 6557 const SmallVectorImpl<SDValue> &OutVals, 6558 const SDLoc &dl, SelectionDAG &DAG) const { 6559 SmallVector<CCValAssign, 16> RVLocs; 6560 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6561 *DAG.getContext()); 6562 CCInfo.AnalyzeReturn(Outs, 6563 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6564 ? RetCC_PPC_Cold 6565 : RetCC_PPC); 6566 6567 SDValue Flag; 6568 SmallVector<SDValue, 4> RetOps(1, Chain); 6569 6570 // Copy the result values into the output registers. 6571 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6572 CCValAssign &VA = RVLocs[i]; 6573 assert(VA.isRegLoc() && "Can only return in registers!"); 6574 6575 SDValue Arg = OutVals[i]; 6576 6577 switch (VA.getLocInfo()) { 6578 default: llvm_unreachable("Unknown loc info!"); 6579 case CCValAssign::Full: break; 6580 case CCValAssign::AExt: 6581 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6582 break; 6583 case CCValAssign::ZExt: 6584 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6585 break; 6586 case CCValAssign::SExt: 6587 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6588 break; 6589 } 6590 6591 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6592 Flag = Chain.getValue(1); 6593 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6594 } 6595 6596 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6597 const MCPhysReg *I = 6598 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6599 if (I) { 6600 for (; *I; ++I) { 6601 6602 if (PPC::G8RCRegClass.contains(*I)) 6603 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6604 else if (PPC::F8RCRegClass.contains(*I)) 6605 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6606 else if (PPC::CRRCRegClass.contains(*I)) 6607 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6608 else if (PPC::VRRCRegClass.contains(*I)) 6609 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6610 else 6611 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6612 } 6613 } 6614 6615 RetOps[0] = Chain; // Update chain. 6616 6617 // Add the flag if we have it. 6618 if (Flag.getNode()) 6619 RetOps.push_back(Flag); 6620 6621 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6622 } 6623 6624 SDValue 6625 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6626 SelectionDAG &DAG) const { 6627 SDLoc dl(Op); 6628 6629 // Get the correct type for integers. 6630 EVT IntVT = Op.getValueType(); 6631 6632 // Get the inputs. 6633 SDValue Chain = Op.getOperand(0); 6634 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6635 // Build a DYNAREAOFFSET node. 6636 SDValue Ops[2] = {Chain, FPSIdx}; 6637 SDVTList VTs = DAG.getVTList(IntVT); 6638 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6639 } 6640 6641 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6642 SelectionDAG &DAG) const { 6643 // When we pop the dynamic allocation we need to restore the SP link. 6644 SDLoc dl(Op); 6645 6646 // Get the correct type for pointers. 6647 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6648 6649 // Construct the stack pointer operand. 6650 bool isPPC64 = Subtarget.isPPC64(); 6651 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6652 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6653 6654 // Get the operands for the STACKRESTORE. 6655 SDValue Chain = Op.getOperand(0); 6656 SDValue SaveSP = Op.getOperand(1); 6657 6658 // Load the old link SP. 6659 SDValue LoadLinkSP = 6660 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6661 6662 // Restore the stack pointer. 6663 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6664 6665 // Store the old link SP. 6666 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6667 } 6668 6669 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6670 MachineFunction &MF = DAG.getMachineFunction(); 6671 bool isPPC64 = Subtarget.isPPC64(); 6672 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6673 6674 // Get current frame pointer save index. The users of this index will be 6675 // primarily DYNALLOC instructions. 6676 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6677 int RASI = FI->getReturnAddrSaveIndex(); 6678 6679 // If the frame pointer save index hasn't been defined yet. 6680 if (!RASI) { 6681 // Find out what the fix offset of the frame pointer save area. 6682 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6683 // Allocate the frame index for frame pointer save area. 6684 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6685 // Save the result. 6686 FI->setReturnAddrSaveIndex(RASI); 6687 } 6688 return DAG.getFrameIndex(RASI, PtrVT); 6689 } 6690 6691 SDValue 6692 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6693 MachineFunction &MF = DAG.getMachineFunction(); 6694 bool isPPC64 = Subtarget.isPPC64(); 6695 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6696 6697 // Get current frame pointer save index. The users of this index will be 6698 // primarily DYNALLOC instructions. 6699 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6700 int FPSI = FI->getFramePointerSaveIndex(); 6701 6702 // If the frame pointer save index hasn't been defined yet. 6703 if (!FPSI) { 6704 // Find out what the fix offset of the frame pointer save area. 6705 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6706 // Allocate the frame index for frame pointer save area. 6707 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6708 // Save the result. 6709 FI->setFramePointerSaveIndex(FPSI); 6710 } 6711 return DAG.getFrameIndex(FPSI, PtrVT); 6712 } 6713 6714 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6715 SelectionDAG &DAG) const { 6716 // Get the inputs. 6717 SDValue Chain = Op.getOperand(0); 6718 SDValue Size = Op.getOperand(1); 6719 SDLoc dl(Op); 6720 6721 // Get the correct type for pointers. 6722 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6723 // Negate the size. 6724 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6725 DAG.getConstant(0, dl, PtrVT), Size); 6726 // Construct a node for the frame pointer save index. 6727 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6728 // Build a DYNALLOC node. 6729 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6730 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6731 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6732 } 6733 6734 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6735 SelectionDAG &DAG) const { 6736 MachineFunction &MF = DAG.getMachineFunction(); 6737 6738 bool isPPC64 = Subtarget.isPPC64(); 6739 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6740 6741 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6742 return DAG.getFrameIndex(FI, PtrVT); 6743 } 6744 6745 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6746 SelectionDAG &DAG) const { 6747 SDLoc DL(Op); 6748 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6749 DAG.getVTList(MVT::i32, MVT::Other), 6750 Op.getOperand(0), Op.getOperand(1)); 6751 } 6752 6753 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6754 SelectionDAG &DAG) const { 6755 SDLoc DL(Op); 6756 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6757 Op.getOperand(0), Op.getOperand(1)); 6758 } 6759 6760 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6761 if (Op.getValueType().isVector()) 6762 return LowerVectorLoad(Op, DAG); 6763 6764 assert(Op.getValueType() == MVT::i1 && 6765 "Custom lowering only for i1 loads"); 6766 6767 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6768 6769 SDLoc dl(Op); 6770 LoadSDNode *LD = cast<LoadSDNode>(Op); 6771 6772 SDValue Chain = LD->getChain(); 6773 SDValue BasePtr = LD->getBasePtr(); 6774 MachineMemOperand *MMO = LD->getMemOperand(); 6775 6776 SDValue NewLD = 6777 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6778 BasePtr, MVT::i8, MMO); 6779 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6780 6781 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6782 return DAG.getMergeValues(Ops, dl); 6783 } 6784 6785 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6786 if (Op.getOperand(1).getValueType().isVector()) 6787 return LowerVectorStore(Op, DAG); 6788 6789 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6790 "Custom lowering only for i1 stores"); 6791 6792 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6793 6794 SDLoc dl(Op); 6795 StoreSDNode *ST = cast<StoreSDNode>(Op); 6796 6797 SDValue Chain = ST->getChain(); 6798 SDValue BasePtr = ST->getBasePtr(); 6799 SDValue Value = ST->getValue(); 6800 MachineMemOperand *MMO = ST->getMemOperand(); 6801 6802 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6803 Value); 6804 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6805 } 6806 6807 // FIXME: Remove this once the ANDI glue bug is fixed: 6808 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6809 assert(Op.getValueType() == MVT::i1 && 6810 "Custom lowering only for i1 results"); 6811 6812 SDLoc DL(Op); 6813 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6814 Op.getOperand(0)); 6815 } 6816 6817 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 6818 SelectionDAG &DAG) const { 6819 6820 // Implements a vector truncate that fits in a vector register as a shuffle. 6821 // We want to legalize vector truncates down to where the source fits in 6822 // a vector register (and target is therefore smaller than vector register 6823 // size). At that point legalization will try to custom lower the sub-legal 6824 // result and get here - where we can contain the truncate as a single target 6825 // operation. 6826 6827 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 6828 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 6829 // 6830 // We will implement it for big-endian ordering as this (where x denotes 6831 // undefined): 6832 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 6833 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 6834 // 6835 // The same operation in little-endian ordering will be: 6836 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 6837 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 6838 6839 assert(Op.getValueType().isVector() && "Vector type expected."); 6840 6841 SDLoc DL(Op); 6842 SDValue N1 = Op.getOperand(0); 6843 unsigned SrcSize = N1.getValueType().getSizeInBits(); 6844 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 6845 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 6846 6847 EVT TrgVT = Op.getValueType(); 6848 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 6849 EVT EltVT = TrgVT.getVectorElementType(); 6850 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 6851 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 6852 6853 // First list the elements we want to keep. 6854 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 6855 SmallVector<int, 16> ShuffV; 6856 if (Subtarget.isLittleEndian()) 6857 for (unsigned i = 0; i < TrgNumElts; ++i) 6858 ShuffV.push_back(i * SizeMult); 6859 else 6860 for (unsigned i = 1; i <= TrgNumElts; ++i) 6861 ShuffV.push_back(i * SizeMult - 1); 6862 6863 // Populate the remaining elements with undefs. 6864 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 6865 // ShuffV.push_back(i + WideNumElts); 6866 ShuffV.push_back(WideNumElts + 1); 6867 6868 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 6869 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 6870 } 6871 6872 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6873 /// possible. 6874 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6875 // Not FP? Not a fsel. 6876 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6877 !Op.getOperand(2).getValueType().isFloatingPoint()) 6878 return Op; 6879 6880 // We might be able to do better than this under some circumstances, but in 6881 // general, fsel-based lowering of select is a finite-math-only optimization. 6882 // For more information, see section F.3 of the 2.06 ISA specification. 6883 if (!DAG.getTarget().Options.NoInfsFPMath || 6884 !DAG.getTarget().Options.NoNaNsFPMath) 6885 return Op; 6886 // TODO: Propagate flags from the select rather than global settings. 6887 SDNodeFlags Flags; 6888 Flags.setNoInfs(true); 6889 Flags.setNoNaNs(true); 6890 6891 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6892 6893 EVT ResVT = Op.getValueType(); 6894 EVT CmpVT = Op.getOperand(0).getValueType(); 6895 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6896 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6897 SDLoc dl(Op); 6898 6899 // If the RHS of the comparison is a 0.0, we don't need to do the 6900 // subtraction at all. 6901 SDValue Sel1; 6902 if (isFloatingPointZero(RHS)) 6903 switch (CC) { 6904 default: break; // SETUO etc aren't handled by fsel. 6905 case ISD::SETNE: 6906 std::swap(TV, FV); 6907 LLVM_FALLTHROUGH; 6908 case ISD::SETEQ: 6909 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6910 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6911 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6912 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6913 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6914 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6915 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6916 case ISD::SETULT: 6917 case ISD::SETLT: 6918 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6919 LLVM_FALLTHROUGH; 6920 case ISD::SETOGE: 6921 case ISD::SETGE: 6922 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6923 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6924 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6925 case ISD::SETUGT: 6926 case ISD::SETGT: 6927 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6928 LLVM_FALLTHROUGH; 6929 case ISD::SETOLE: 6930 case ISD::SETLE: 6931 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6932 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6933 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6934 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6935 } 6936 6937 SDValue Cmp; 6938 switch (CC) { 6939 default: break; // SETUO etc aren't handled by fsel. 6940 case ISD::SETNE: 6941 std::swap(TV, FV); 6942 LLVM_FALLTHROUGH; 6943 case ISD::SETEQ: 6944 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6945 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6946 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6947 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6948 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6949 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6950 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6951 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6952 case ISD::SETULT: 6953 case ISD::SETLT: 6954 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6955 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6956 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6957 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6958 case ISD::SETOGE: 6959 case ISD::SETGE: 6960 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6961 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6962 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6963 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6964 case ISD::SETUGT: 6965 case ISD::SETGT: 6966 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6967 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6968 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6969 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6970 case ISD::SETOLE: 6971 case ISD::SETLE: 6972 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6973 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6974 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6975 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6976 } 6977 return Op; 6978 } 6979 6980 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6981 SelectionDAG &DAG, 6982 const SDLoc &dl) const { 6983 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6984 SDValue Src = Op.getOperand(0); 6985 if (Src.getValueType() == MVT::f32) 6986 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6987 6988 SDValue Tmp; 6989 switch (Op.getSimpleValueType().SimpleTy) { 6990 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6991 case MVT::i32: 6992 Tmp = DAG.getNode( 6993 Op.getOpcode() == ISD::FP_TO_SINT 6994 ? PPCISD::FCTIWZ 6995 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6996 dl, MVT::f64, Src); 6997 break; 6998 case MVT::i64: 6999 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7000 "i64 FP_TO_UINT is supported only with FPCVT"); 7001 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7002 PPCISD::FCTIDUZ, 7003 dl, MVT::f64, Src); 7004 break; 7005 } 7006 7007 // Convert the FP value to an int value through memory. 7008 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7009 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7010 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7011 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7012 MachinePointerInfo MPI = 7013 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7014 7015 // Emit a store to the stack slot. 7016 SDValue Chain; 7017 if (i32Stack) { 7018 MachineFunction &MF = DAG.getMachineFunction(); 7019 MachineMemOperand *MMO = 7020 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7021 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7022 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7023 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7024 } else 7025 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7026 7027 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7028 // add in a bias on big endian. 7029 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7030 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7031 DAG.getConstant(4, dl, FIPtr.getValueType())); 7032 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7033 } 7034 7035 RLI.Chain = Chain; 7036 RLI.Ptr = FIPtr; 7037 RLI.MPI = MPI; 7038 } 7039 7040 /// Custom lowers floating point to integer conversions to use 7041 /// the direct move instructions available in ISA 2.07 to avoid the 7042 /// need for load/store combinations. 7043 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7044 SelectionDAG &DAG, 7045 const SDLoc &dl) const { 7046 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7047 SDValue Src = Op.getOperand(0); 7048 7049 if (Src.getValueType() == MVT::f32) 7050 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7051 7052 SDValue Tmp; 7053 switch (Op.getSimpleValueType().SimpleTy) { 7054 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7055 case MVT::i32: 7056 Tmp = DAG.getNode( 7057 Op.getOpcode() == ISD::FP_TO_SINT 7058 ? PPCISD::FCTIWZ 7059 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7060 dl, MVT::f64, Src); 7061 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7062 break; 7063 case MVT::i64: 7064 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7065 "i64 FP_TO_UINT is supported only with FPCVT"); 7066 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7067 PPCISD::FCTIDUZ, 7068 dl, MVT::f64, Src); 7069 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7070 break; 7071 } 7072 return Tmp; 7073 } 7074 7075 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7076 const SDLoc &dl) const { 7077 7078 // FP to INT conversions are legal for f128. 7079 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7080 return Op; 7081 7082 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7083 // PPC (the libcall is not available). 7084 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7085 if (Op.getValueType() == MVT::i32) { 7086 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7087 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7088 MVT::f64, Op.getOperand(0), 7089 DAG.getIntPtrConstant(0, dl)); 7090 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7091 MVT::f64, Op.getOperand(0), 7092 DAG.getIntPtrConstant(1, dl)); 7093 7094 // Add the two halves of the long double in round-to-zero mode. 7095 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7096 7097 // Now use a smaller FP_TO_SINT. 7098 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7099 } 7100 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7101 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7102 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7103 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7104 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7105 // FIXME: generated code sucks. 7106 // TODO: Are there fast-math-flags to propagate to this FSUB? 7107 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7108 Op.getOperand(0), Tmp); 7109 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7110 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7111 DAG.getConstant(0x80000000, dl, MVT::i32)); 7112 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7113 Op.getOperand(0)); 7114 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7115 ISD::SETGE); 7116 } 7117 } 7118 7119 return SDValue(); 7120 } 7121 7122 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7123 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7124 7125 ReuseLoadInfo RLI; 7126 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7127 7128 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7129 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7130 } 7131 7132 // We're trying to insert a regular store, S, and then a load, L. If the 7133 // incoming value, O, is a load, we might just be able to have our load use the 7134 // address used by O. However, we don't know if anything else will store to 7135 // that address before we can load from it. To prevent this situation, we need 7136 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7137 // the same chain operand as O, we create a token factor from the chain results 7138 // of O and L, and we replace all uses of O's chain result with that token 7139 // factor (see spliceIntoChain below for this last part). 7140 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7141 ReuseLoadInfo &RLI, 7142 SelectionDAG &DAG, 7143 ISD::LoadExtType ET) const { 7144 SDLoc dl(Op); 7145 if (ET == ISD::NON_EXTLOAD && 7146 (Op.getOpcode() == ISD::FP_TO_UINT || 7147 Op.getOpcode() == ISD::FP_TO_SINT) && 7148 isOperationLegalOrCustom(Op.getOpcode(), 7149 Op.getOperand(0).getValueType())) { 7150 7151 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7152 return true; 7153 } 7154 7155 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7156 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7157 LD->isNonTemporal()) 7158 return false; 7159 if (LD->getMemoryVT() != MemVT) 7160 return false; 7161 7162 RLI.Ptr = LD->getBasePtr(); 7163 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7164 assert(LD->getAddressingMode() == ISD::PRE_INC && 7165 "Non-pre-inc AM on PPC?"); 7166 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7167 LD->getOffset()); 7168 } 7169 7170 RLI.Chain = LD->getChain(); 7171 RLI.MPI = LD->getPointerInfo(); 7172 RLI.IsDereferenceable = LD->isDereferenceable(); 7173 RLI.IsInvariant = LD->isInvariant(); 7174 RLI.Alignment = LD->getAlignment(); 7175 RLI.AAInfo = LD->getAAInfo(); 7176 RLI.Ranges = LD->getRanges(); 7177 7178 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7179 return true; 7180 } 7181 7182 // Given the head of the old chain, ResChain, insert a token factor containing 7183 // it and NewResChain, and make users of ResChain now be users of that token 7184 // factor. 7185 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7186 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7187 SDValue NewResChain, 7188 SelectionDAG &DAG) const { 7189 if (!ResChain) 7190 return; 7191 7192 SDLoc dl(NewResChain); 7193 7194 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7195 NewResChain, DAG.getUNDEF(MVT::Other)); 7196 assert(TF.getNode() != NewResChain.getNode() && 7197 "A new TF really is required here"); 7198 7199 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7200 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7201 } 7202 7203 /// Analyze profitability of direct move 7204 /// prefer float load to int load plus direct move 7205 /// when there is no integer use of int load 7206 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7207 SDNode *Origin = Op.getOperand(0).getNode(); 7208 if (Origin->getOpcode() != ISD::LOAD) 7209 return true; 7210 7211 // If there is no LXSIBZX/LXSIHZX, like Power8, 7212 // prefer direct move if the memory size is 1 or 2 bytes. 7213 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7214 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7215 return true; 7216 7217 for (SDNode::use_iterator UI = Origin->use_begin(), 7218 UE = Origin->use_end(); 7219 UI != UE; ++UI) { 7220 7221 // Only look at the users of the loaded value. 7222 if (UI.getUse().get().getResNo() != 0) 7223 continue; 7224 7225 if (UI->getOpcode() != ISD::SINT_TO_FP && 7226 UI->getOpcode() != ISD::UINT_TO_FP) 7227 return true; 7228 } 7229 7230 return false; 7231 } 7232 7233 /// Custom lowers integer to floating point conversions to use 7234 /// the direct move instructions available in ISA 2.07 to avoid the 7235 /// need for load/store combinations. 7236 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7237 SelectionDAG &DAG, 7238 const SDLoc &dl) const { 7239 assert((Op.getValueType() == MVT::f32 || 7240 Op.getValueType() == MVT::f64) && 7241 "Invalid floating point type as target of conversion"); 7242 assert(Subtarget.hasFPCVT() && 7243 "Int to FP conversions with direct moves require FPCVT"); 7244 SDValue FP; 7245 SDValue Src = Op.getOperand(0); 7246 bool SinglePrec = Op.getValueType() == MVT::f32; 7247 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7248 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7249 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7250 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7251 7252 if (WordInt) { 7253 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7254 dl, MVT::f64, Src); 7255 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7256 } 7257 else { 7258 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7259 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7260 } 7261 7262 return FP; 7263 } 7264 7265 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7266 7267 EVT VecVT = Vec.getValueType(); 7268 assert(VecVT.isVector() && "Expected a vector type."); 7269 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7270 7271 EVT EltVT = VecVT.getVectorElementType(); 7272 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7273 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7274 7275 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7276 SmallVector<SDValue, 16> Ops(NumConcat); 7277 Ops[0] = Vec; 7278 SDValue UndefVec = DAG.getUNDEF(VecVT); 7279 for (unsigned i = 1; i < NumConcat; ++i) 7280 Ops[i] = UndefVec; 7281 7282 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7283 } 7284 7285 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7286 const SDLoc &dl) const { 7287 7288 unsigned Opc = Op.getOpcode(); 7289 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7290 "Unexpected conversion type"); 7291 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7292 "Supports conversions to v2f64/v4f32 only."); 7293 7294 bool SignedConv = Opc == ISD::SINT_TO_FP; 7295 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7296 7297 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7298 EVT WideVT = Wide.getValueType(); 7299 unsigned WideNumElts = WideVT.getVectorNumElements(); 7300 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7301 7302 SmallVector<int, 16> ShuffV; 7303 for (unsigned i = 0; i < WideNumElts; ++i) 7304 ShuffV.push_back(i + WideNumElts); 7305 7306 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7307 int SaveElts = FourEltRes ? 4 : 2; 7308 if (Subtarget.isLittleEndian()) 7309 for (int i = 0; i < SaveElts; i++) 7310 ShuffV[i * Stride] = i; 7311 else 7312 for (int i = 1; i <= SaveElts; i++) 7313 ShuffV[i * Stride - 1] = i - 1; 7314 7315 SDValue ShuffleSrc2 = 7316 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7317 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7318 unsigned ExtendOp = 7319 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7320 7321 SDValue Extend; 7322 if (!Subtarget.hasP9Altivec() && SignedConv) { 7323 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7324 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7325 DAG.getValueType(Op.getOperand(0).getValueType())); 7326 } else 7327 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7328 7329 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7330 } 7331 7332 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7333 SelectionDAG &DAG) const { 7334 SDLoc dl(Op); 7335 7336 EVT InVT = Op.getOperand(0).getValueType(); 7337 EVT OutVT = Op.getValueType(); 7338 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7339 isOperationCustom(Op.getOpcode(), InVT)) 7340 return LowerINT_TO_FPVector(Op, DAG, dl); 7341 7342 // Conversions to f128 are legal. 7343 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7344 return Op; 7345 7346 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7347 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7348 return SDValue(); 7349 7350 SDValue Value = Op.getOperand(0); 7351 // The values are now known to be -1 (false) or 1 (true). To convert this 7352 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7353 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7354 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7355 7356 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7357 7358 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7359 7360 if (Op.getValueType() != MVT::v4f64) 7361 Value = DAG.getNode(ISD::FP_ROUND, dl, 7362 Op.getValueType(), Value, 7363 DAG.getIntPtrConstant(1, dl)); 7364 return Value; 7365 } 7366 7367 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7368 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7369 return SDValue(); 7370 7371 if (Op.getOperand(0).getValueType() == MVT::i1) 7372 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7373 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7374 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7375 7376 // If we have direct moves, we can do all the conversion, skip the store/load 7377 // however, without FPCVT we can't do most conversions. 7378 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7379 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7380 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7381 7382 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7383 "UINT_TO_FP is supported only with FPCVT"); 7384 7385 // If we have FCFIDS, then use it when converting to single-precision. 7386 // Otherwise, convert to double-precision and then round. 7387 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7388 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7389 : PPCISD::FCFIDS) 7390 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7391 : PPCISD::FCFID); 7392 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7393 ? MVT::f32 7394 : MVT::f64; 7395 7396 if (Op.getOperand(0).getValueType() == MVT::i64) { 7397 SDValue SINT = Op.getOperand(0); 7398 // When converting to single-precision, we actually need to convert 7399 // to double-precision first and then round to single-precision. 7400 // To avoid double-rounding effects during that operation, we have 7401 // to prepare the input operand. Bits that might be truncated when 7402 // converting to double-precision are replaced by a bit that won't 7403 // be lost at this stage, but is below the single-precision rounding 7404 // position. 7405 // 7406 // However, if -enable-unsafe-fp-math is in effect, accept double 7407 // rounding to avoid the extra overhead. 7408 if (Op.getValueType() == MVT::f32 && 7409 !Subtarget.hasFPCVT() && 7410 !DAG.getTarget().Options.UnsafeFPMath) { 7411 7412 // Twiddle input to make sure the low 11 bits are zero. (If this 7413 // is the case, we are guaranteed the value will fit into the 53 bit 7414 // mantissa of an IEEE double-precision value without rounding.) 7415 // If any of those low 11 bits were not zero originally, make sure 7416 // bit 12 (value 2048) is set instead, so that the final rounding 7417 // to single-precision gets the correct result. 7418 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7419 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7420 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7421 Round, DAG.getConstant(2047, dl, MVT::i64)); 7422 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7423 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7424 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7425 7426 // However, we cannot use that value unconditionally: if the magnitude 7427 // of the input value is small, the bit-twiddling we did above might 7428 // end up visibly changing the output. Fortunately, in that case, we 7429 // don't need to twiddle bits since the original input will convert 7430 // exactly to double-precision floating-point already. Therefore, 7431 // construct a conditional to use the original value if the top 11 7432 // bits are all sign-bit copies, and use the rounded value computed 7433 // above otherwise. 7434 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7435 SINT, DAG.getConstant(53, dl, MVT::i32)); 7436 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7437 Cond, DAG.getConstant(1, dl, MVT::i64)); 7438 Cond = DAG.getSetCC(dl, MVT::i32, 7439 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7440 7441 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7442 } 7443 7444 ReuseLoadInfo RLI; 7445 SDValue Bits; 7446 7447 MachineFunction &MF = DAG.getMachineFunction(); 7448 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7449 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7450 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7451 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7452 } else if (Subtarget.hasLFIWAX() && 7453 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7454 MachineMemOperand *MMO = 7455 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7456 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7457 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7458 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7459 DAG.getVTList(MVT::f64, MVT::Other), 7460 Ops, MVT::i32, MMO); 7461 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7462 } else if (Subtarget.hasFPCVT() && 7463 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7464 MachineMemOperand *MMO = 7465 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7466 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7467 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7468 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7469 DAG.getVTList(MVT::f64, MVT::Other), 7470 Ops, MVT::i32, MMO); 7471 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7472 } else if (((Subtarget.hasLFIWAX() && 7473 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7474 (Subtarget.hasFPCVT() && 7475 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7476 SINT.getOperand(0).getValueType() == MVT::i32) { 7477 MachineFrameInfo &MFI = MF.getFrameInfo(); 7478 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7479 7480 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7481 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7482 7483 SDValue Store = 7484 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7485 MachinePointerInfo::getFixedStack( 7486 DAG.getMachineFunction(), FrameIdx)); 7487 7488 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7489 "Expected an i32 store"); 7490 7491 RLI.Ptr = FIdx; 7492 RLI.Chain = Store; 7493 RLI.MPI = 7494 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7495 RLI.Alignment = 4; 7496 7497 MachineMemOperand *MMO = 7498 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7499 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7500 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7501 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7502 PPCISD::LFIWZX : PPCISD::LFIWAX, 7503 dl, DAG.getVTList(MVT::f64, MVT::Other), 7504 Ops, MVT::i32, MMO); 7505 } else 7506 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7507 7508 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7509 7510 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7511 FP = DAG.getNode(ISD::FP_ROUND, dl, 7512 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7513 return FP; 7514 } 7515 7516 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7517 "Unhandled INT_TO_FP type in custom expander!"); 7518 // Since we only generate this in 64-bit mode, we can take advantage of 7519 // 64-bit registers. In particular, sign extend the input value into the 7520 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7521 // then lfd it and fcfid it. 7522 MachineFunction &MF = DAG.getMachineFunction(); 7523 MachineFrameInfo &MFI = MF.getFrameInfo(); 7524 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7525 7526 SDValue Ld; 7527 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7528 ReuseLoadInfo RLI; 7529 bool ReusingLoad; 7530 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7531 DAG))) { 7532 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7533 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7534 7535 SDValue Store = 7536 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7537 MachinePointerInfo::getFixedStack( 7538 DAG.getMachineFunction(), FrameIdx)); 7539 7540 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7541 "Expected an i32 store"); 7542 7543 RLI.Ptr = FIdx; 7544 RLI.Chain = Store; 7545 RLI.MPI = 7546 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7547 RLI.Alignment = 4; 7548 } 7549 7550 MachineMemOperand *MMO = 7551 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7552 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7553 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7554 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7555 PPCISD::LFIWZX : PPCISD::LFIWAX, 7556 dl, DAG.getVTList(MVT::f64, MVT::Other), 7557 Ops, MVT::i32, MMO); 7558 if (ReusingLoad) 7559 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7560 } else { 7561 assert(Subtarget.isPPC64() && 7562 "i32->FP without LFIWAX supported only on PPC64"); 7563 7564 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7565 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7566 7567 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7568 Op.getOperand(0)); 7569 7570 // STD the extended value into the stack slot. 7571 SDValue Store = DAG.getStore( 7572 DAG.getEntryNode(), dl, Ext64, FIdx, 7573 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7574 7575 // Load the value as a double. 7576 Ld = DAG.getLoad( 7577 MVT::f64, dl, Store, FIdx, 7578 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7579 } 7580 7581 // FCFID it and return it. 7582 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7583 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7584 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7585 DAG.getIntPtrConstant(0, dl)); 7586 return FP; 7587 } 7588 7589 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7590 SelectionDAG &DAG) const { 7591 SDLoc dl(Op); 7592 /* 7593 The rounding mode is in bits 30:31 of FPSR, and has the following 7594 settings: 7595 00 Round to nearest 7596 01 Round to 0 7597 10 Round to +inf 7598 11 Round to -inf 7599 7600 FLT_ROUNDS, on the other hand, expects the following: 7601 -1 Undefined 7602 0 Round to 0 7603 1 Round to nearest 7604 2 Round to +inf 7605 3 Round to -inf 7606 7607 To perform the conversion, we do: 7608 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7609 */ 7610 7611 MachineFunction &MF = DAG.getMachineFunction(); 7612 EVT VT = Op.getValueType(); 7613 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7614 7615 // Save FP Control Word to register 7616 EVT NodeTys[] = { 7617 MVT::f64, // return register 7618 MVT::Glue // unused in this context 7619 }; 7620 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7621 7622 // Save FP register to stack slot 7623 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7624 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7625 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7626 MachinePointerInfo()); 7627 7628 // Load FP Control Word from low 32 bits of stack slot. 7629 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7630 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7631 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7632 7633 // Transform as necessary 7634 SDValue CWD1 = 7635 DAG.getNode(ISD::AND, dl, MVT::i32, 7636 CWD, DAG.getConstant(3, dl, MVT::i32)); 7637 SDValue CWD2 = 7638 DAG.getNode(ISD::SRL, dl, MVT::i32, 7639 DAG.getNode(ISD::AND, dl, MVT::i32, 7640 DAG.getNode(ISD::XOR, dl, MVT::i32, 7641 CWD, DAG.getConstant(3, dl, MVT::i32)), 7642 DAG.getConstant(3, dl, MVT::i32)), 7643 DAG.getConstant(1, dl, MVT::i32)); 7644 7645 SDValue RetVal = 7646 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7647 7648 return DAG.getNode((VT.getSizeInBits() < 16 ? 7649 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7650 } 7651 7652 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7653 EVT VT = Op.getValueType(); 7654 unsigned BitWidth = VT.getSizeInBits(); 7655 SDLoc dl(Op); 7656 assert(Op.getNumOperands() == 3 && 7657 VT == Op.getOperand(1).getValueType() && 7658 "Unexpected SHL!"); 7659 7660 // Expand into a bunch of logical ops. Note that these ops 7661 // depend on the PPC behavior for oversized shift amounts. 7662 SDValue Lo = Op.getOperand(0); 7663 SDValue Hi = Op.getOperand(1); 7664 SDValue Amt = Op.getOperand(2); 7665 EVT AmtVT = Amt.getValueType(); 7666 7667 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7668 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7669 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7670 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7671 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7672 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7673 DAG.getConstant(-BitWidth, dl, AmtVT)); 7674 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7675 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7676 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7677 SDValue OutOps[] = { OutLo, OutHi }; 7678 return DAG.getMergeValues(OutOps, dl); 7679 } 7680 7681 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7682 EVT VT = Op.getValueType(); 7683 SDLoc dl(Op); 7684 unsigned BitWidth = VT.getSizeInBits(); 7685 assert(Op.getNumOperands() == 3 && 7686 VT == Op.getOperand(1).getValueType() && 7687 "Unexpected SRL!"); 7688 7689 // Expand into a bunch of logical ops. Note that these ops 7690 // depend on the PPC behavior for oversized shift amounts. 7691 SDValue Lo = Op.getOperand(0); 7692 SDValue Hi = Op.getOperand(1); 7693 SDValue Amt = Op.getOperand(2); 7694 EVT AmtVT = Amt.getValueType(); 7695 7696 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7697 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7698 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7699 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7700 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7701 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7702 DAG.getConstant(-BitWidth, dl, AmtVT)); 7703 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7704 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7705 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7706 SDValue OutOps[] = { OutLo, OutHi }; 7707 return DAG.getMergeValues(OutOps, dl); 7708 } 7709 7710 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7711 SDLoc dl(Op); 7712 EVT VT = Op.getValueType(); 7713 unsigned BitWidth = VT.getSizeInBits(); 7714 assert(Op.getNumOperands() == 3 && 7715 VT == Op.getOperand(1).getValueType() && 7716 "Unexpected SRA!"); 7717 7718 // Expand into a bunch of logical ops, followed by a select_cc. 7719 SDValue Lo = Op.getOperand(0); 7720 SDValue Hi = Op.getOperand(1); 7721 SDValue Amt = Op.getOperand(2); 7722 EVT AmtVT = Amt.getValueType(); 7723 7724 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7725 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7726 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7727 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7728 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7729 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7730 DAG.getConstant(-BitWidth, dl, AmtVT)); 7731 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7732 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7733 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7734 Tmp4, Tmp6, ISD::SETLE); 7735 SDValue OutOps[] = { OutLo, OutHi }; 7736 return DAG.getMergeValues(OutOps, dl); 7737 } 7738 7739 //===----------------------------------------------------------------------===// 7740 // Vector related lowering. 7741 // 7742 7743 /// BuildSplatI - Build a canonical splati of Val with an element size of 7744 /// SplatSize. Cast the result to VT. 7745 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7746 SelectionDAG &DAG, const SDLoc &dl) { 7747 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7748 7749 static const MVT VTys[] = { // canonical VT to use for each size. 7750 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7751 }; 7752 7753 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7754 7755 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7756 if (Val == -1) 7757 SplatSize = 1; 7758 7759 EVT CanonicalVT = VTys[SplatSize-1]; 7760 7761 // Build a canonical splat for this value. 7762 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7763 } 7764 7765 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7766 /// specified intrinsic ID. 7767 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7768 const SDLoc &dl, EVT DestVT = MVT::Other) { 7769 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7770 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7771 DAG.getConstant(IID, dl, MVT::i32), Op); 7772 } 7773 7774 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7775 /// specified intrinsic ID. 7776 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7777 SelectionDAG &DAG, const SDLoc &dl, 7778 EVT DestVT = MVT::Other) { 7779 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7780 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7781 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7782 } 7783 7784 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7785 /// specified intrinsic ID. 7786 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7787 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7788 EVT DestVT = MVT::Other) { 7789 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7790 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7791 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7792 } 7793 7794 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7795 /// amount. The result has the specified value type. 7796 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7797 SelectionDAG &DAG, const SDLoc &dl) { 7798 // Force LHS/RHS to be the right type. 7799 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7800 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7801 7802 int Ops[16]; 7803 for (unsigned i = 0; i != 16; ++i) 7804 Ops[i] = i + Amt; 7805 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7806 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7807 } 7808 7809 /// Do we have an efficient pattern in a .td file for this node? 7810 /// 7811 /// \param V - pointer to the BuildVectorSDNode being matched 7812 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7813 /// 7814 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7815 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7816 /// the opposite is true (expansion is beneficial) are: 7817 /// - The node builds a vector out of integers that are not 32 or 64-bits 7818 /// - The node builds a vector out of constants 7819 /// - The node is a "load-and-splat" 7820 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7821 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7822 bool HasDirectMove, 7823 bool HasP8Vector) { 7824 EVT VecVT = V->getValueType(0); 7825 bool RightType = VecVT == MVT::v2f64 || 7826 (HasP8Vector && VecVT == MVT::v4f32) || 7827 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7828 if (!RightType) 7829 return false; 7830 7831 bool IsSplat = true; 7832 bool IsLoad = false; 7833 SDValue Op0 = V->getOperand(0); 7834 7835 // This function is called in a block that confirms the node is not a constant 7836 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7837 // different constants. 7838 if (V->isConstant()) 7839 return false; 7840 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7841 if (V->getOperand(i).isUndef()) 7842 return false; 7843 // We want to expand nodes that represent load-and-splat even if the 7844 // loaded value is a floating point truncation or conversion to int. 7845 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7846 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7847 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7848 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7849 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7850 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7851 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7852 IsLoad = true; 7853 // If the operands are different or the input is not a load and has more 7854 // uses than just this BV node, then it isn't a splat. 7855 if (V->getOperand(i) != Op0 || 7856 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7857 IsSplat = false; 7858 } 7859 return !(IsSplat && IsLoad); 7860 } 7861 7862 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7863 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7864 7865 SDLoc dl(Op); 7866 SDValue Op0 = Op->getOperand(0); 7867 7868 if (!EnableQuadPrecision || 7869 (Op.getValueType() != MVT::f128 ) || 7870 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7871 (Op0.getOperand(0).getValueType() != MVT::i64) || 7872 (Op0.getOperand(1).getValueType() != MVT::i64)) 7873 return SDValue(); 7874 7875 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7876 Op0.getOperand(1)); 7877 } 7878 7879 // If this is a case we can't handle, return null and let the default 7880 // expansion code take care of it. If we CAN select this case, and if it 7881 // selects to a single instruction, return Op. Otherwise, if we can codegen 7882 // this case more efficiently than a constant pool load, lower it to the 7883 // sequence of ops that should be used. 7884 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7885 SelectionDAG &DAG) const { 7886 SDLoc dl(Op); 7887 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7888 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7889 7890 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7891 // We first build an i32 vector, load it into a QPX register, 7892 // then convert it to a floating-point vector and compare it 7893 // to a zero vector to get the boolean result. 7894 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7895 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7896 MachinePointerInfo PtrInfo = 7897 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7898 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7899 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7900 7901 assert(BVN->getNumOperands() == 4 && 7902 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7903 7904 bool IsConst = true; 7905 for (unsigned i = 0; i < 4; ++i) { 7906 if (BVN->getOperand(i).isUndef()) continue; 7907 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7908 IsConst = false; 7909 break; 7910 } 7911 } 7912 7913 if (IsConst) { 7914 Constant *One = 7915 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7916 Constant *NegOne = 7917 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7918 7919 Constant *CV[4]; 7920 for (unsigned i = 0; i < 4; ++i) { 7921 if (BVN->getOperand(i).isUndef()) 7922 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7923 else if (isNullConstant(BVN->getOperand(i))) 7924 CV[i] = NegOne; 7925 else 7926 CV[i] = One; 7927 } 7928 7929 Constant *CP = ConstantVector::get(CV); 7930 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7931 16 /* alignment */); 7932 7933 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7934 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7935 return DAG.getMemIntrinsicNode( 7936 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7937 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7938 } 7939 7940 SmallVector<SDValue, 4> Stores; 7941 for (unsigned i = 0; i < 4; ++i) { 7942 if (BVN->getOperand(i).isUndef()) continue; 7943 7944 unsigned Offset = 4*i; 7945 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7946 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7947 7948 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7949 if (StoreSize > 4) { 7950 Stores.push_back( 7951 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7952 PtrInfo.getWithOffset(Offset), MVT::i32)); 7953 } else { 7954 SDValue StoreValue = BVN->getOperand(i); 7955 if (StoreSize < 4) 7956 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7957 7958 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7959 PtrInfo.getWithOffset(Offset))); 7960 } 7961 } 7962 7963 SDValue StoreChain; 7964 if (!Stores.empty()) 7965 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7966 else 7967 StoreChain = DAG.getEntryNode(); 7968 7969 // Now load from v4i32 into the QPX register; this will extend it to 7970 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7971 // is typed as v4f64 because the QPX register integer states are not 7972 // explicitly represented. 7973 7974 SDValue Ops[] = {StoreChain, 7975 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7976 FIdx}; 7977 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7978 7979 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7980 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7981 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7982 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7983 LoadedVect); 7984 7985 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7986 7987 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7988 } 7989 7990 // All other QPX vectors are handled by generic code. 7991 if (Subtarget.hasQPX()) 7992 return SDValue(); 7993 7994 // Check if this is a splat of a constant value. 7995 APInt APSplatBits, APSplatUndef; 7996 unsigned SplatBitSize; 7997 bool HasAnyUndefs; 7998 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7999 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8000 SplatBitSize > 32) { 8001 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8002 // lowered to VSX instructions under certain conditions. 8003 // Without VSX, there is no pattern more efficient than expanding the node. 8004 if (Subtarget.hasVSX() && 8005 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8006 Subtarget.hasP8Vector())) 8007 return Op; 8008 return SDValue(); 8009 } 8010 8011 unsigned SplatBits = APSplatBits.getZExtValue(); 8012 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8013 unsigned SplatSize = SplatBitSize / 8; 8014 8015 // First, handle single instruction cases. 8016 8017 // All zeros? 8018 if (SplatBits == 0) { 8019 // Canonicalize all zero vectors to be v4i32. 8020 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8021 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8022 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8023 } 8024 return Op; 8025 } 8026 8027 // We have XXSPLTIB for constant splats one byte wide 8028 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8029 // This is a splat of 1-byte elements with some elements potentially undef. 8030 // Rather than trying to match undef in the SDAG patterns, ensure that all 8031 // elements are the same constant. 8032 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8033 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8034 dl, MVT::i32)); 8035 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8036 if (Op.getValueType() != MVT::v16i8) 8037 return DAG.getBitcast(Op.getValueType(), NewBV); 8038 return NewBV; 8039 } 8040 8041 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8042 // detect that constant splats like v8i16: 0xABAB are really just splats 8043 // of a 1-byte constant. In this case, we need to convert the node to a 8044 // splat of v16i8 and a bitcast. 8045 if (Op.getValueType() != MVT::v16i8) 8046 return DAG.getBitcast(Op.getValueType(), 8047 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8048 8049 return Op; 8050 } 8051 8052 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8053 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8054 (32-SplatBitSize)); 8055 if (SextVal >= -16 && SextVal <= 15) 8056 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8057 8058 // Two instruction sequences. 8059 8060 // If this value is in the range [-32,30] and is even, use: 8061 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8062 // If this value is in the range [17,31] and is odd, use: 8063 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8064 // If this value is in the range [-31,-17] and is odd, use: 8065 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8066 // Note the last two are three-instruction sequences. 8067 if (SextVal >= -32 && SextVal <= 31) { 8068 // To avoid having these optimizations undone by constant folding, 8069 // we convert to a pseudo that will be expanded later into one of 8070 // the above forms. 8071 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8072 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8073 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8074 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8075 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8076 if (VT == Op.getValueType()) 8077 return RetVal; 8078 else 8079 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8080 } 8081 8082 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8083 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8084 // for fneg/fabs. 8085 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8086 // Make -1 and vspltisw -1: 8087 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8088 8089 // Make the VSLW intrinsic, computing 0x8000_0000. 8090 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8091 OnesV, DAG, dl); 8092 8093 // xor by OnesV to invert it. 8094 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8095 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8096 } 8097 8098 // Check to see if this is a wide variety of vsplti*, binop self cases. 8099 static const signed char SplatCsts[] = { 8100 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8101 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8102 }; 8103 8104 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8105 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8106 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8107 int i = SplatCsts[idx]; 8108 8109 // Figure out what shift amount will be used by altivec if shifted by i in 8110 // this splat size. 8111 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8112 8113 // vsplti + shl self. 8114 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8115 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8116 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8117 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8118 Intrinsic::ppc_altivec_vslw 8119 }; 8120 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8121 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8122 } 8123 8124 // vsplti + srl self. 8125 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8126 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8127 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8128 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8129 Intrinsic::ppc_altivec_vsrw 8130 }; 8131 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8132 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8133 } 8134 8135 // vsplti + sra self. 8136 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8137 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8138 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8139 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8140 Intrinsic::ppc_altivec_vsraw 8141 }; 8142 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8143 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8144 } 8145 8146 // vsplti + rol self. 8147 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8148 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8149 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8150 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8151 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8152 Intrinsic::ppc_altivec_vrlw 8153 }; 8154 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8155 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8156 } 8157 8158 // t = vsplti c, result = vsldoi t, t, 1 8159 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8160 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8161 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8162 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8163 } 8164 // t = vsplti c, result = vsldoi t, t, 2 8165 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8166 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8167 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8168 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8169 } 8170 // t = vsplti c, result = vsldoi t, t, 3 8171 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8172 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8173 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8174 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8175 } 8176 } 8177 8178 return SDValue(); 8179 } 8180 8181 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8182 /// the specified operations to build the shuffle. 8183 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8184 SDValue RHS, SelectionDAG &DAG, 8185 const SDLoc &dl) { 8186 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8187 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8188 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8189 8190 enum { 8191 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8192 OP_VMRGHW, 8193 OP_VMRGLW, 8194 OP_VSPLTISW0, 8195 OP_VSPLTISW1, 8196 OP_VSPLTISW2, 8197 OP_VSPLTISW3, 8198 OP_VSLDOI4, 8199 OP_VSLDOI8, 8200 OP_VSLDOI12 8201 }; 8202 8203 if (OpNum == OP_COPY) { 8204 if (LHSID == (1*9+2)*9+3) return LHS; 8205 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8206 return RHS; 8207 } 8208 8209 SDValue OpLHS, OpRHS; 8210 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8211 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8212 8213 int ShufIdxs[16]; 8214 switch (OpNum) { 8215 default: llvm_unreachable("Unknown i32 permute!"); 8216 case OP_VMRGHW: 8217 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8218 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8219 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8220 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8221 break; 8222 case OP_VMRGLW: 8223 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8224 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8225 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8226 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8227 break; 8228 case OP_VSPLTISW0: 8229 for (unsigned i = 0; i != 16; ++i) 8230 ShufIdxs[i] = (i&3)+0; 8231 break; 8232 case OP_VSPLTISW1: 8233 for (unsigned i = 0; i != 16; ++i) 8234 ShufIdxs[i] = (i&3)+4; 8235 break; 8236 case OP_VSPLTISW2: 8237 for (unsigned i = 0; i != 16; ++i) 8238 ShufIdxs[i] = (i&3)+8; 8239 break; 8240 case OP_VSPLTISW3: 8241 for (unsigned i = 0; i != 16; ++i) 8242 ShufIdxs[i] = (i&3)+12; 8243 break; 8244 case OP_VSLDOI4: 8245 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8246 case OP_VSLDOI8: 8247 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8248 case OP_VSLDOI12: 8249 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8250 } 8251 EVT VT = OpLHS.getValueType(); 8252 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8253 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8254 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8255 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8256 } 8257 8258 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8259 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8260 /// SDValue. 8261 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8262 SelectionDAG &DAG) const { 8263 const unsigned BytesInVector = 16; 8264 bool IsLE = Subtarget.isLittleEndian(); 8265 SDLoc dl(N); 8266 SDValue V1 = N->getOperand(0); 8267 SDValue V2 = N->getOperand(1); 8268 unsigned ShiftElts = 0, InsertAtByte = 0; 8269 bool Swap = false; 8270 8271 // Shifts required to get the byte we want at element 7. 8272 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8273 0, 15, 14, 13, 12, 11, 10, 9}; 8274 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8275 1, 2, 3, 4, 5, 6, 7, 8}; 8276 8277 ArrayRef<int> Mask = N->getMask(); 8278 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8279 8280 // For each mask element, find out if we're just inserting something 8281 // from V2 into V1 or vice versa. 8282 // Possible permutations inserting an element from V2 into V1: 8283 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8284 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8285 // ... 8286 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8287 // Inserting from V1 into V2 will be similar, except mask range will be 8288 // [16,31]. 8289 8290 bool FoundCandidate = false; 8291 // If both vector operands for the shuffle are the same vector, the mask 8292 // will contain only elements from the first one and the second one will be 8293 // undef. 8294 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8295 // Go through the mask of half-words to find an element that's being moved 8296 // from one vector to the other. 8297 for (unsigned i = 0; i < BytesInVector; ++i) { 8298 unsigned CurrentElement = Mask[i]; 8299 // If 2nd operand is undefined, we should only look for element 7 in the 8300 // Mask. 8301 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8302 continue; 8303 8304 bool OtherElementsInOrder = true; 8305 // Examine the other elements in the Mask to see if they're in original 8306 // order. 8307 for (unsigned j = 0; j < BytesInVector; ++j) { 8308 if (j == i) 8309 continue; 8310 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8311 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8312 // in which we always assume we're always picking from the 1st operand. 8313 int MaskOffset = 8314 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8315 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8316 OtherElementsInOrder = false; 8317 break; 8318 } 8319 } 8320 // If other elements are in original order, we record the number of shifts 8321 // we need to get the element we want into element 7. Also record which byte 8322 // in the vector we should insert into. 8323 if (OtherElementsInOrder) { 8324 // If 2nd operand is undefined, we assume no shifts and no swapping. 8325 if (V2.isUndef()) { 8326 ShiftElts = 0; 8327 Swap = false; 8328 } else { 8329 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8330 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8331 : BigEndianShifts[CurrentElement & 0xF]; 8332 Swap = CurrentElement < BytesInVector; 8333 } 8334 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8335 FoundCandidate = true; 8336 break; 8337 } 8338 } 8339 8340 if (!FoundCandidate) 8341 return SDValue(); 8342 8343 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8344 // optionally with VECSHL if shift is required. 8345 if (Swap) 8346 std::swap(V1, V2); 8347 if (V2.isUndef()) 8348 V2 = V1; 8349 if (ShiftElts) { 8350 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8351 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8352 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8353 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8354 } 8355 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8356 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8357 } 8358 8359 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8360 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8361 /// SDValue. 8362 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8363 SelectionDAG &DAG) const { 8364 const unsigned NumHalfWords = 8; 8365 const unsigned BytesInVector = NumHalfWords * 2; 8366 // Check that the shuffle is on half-words. 8367 if (!isNByteElemShuffleMask(N, 2, 1)) 8368 return SDValue(); 8369 8370 bool IsLE = Subtarget.isLittleEndian(); 8371 SDLoc dl(N); 8372 SDValue V1 = N->getOperand(0); 8373 SDValue V2 = N->getOperand(1); 8374 unsigned ShiftElts = 0, InsertAtByte = 0; 8375 bool Swap = false; 8376 8377 // Shifts required to get the half-word we want at element 3. 8378 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8379 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8380 8381 uint32_t Mask = 0; 8382 uint32_t OriginalOrderLow = 0x1234567; 8383 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8384 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8385 // 32-bit space, only need 4-bit nibbles per element. 8386 for (unsigned i = 0; i < NumHalfWords; ++i) { 8387 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8388 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8389 } 8390 8391 // For each mask element, find out if we're just inserting something 8392 // from V2 into V1 or vice versa. Possible permutations inserting an element 8393 // from V2 into V1: 8394 // X, 1, 2, 3, 4, 5, 6, 7 8395 // 0, X, 2, 3, 4, 5, 6, 7 8396 // 0, 1, X, 3, 4, 5, 6, 7 8397 // 0, 1, 2, X, 4, 5, 6, 7 8398 // 0, 1, 2, 3, X, 5, 6, 7 8399 // 0, 1, 2, 3, 4, X, 6, 7 8400 // 0, 1, 2, 3, 4, 5, X, 7 8401 // 0, 1, 2, 3, 4, 5, 6, X 8402 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8403 8404 bool FoundCandidate = false; 8405 // Go through the mask of half-words to find an element that's being moved 8406 // from one vector to the other. 8407 for (unsigned i = 0; i < NumHalfWords; ++i) { 8408 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8409 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8410 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8411 uint32_t TargetOrder = 0x0; 8412 8413 // If both vector operands for the shuffle are the same vector, the mask 8414 // will contain only elements from the first one and the second one will be 8415 // undef. 8416 if (V2.isUndef()) { 8417 ShiftElts = 0; 8418 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8419 TargetOrder = OriginalOrderLow; 8420 Swap = false; 8421 // Skip if not the correct element or mask of other elements don't equal 8422 // to our expected order. 8423 if (MaskOneElt == VINSERTHSrcElem && 8424 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8425 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8426 FoundCandidate = true; 8427 break; 8428 } 8429 } else { // If both operands are defined. 8430 // Target order is [8,15] if the current mask is between [0,7]. 8431 TargetOrder = 8432 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8433 // Skip if mask of other elements don't equal our expected order. 8434 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8435 // We only need the last 3 bits for the number of shifts. 8436 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8437 : BigEndianShifts[MaskOneElt & 0x7]; 8438 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8439 Swap = MaskOneElt < NumHalfWords; 8440 FoundCandidate = true; 8441 break; 8442 } 8443 } 8444 } 8445 8446 if (!FoundCandidate) 8447 return SDValue(); 8448 8449 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8450 // optionally with VECSHL if shift is required. 8451 if (Swap) 8452 std::swap(V1, V2); 8453 if (V2.isUndef()) 8454 V2 = V1; 8455 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8456 if (ShiftElts) { 8457 // Double ShiftElts because we're left shifting on v16i8 type. 8458 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8459 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8460 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8461 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8462 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8463 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8464 } 8465 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8466 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8467 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8468 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8469 } 8470 8471 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8472 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8473 /// return the code it can be lowered into. Worst case, it can always be 8474 /// lowered into a vperm. 8475 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8476 SelectionDAG &DAG) const { 8477 SDLoc dl(Op); 8478 SDValue V1 = Op.getOperand(0); 8479 SDValue V2 = Op.getOperand(1); 8480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8481 EVT VT = Op.getValueType(); 8482 bool isLittleEndian = Subtarget.isLittleEndian(); 8483 8484 unsigned ShiftElts, InsertAtByte; 8485 bool Swap = false; 8486 if (Subtarget.hasP9Vector() && 8487 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8488 isLittleEndian)) { 8489 if (Swap) 8490 std::swap(V1, V2); 8491 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8492 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8493 if (ShiftElts) { 8494 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8495 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8496 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8497 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8498 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8499 } 8500 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8501 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8502 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8503 } 8504 8505 if (Subtarget.hasP9Altivec()) { 8506 SDValue NewISDNode; 8507 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8508 return NewISDNode; 8509 8510 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8511 return NewISDNode; 8512 } 8513 8514 if (Subtarget.hasVSX() && 8515 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8516 if (Swap) 8517 std::swap(V1, V2); 8518 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8519 SDValue Conv2 = 8520 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8521 8522 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8523 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8524 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8525 } 8526 8527 if (Subtarget.hasVSX() && 8528 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8529 if (Swap) 8530 std::swap(V1, V2); 8531 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8532 SDValue Conv2 = 8533 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8534 8535 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8536 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8537 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8538 } 8539 8540 if (Subtarget.hasP9Vector()) { 8541 if (PPC::isXXBRHShuffleMask(SVOp)) { 8542 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8543 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8544 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8545 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8546 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8547 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8548 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8549 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8550 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8551 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8552 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8553 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8554 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8555 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8556 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8557 } 8558 } 8559 8560 if (Subtarget.hasVSX()) { 8561 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8562 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8563 8564 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8565 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8566 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8567 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8568 } 8569 8570 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8571 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8572 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8573 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8574 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8575 } 8576 } 8577 8578 if (Subtarget.hasQPX()) { 8579 if (VT.getVectorNumElements() != 4) 8580 return SDValue(); 8581 8582 if (V2.isUndef()) V2 = V1; 8583 8584 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8585 if (AlignIdx != -1) { 8586 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8587 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8588 } else if (SVOp->isSplat()) { 8589 int SplatIdx = SVOp->getSplatIndex(); 8590 if (SplatIdx >= 4) { 8591 std::swap(V1, V2); 8592 SplatIdx -= 4; 8593 } 8594 8595 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8596 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8597 } 8598 8599 // Lower this into a qvgpci/qvfperm pair. 8600 8601 // Compute the qvgpci literal 8602 unsigned idx = 0; 8603 for (unsigned i = 0; i < 4; ++i) { 8604 int m = SVOp->getMaskElt(i); 8605 unsigned mm = m >= 0 ? (unsigned) m : i; 8606 idx |= mm << (3-i)*3; 8607 } 8608 8609 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8610 DAG.getConstant(idx, dl, MVT::i32)); 8611 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8612 } 8613 8614 // Cases that are handled by instructions that take permute immediates 8615 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8616 // selected by the instruction selector. 8617 if (V2.isUndef()) { 8618 if (PPC::isSplatShuffleMask(SVOp, 1) || 8619 PPC::isSplatShuffleMask(SVOp, 2) || 8620 PPC::isSplatShuffleMask(SVOp, 4) || 8621 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8622 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8623 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8624 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8625 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8626 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8627 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8628 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8629 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8630 (Subtarget.hasP8Altivec() && ( 8631 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8632 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8633 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8634 return Op; 8635 } 8636 } 8637 8638 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8639 // and produce a fixed permutation. If any of these match, do not lower to 8640 // VPERM. 8641 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8642 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8643 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8644 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8645 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8646 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8647 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8648 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8649 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8650 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8651 (Subtarget.hasP8Altivec() && ( 8652 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8653 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8654 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8655 return Op; 8656 8657 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8658 // perfect shuffle table to emit an optimal matching sequence. 8659 ArrayRef<int> PermMask = SVOp->getMask(); 8660 8661 unsigned PFIndexes[4]; 8662 bool isFourElementShuffle = true; 8663 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8664 unsigned EltNo = 8; // Start out undef. 8665 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8666 if (PermMask[i*4+j] < 0) 8667 continue; // Undef, ignore it. 8668 8669 unsigned ByteSource = PermMask[i*4+j]; 8670 if ((ByteSource & 3) != j) { 8671 isFourElementShuffle = false; 8672 break; 8673 } 8674 8675 if (EltNo == 8) { 8676 EltNo = ByteSource/4; 8677 } else if (EltNo != ByteSource/4) { 8678 isFourElementShuffle = false; 8679 break; 8680 } 8681 } 8682 PFIndexes[i] = EltNo; 8683 } 8684 8685 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8686 // perfect shuffle vector to determine if it is cost effective to do this as 8687 // discrete instructions, or whether we should use a vperm. 8688 // For now, we skip this for little endian until such time as we have a 8689 // little-endian perfect shuffle table. 8690 if (isFourElementShuffle && !isLittleEndian) { 8691 // Compute the index in the perfect shuffle table. 8692 unsigned PFTableIndex = 8693 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8694 8695 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8696 unsigned Cost = (PFEntry >> 30); 8697 8698 // Determining when to avoid vperm is tricky. Many things affect the cost 8699 // of vperm, particularly how many times the perm mask needs to be computed. 8700 // For example, if the perm mask can be hoisted out of a loop or is already 8701 // used (perhaps because there are multiple permutes with the same shuffle 8702 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8703 // the loop requires an extra register. 8704 // 8705 // As a compromise, we only emit discrete instructions if the shuffle can be 8706 // generated in 3 or fewer operations. When we have loop information 8707 // available, if this block is within a loop, we should avoid using vperm 8708 // for 3-operation perms and use a constant pool load instead. 8709 if (Cost < 3) 8710 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8711 } 8712 8713 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8714 // vector that will get spilled to the constant pool. 8715 if (V2.isUndef()) V2 = V1; 8716 8717 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8718 // that it is in input element units, not in bytes. Convert now. 8719 8720 // For little endian, the order of the input vectors is reversed, and 8721 // the permutation mask is complemented with respect to 31. This is 8722 // necessary to produce proper semantics with the big-endian-biased vperm 8723 // instruction. 8724 EVT EltVT = V1.getValueType().getVectorElementType(); 8725 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8726 8727 SmallVector<SDValue, 16> ResultMask; 8728 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8729 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8730 8731 for (unsigned j = 0; j != BytesPerElement; ++j) 8732 if (isLittleEndian) 8733 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8734 dl, MVT::i32)); 8735 else 8736 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8737 MVT::i32)); 8738 } 8739 8740 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8741 if (isLittleEndian) 8742 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8743 V2, V1, VPermMask); 8744 else 8745 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8746 V1, V2, VPermMask); 8747 } 8748 8749 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8750 /// vector comparison. If it is, return true and fill in Opc/isDot with 8751 /// information about the intrinsic. 8752 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8753 bool &isDot, const PPCSubtarget &Subtarget) { 8754 unsigned IntrinsicID = 8755 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8756 CompareOpc = -1; 8757 isDot = false; 8758 switch (IntrinsicID) { 8759 default: 8760 return false; 8761 // Comparison predicates. 8762 case Intrinsic::ppc_altivec_vcmpbfp_p: 8763 CompareOpc = 966; 8764 isDot = true; 8765 break; 8766 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8767 CompareOpc = 198; 8768 isDot = true; 8769 break; 8770 case Intrinsic::ppc_altivec_vcmpequb_p: 8771 CompareOpc = 6; 8772 isDot = true; 8773 break; 8774 case Intrinsic::ppc_altivec_vcmpequh_p: 8775 CompareOpc = 70; 8776 isDot = true; 8777 break; 8778 case Intrinsic::ppc_altivec_vcmpequw_p: 8779 CompareOpc = 134; 8780 isDot = true; 8781 break; 8782 case Intrinsic::ppc_altivec_vcmpequd_p: 8783 if (Subtarget.hasP8Altivec()) { 8784 CompareOpc = 199; 8785 isDot = true; 8786 } else 8787 return false; 8788 break; 8789 case Intrinsic::ppc_altivec_vcmpneb_p: 8790 case Intrinsic::ppc_altivec_vcmpneh_p: 8791 case Intrinsic::ppc_altivec_vcmpnew_p: 8792 case Intrinsic::ppc_altivec_vcmpnezb_p: 8793 case Intrinsic::ppc_altivec_vcmpnezh_p: 8794 case Intrinsic::ppc_altivec_vcmpnezw_p: 8795 if (Subtarget.hasP9Altivec()) { 8796 switch (IntrinsicID) { 8797 default: 8798 llvm_unreachable("Unknown comparison intrinsic."); 8799 case Intrinsic::ppc_altivec_vcmpneb_p: 8800 CompareOpc = 7; 8801 break; 8802 case Intrinsic::ppc_altivec_vcmpneh_p: 8803 CompareOpc = 71; 8804 break; 8805 case Intrinsic::ppc_altivec_vcmpnew_p: 8806 CompareOpc = 135; 8807 break; 8808 case Intrinsic::ppc_altivec_vcmpnezb_p: 8809 CompareOpc = 263; 8810 break; 8811 case Intrinsic::ppc_altivec_vcmpnezh_p: 8812 CompareOpc = 327; 8813 break; 8814 case Intrinsic::ppc_altivec_vcmpnezw_p: 8815 CompareOpc = 391; 8816 break; 8817 } 8818 isDot = true; 8819 } else 8820 return false; 8821 break; 8822 case Intrinsic::ppc_altivec_vcmpgefp_p: 8823 CompareOpc = 454; 8824 isDot = true; 8825 break; 8826 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8827 CompareOpc = 710; 8828 isDot = true; 8829 break; 8830 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8831 CompareOpc = 774; 8832 isDot = true; 8833 break; 8834 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8835 CompareOpc = 838; 8836 isDot = true; 8837 break; 8838 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8839 CompareOpc = 902; 8840 isDot = true; 8841 break; 8842 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8843 if (Subtarget.hasP8Altivec()) { 8844 CompareOpc = 967; 8845 isDot = true; 8846 } else 8847 return false; 8848 break; 8849 case Intrinsic::ppc_altivec_vcmpgtub_p: 8850 CompareOpc = 518; 8851 isDot = true; 8852 break; 8853 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8854 CompareOpc = 582; 8855 isDot = true; 8856 break; 8857 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8858 CompareOpc = 646; 8859 isDot = true; 8860 break; 8861 case Intrinsic::ppc_altivec_vcmpgtud_p: 8862 if (Subtarget.hasP8Altivec()) { 8863 CompareOpc = 711; 8864 isDot = true; 8865 } else 8866 return false; 8867 break; 8868 8869 // VSX predicate comparisons use the same infrastructure 8870 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8871 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8872 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8873 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8874 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8875 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8876 if (Subtarget.hasVSX()) { 8877 switch (IntrinsicID) { 8878 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8879 CompareOpc = 99; 8880 break; 8881 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8882 CompareOpc = 115; 8883 break; 8884 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8885 CompareOpc = 107; 8886 break; 8887 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8888 CompareOpc = 67; 8889 break; 8890 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8891 CompareOpc = 83; 8892 break; 8893 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8894 CompareOpc = 75; 8895 break; 8896 } 8897 isDot = true; 8898 } else 8899 return false; 8900 break; 8901 8902 // Normal Comparisons. 8903 case Intrinsic::ppc_altivec_vcmpbfp: 8904 CompareOpc = 966; 8905 break; 8906 case Intrinsic::ppc_altivec_vcmpeqfp: 8907 CompareOpc = 198; 8908 break; 8909 case Intrinsic::ppc_altivec_vcmpequb: 8910 CompareOpc = 6; 8911 break; 8912 case Intrinsic::ppc_altivec_vcmpequh: 8913 CompareOpc = 70; 8914 break; 8915 case Intrinsic::ppc_altivec_vcmpequw: 8916 CompareOpc = 134; 8917 break; 8918 case Intrinsic::ppc_altivec_vcmpequd: 8919 if (Subtarget.hasP8Altivec()) 8920 CompareOpc = 199; 8921 else 8922 return false; 8923 break; 8924 case Intrinsic::ppc_altivec_vcmpneb: 8925 case Intrinsic::ppc_altivec_vcmpneh: 8926 case Intrinsic::ppc_altivec_vcmpnew: 8927 case Intrinsic::ppc_altivec_vcmpnezb: 8928 case Intrinsic::ppc_altivec_vcmpnezh: 8929 case Intrinsic::ppc_altivec_vcmpnezw: 8930 if (Subtarget.hasP9Altivec()) 8931 switch (IntrinsicID) { 8932 default: 8933 llvm_unreachable("Unknown comparison intrinsic."); 8934 case Intrinsic::ppc_altivec_vcmpneb: 8935 CompareOpc = 7; 8936 break; 8937 case Intrinsic::ppc_altivec_vcmpneh: 8938 CompareOpc = 71; 8939 break; 8940 case Intrinsic::ppc_altivec_vcmpnew: 8941 CompareOpc = 135; 8942 break; 8943 case Intrinsic::ppc_altivec_vcmpnezb: 8944 CompareOpc = 263; 8945 break; 8946 case Intrinsic::ppc_altivec_vcmpnezh: 8947 CompareOpc = 327; 8948 break; 8949 case Intrinsic::ppc_altivec_vcmpnezw: 8950 CompareOpc = 391; 8951 break; 8952 } 8953 else 8954 return false; 8955 break; 8956 case Intrinsic::ppc_altivec_vcmpgefp: 8957 CompareOpc = 454; 8958 break; 8959 case Intrinsic::ppc_altivec_vcmpgtfp: 8960 CompareOpc = 710; 8961 break; 8962 case Intrinsic::ppc_altivec_vcmpgtsb: 8963 CompareOpc = 774; 8964 break; 8965 case Intrinsic::ppc_altivec_vcmpgtsh: 8966 CompareOpc = 838; 8967 break; 8968 case Intrinsic::ppc_altivec_vcmpgtsw: 8969 CompareOpc = 902; 8970 break; 8971 case Intrinsic::ppc_altivec_vcmpgtsd: 8972 if (Subtarget.hasP8Altivec()) 8973 CompareOpc = 967; 8974 else 8975 return false; 8976 break; 8977 case Intrinsic::ppc_altivec_vcmpgtub: 8978 CompareOpc = 518; 8979 break; 8980 case Intrinsic::ppc_altivec_vcmpgtuh: 8981 CompareOpc = 582; 8982 break; 8983 case Intrinsic::ppc_altivec_vcmpgtuw: 8984 CompareOpc = 646; 8985 break; 8986 case Intrinsic::ppc_altivec_vcmpgtud: 8987 if (Subtarget.hasP8Altivec()) 8988 CompareOpc = 711; 8989 else 8990 return false; 8991 break; 8992 } 8993 return true; 8994 } 8995 8996 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8997 /// lower, do it, otherwise return null. 8998 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8999 SelectionDAG &DAG) const { 9000 unsigned IntrinsicID = 9001 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9002 9003 SDLoc dl(Op); 9004 9005 if (IntrinsicID == Intrinsic::thread_pointer) { 9006 // Reads the thread pointer register, used for __builtin_thread_pointer. 9007 if (Subtarget.isPPC64()) 9008 return DAG.getRegister(PPC::X13, MVT::i64); 9009 return DAG.getRegister(PPC::R2, MVT::i32); 9010 } 9011 9012 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9013 // opcode number of the comparison. 9014 int CompareOpc; 9015 bool isDot; 9016 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9017 return SDValue(); // Don't custom lower most intrinsics. 9018 9019 // If this is a non-dot comparison, make the VCMP node and we are done. 9020 if (!isDot) { 9021 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9022 Op.getOperand(1), Op.getOperand(2), 9023 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9024 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9025 } 9026 9027 // Create the PPCISD altivec 'dot' comparison node. 9028 SDValue Ops[] = { 9029 Op.getOperand(2), // LHS 9030 Op.getOperand(3), // RHS 9031 DAG.getConstant(CompareOpc, dl, MVT::i32) 9032 }; 9033 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9034 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9035 9036 // Now that we have the comparison, emit a copy from the CR to a GPR. 9037 // This is flagged to the above dot comparison. 9038 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9039 DAG.getRegister(PPC::CR6, MVT::i32), 9040 CompNode.getValue(1)); 9041 9042 // Unpack the result based on how the target uses it. 9043 unsigned BitNo; // Bit # of CR6. 9044 bool InvertBit; // Invert result? 9045 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9046 default: // Can't happen, don't crash on invalid number though. 9047 case 0: // Return the value of the EQ bit of CR6. 9048 BitNo = 0; InvertBit = false; 9049 break; 9050 case 1: // Return the inverted value of the EQ bit of CR6. 9051 BitNo = 0; InvertBit = true; 9052 break; 9053 case 2: // Return the value of the LT bit of CR6. 9054 BitNo = 2; InvertBit = false; 9055 break; 9056 case 3: // Return the inverted value of the LT bit of CR6. 9057 BitNo = 2; InvertBit = true; 9058 break; 9059 } 9060 9061 // Shift the bit into the low position. 9062 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9063 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9064 // Isolate the bit. 9065 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9066 DAG.getConstant(1, dl, MVT::i32)); 9067 9068 // If we are supposed to, toggle the bit. 9069 if (InvertBit) 9070 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9071 DAG.getConstant(1, dl, MVT::i32)); 9072 return Flags; 9073 } 9074 9075 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9076 SelectionDAG &DAG) const { 9077 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9078 // the beginning of the argument list. 9079 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9080 SDLoc DL(Op); 9081 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9082 case Intrinsic::ppc_cfence: { 9083 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9084 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9085 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9086 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9087 Op.getOperand(ArgStart + 1)), 9088 Op.getOperand(0)), 9089 0); 9090 } 9091 default: 9092 break; 9093 } 9094 return SDValue(); 9095 } 9096 9097 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9098 // Check for a DIV with the same operands as this REM. 9099 for (auto UI : Op.getOperand(1)->uses()) { 9100 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9101 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9102 if (UI->getOperand(0) == Op.getOperand(0) && 9103 UI->getOperand(1) == Op.getOperand(1)) 9104 return SDValue(); 9105 } 9106 return Op; 9107 } 9108 9109 // Lower scalar BSWAP64 to xxbrd. 9110 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9111 SDLoc dl(Op); 9112 // MTVSRDD 9113 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9114 Op.getOperand(0)); 9115 // XXBRD 9116 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9117 // MFVSRD 9118 int VectorIndex = 0; 9119 if (Subtarget.isLittleEndian()) 9120 VectorIndex = 1; 9121 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9122 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9123 return Op; 9124 } 9125 9126 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9127 // compared to a value that is atomically loaded (atomic loads zero-extend). 9128 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9129 SelectionDAG &DAG) const { 9130 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9131 "Expecting an atomic compare-and-swap here."); 9132 SDLoc dl(Op); 9133 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9134 EVT MemVT = AtomicNode->getMemoryVT(); 9135 if (MemVT.getSizeInBits() >= 32) 9136 return Op; 9137 9138 SDValue CmpOp = Op.getOperand(2); 9139 // If this is already correctly zero-extended, leave it alone. 9140 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9141 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9142 return Op; 9143 9144 // Clear the high bits of the compare operand. 9145 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9146 SDValue NewCmpOp = 9147 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9148 DAG.getConstant(MaskVal, dl, MVT::i32)); 9149 9150 // Replace the existing compare operand with the properly zero-extended one. 9151 SmallVector<SDValue, 4> Ops; 9152 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9153 Ops.push_back(AtomicNode->getOperand(i)); 9154 Ops[2] = NewCmpOp; 9155 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9156 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9157 auto NodeTy = 9158 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9159 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9160 } 9161 9162 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9163 SelectionDAG &DAG) const { 9164 SDLoc dl(Op); 9165 // Create a stack slot that is 16-byte aligned. 9166 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9167 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9168 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9169 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9170 9171 // Store the input value into Value#0 of the stack slot. 9172 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9173 MachinePointerInfo()); 9174 // Load it out. 9175 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9176 } 9177 9178 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9179 SelectionDAG &DAG) const { 9180 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9181 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9182 9183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9184 // We have legal lowering for constant indices but not for variable ones. 9185 if (!C) 9186 return SDValue(); 9187 9188 EVT VT = Op.getValueType(); 9189 SDLoc dl(Op); 9190 SDValue V1 = Op.getOperand(0); 9191 SDValue V2 = Op.getOperand(1); 9192 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9193 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9194 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9195 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9196 unsigned InsertAtElement = C->getZExtValue(); 9197 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9198 if (Subtarget.isLittleEndian()) { 9199 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9200 } 9201 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9202 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9203 } 9204 return Op; 9205 } 9206 9207 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9208 SelectionDAG &DAG) const { 9209 SDLoc dl(Op); 9210 SDNode *N = Op.getNode(); 9211 9212 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9213 "Unknown extract_vector_elt type"); 9214 9215 SDValue Value = N->getOperand(0); 9216 9217 // The first part of this is like the store lowering except that we don't 9218 // need to track the chain. 9219 9220 // The values are now known to be -1 (false) or 1 (true). To convert this 9221 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9222 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9223 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9224 9225 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9226 // understand how to form the extending load. 9227 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9228 9229 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9230 9231 // Now convert to an integer and store. 9232 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9233 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9234 Value); 9235 9236 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9237 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9238 MachinePointerInfo PtrInfo = 9239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9240 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9241 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9242 9243 SDValue StoreChain = DAG.getEntryNode(); 9244 SDValue Ops[] = {StoreChain, 9245 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9246 Value, FIdx}; 9247 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9248 9249 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9250 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9251 9252 // Extract the value requested. 9253 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9254 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9255 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9256 9257 SDValue IntVal = 9258 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9259 9260 if (!Subtarget.useCRBits()) 9261 return IntVal; 9262 9263 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9264 } 9265 9266 /// Lowering for QPX v4i1 loads 9267 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9268 SelectionDAG &DAG) const { 9269 SDLoc dl(Op); 9270 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9271 SDValue LoadChain = LN->getChain(); 9272 SDValue BasePtr = LN->getBasePtr(); 9273 9274 if (Op.getValueType() == MVT::v4f64 || 9275 Op.getValueType() == MVT::v4f32) { 9276 EVT MemVT = LN->getMemoryVT(); 9277 unsigned Alignment = LN->getAlignment(); 9278 9279 // If this load is properly aligned, then it is legal. 9280 if (Alignment >= MemVT.getStoreSize()) 9281 return Op; 9282 9283 EVT ScalarVT = Op.getValueType().getScalarType(), 9284 ScalarMemVT = MemVT.getScalarType(); 9285 unsigned Stride = ScalarMemVT.getStoreSize(); 9286 9287 SDValue Vals[4], LoadChains[4]; 9288 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9289 SDValue Load; 9290 if (ScalarVT != ScalarMemVT) 9291 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9292 BasePtr, 9293 LN->getPointerInfo().getWithOffset(Idx * Stride), 9294 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9295 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9296 else 9297 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9298 LN->getPointerInfo().getWithOffset(Idx * Stride), 9299 MinAlign(Alignment, Idx * Stride), 9300 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9301 9302 if (Idx == 0 && LN->isIndexed()) { 9303 assert(LN->getAddressingMode() == ISD::PRE_INC && 9304 "Unknown addressing mode on vector load"); 9305 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9306 LN->getAddressingMode()); 9307 } 9308 9309 Vals[Idx] = Load; 9310 LoadChains[Idx] = Load.getValue(1); 9311 9312 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9313 DAG.getConstant(Stride, dl, 9314 BasePtr.getValueType())); 9315 } 9316 9317 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9318 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9319 9320 if (LN->isIndexed()) { 9321 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9322 return DAG.getMergeValues(RetOps, dl); 9323 } 9324 9325 SDValue RetOps[] = { Value, TF }; 9326 return DAG.getMergeValues(RetOps, dl); 9327 } 9328 9329 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9330 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9331 9332 // To lower v4i1 from a byte array, we load the byte elements of the 9333 // vector and then reuse the BUILD_VECTOR logic. 9334 9335 SDValue VectElmts[4], VectElmtChains[4]; 9336 for (unsigned i = 0; i < 4; ++i) { 9337 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9338 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9339 9340 VectElmts[i] = DAG.getExtLoad( 9341 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9342 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9343 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9344 VectElmtChains[i] = VectElmts[i].getValue(1); 9345 } 9346 9347 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9348 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9349 9350 SDValue RVals[] = { Value, LoadChain }; 9351 return DAG.getMergeValues(RVals, dl); 9352 } 9353 9354 /// Lowering for QPX v4i1 stores 9355 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9356 SelectionDAG &DAG) const { 9357 SDLoc dl(Op); 9358 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9359 SDValue StoreChain = SN->getChain(); 9360 SDValue BasePtr = SN->getBasePtr(); 9361 SDValue Value = SN->getValue(); 9362 9363 if (Value.getValueType() == MVT::v4f64 || 9364 Value.getValueType() == MVT::v4f32) { 9365 EVT MemVT = SN->getMemoryVT(); 9366 unsigned Alignment = SN->getAlignment(); 9367 9368 // If this store is properly aligned, then it is legal. 9369 if (Alignment >= MemVT.getStoreSize()) 9370 return Op; 9371 9372 EVT ScalarVT = Value.getValueType().getScalarType(), 9373 ScalarMemVT = MemVT.getScalarType(); 9374 unsigned Stride = ScalarMemVT.getStoreSize(); 9375 9376 SDValue Stores[4]; 9377 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9378 SDValue Ex = DAG.getNode( 9379 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9380 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9381 SDValue Store; 9382 if (ScalarVT != ScalarMemVT) 9383 Store = 9384 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9385 SN->getPointerInfo().getWithOffset(Idx * Stride), 9386 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9387 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9388 else 9389 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9390 SN->getPointerInfo().getWithOffset(Idx * Stride), 9391 MinAlign(Alignment, Idx * Stride), 9392 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9393 9394 if (Idx == 0 && SN->isIndexed()) { 9395 assert(SN->getAddressingMode() == ISD::PRE_INC && 9396 "Unknown addressing mode on vector store"); 9397 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9398 SN->getAddressingMode()); 9399 } 9400 9401 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9402 DAG.getConstant(Stride, dl, 9403 BasePtr.getValueType())); 9404 Stores[Idx] = Store; 9405 } 9406 9407 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9408 9409 if (SN->isIndexed()) { 9410 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9411 return DAG.getMergeValues(RetOps, dl); 9412 } 9413 9414 return TF; 9415 } 9416 9417 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9418 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9419 9420 // The values are now known to be -1 (false) or 1 (true). To convert this 9421 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9422 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9423 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9424 9425 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9426 // understand how to form the extending load. 9427 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9428 9429 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9430 9431 // Now convert to an integer and store. 9432 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9433 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9434 Value); 9435 9436 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9437 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9438 MachinePointerInfo PtrInfo = 9439 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9440 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9441 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9442 9443 SDValue Ops[] = {StoreChain, 9444 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9445 Value, FIdx}; 9446 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9447 9448 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9449 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9450 9451 // Move data into the byte array. 9452 SDValue Loads[4], LoadChains[4]; 9453 for (unsigned i = 0; i < 4; ++i) { 9454 unsigned Offset = 4*i; 9455 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9456 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9457 9458 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9459 PtrInfo.getWithOffset(Offset)); 9460 LoadChains[i] = Loads[i].getValue(1); 9461 } 9462 9463 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9464 9465 SDValue Stores[4]; 9466 for (unsigned i = 0; i < 4; ++i) { 9467 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9468 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9469 9470 Stores[i] = DAG.getTruncStore( 9471 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9472 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9473 SN->getAAInfo()); 9474 } 9475 9476 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9477 9478 return StoreChain; 9479 } 9480 9481 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9482 SDLoc dl(Op); 9483 if (Op.getValueType() == MVT::v4i32) { 9484 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9485 9486 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9487 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9488 9489 SDValue RHSSwap = // = vrlw RHS, 16 9490 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9491 9492 // Shrinkify inputs to v8i16. 9493 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9494 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9495 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9496 9497 // Low parts multiplied together, generating 32-bit results (we ignore the 9498 // top parts). 9499 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9500 LHS, RHS, DAG, dl, MVT::v4i32); 9501 9502 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9503 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9504 // Shift the high parts up 16 bits. 9505 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9506 Neg16, DAG, dl); 9507 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9508 } else if (Op.getValueType() == MVT::v8i16) { 9509 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9510 9511 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9512 9513 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9514 LHS, RHS, Zero, DAG, dl); 9515 } else if (Op.getValueType() == MVT::v16i8) { 9516 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9517 bool isLittleEndian = Subtarget.isLittleEndian(); 9518 9519 // Multiply the even 8-bit parts, producing 16-bit sums. 9520 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9521 LHS, RHS, DAG, dl, MVT::v8i16); 9522 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9523 9524 // Multiply the odd 8-bit parts, producing 16-bit sums. 9525 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9526 LHS, RHS, DAG, dl, MVT::v8i16); 9527 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9528 9529 // Merge the results together. Because vmuleub and vmuloub are 9530 // instructions with a big-endian bias, we must reverse the 9531 // element numbering and reverse the meaning of "odd" and "even" 9532 // when generating little endian code. 9533 int Ops[16]; 9534 for (unsigned i = 0; i != 8; ++i) { 9535 if (isLittleEndian) { 9536 Ops[i*2 ] = 2*i; 9537 Ops[i*2+1] = 2*i+16; 9538 } else { 9539 Ops[i*2 ] = 2*i+1; 9540 Ops[i*2+1] = 2*i+1+16; 9541 } 9542 } 9543 if (isLittleEndian) 9544 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9545 else 9546 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9547 } else { 9548 llvm_unreachable("Unknown mul to lower!"); 9549 } 9550 } 9551 9552 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9553 9554 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9555 9556 EVT VT = Op.getValueType(); 9557 assert(VT.isVector() && 9558 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9559 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9560 VT == MVT::v16i8) && 9561 "Unexpected vector element type!"); 9562 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9563 "Current subtarget doesn't support smax v2i64!"); 9564 9565 // For vector abs, it can be lowered to: 9566 // abs x 9567 // ==> 9568 // y = -x 9569 // smax(x, y) 9570 9571 SDLoc dl(Op); 9572 SDValue X = Op.getOperand(0); 9573 SDValue Zero = DAG.getConstant(0, dl, VT); 9574 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9575 9576 // SMAX patch https://reviews.llvm.org/D47332 9577 // hasn't landed yet, so use intrinsic first here. 9578 // TODO: Should use SMAX directly once SMAX patch landed 9579 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9580 if (VT == MVT::v2i64) 9581 BifID = Intrinsic::ppc_altivec_vmaxsd; 9582 else if (VT == MVT::v8i16) 9583 BifID = Intrinsic::ppc_altivec_vmaxsh; 9584 else if (VT == MVT::v16i8) 9585 BifID = Intrinsic::ppc_altivec_vmaxsb; 9586 9587 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9588 } 9589 9590 /// LowerOperation - Provide custom lowering hooks for some operations. 9591 /// 9592 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9593 switch (Op.getOpcode()) { 9594 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9595 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9596 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9597 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9598 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9599 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9600 case ISD::SETCC: return LowerSETCC(Op, DAG); 9601 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9602 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9603 9604 // Variable argument lowering. 9605 case ISD::VASTART: return LowerVASTART(Op, DAG); 9606 case ISD::VAARG: return LowerVAARG(Op, DAG); 9607 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9608 9609 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9610 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9611 case ISD::GET_DYNAMIC_AREA_OFFSET: 9612 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9613 9614 // Exception handling lowering. 9615 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9616 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9617 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9618 9619 case ISD::LOAD: return LowerLOAD(Op, DAG); 9620 case ISD::STORE: return LowerSTORE(Op, DAG); 9621 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9622 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9623 case ISD::FP_TO_UINT: 9624 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9625 case ISD::UINT_TO_FP: 9626 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9627 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9628 9629 // Lower 64-bit shifts. 9630 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9631 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9632 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9633 9634 // Vector-related lowering. 9635 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9636 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9637 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9638 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9639 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9640 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9641 case ISD::MUL: return LowerMUL(Op, DAG); 9642 case ISD::ABS: return LowerABS(Op, DAG); 9643 9644 // For counter-based loop handling. 9645 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9646 9647 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9648 9649 // Frame & Return address. 9650 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9651 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9652 9653 case ISD::INTRINSIC_VOID: 9654 return LowerINTRINSIC_VOID(Op, DAG); 9655 case ISD::SREM: 9656 case ISD::UREM: 9657 return LowerREM(Op, DAG); 9658 case ISD::BSWAP: 9659 return LowerBSWAP(Op, DAG); 9660 case ISD::ATOMIC_CMP_SWAP: 9661 return LowerATOMIC_CMP_SWAP(Op, DAG); 9662 } 9663 } 9664 9665 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9666 SmallVectorImpl<SDValue>&Results, 9667 SelectionDAG &DAG) const { 9668 SDLoc dl(N); 9669 switch (N->getOpcode()) { 9670 default: 9671 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9672 case ISD::READCYCLECOUNTER: { 9673 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9674 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9675 9676 Results.push_back(RTB); 9677 Results.push_back(RTB.getValue(1)); 9678 Results.push_back(RTB.getValue(2)); 9679 break; 9680 } 9681 case ISD::INTRINSIC_W_CHAIN: { 9682 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9683 Intrinsic::ppc_is_decremented_ctr_nonzero) 9684 break; 9685 9686 assert(N->getValueType(0) == MVT::i1 && 9687 "Unexpected result type for CTR decrement intrinsic"); 9688 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9689 N->getValueType(0)); 9690 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9691 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9692 N->getOperand(1)); 9693 9694 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9695 Results.push_back(NewInt.getValue(1)); 9696 break; 9697 } 9698 case ISD::VAARG: { 9699 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9700 return; 9701 9702 EVT VT = N->getValueType(0); 9703 9704 if (VT == MVT::i64) { 9705 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9706 9707 Results.push_back(NewNode); 9708 Results.push_back(NewNode.getValue(1)); 9709 } 9710 return; 9711 } 9712 case ISD::FP_TO_SINT: 9713 case ISD::FP_TO_UINT: 9714 // LowerFP_TO_INT() can only handle f32 and f64. 9715 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9716 return; 9717 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9718 return; 9719 case ISD::TRUNCATE: { 9720 EVT TrgVT = N->getValueType(0); 9721 if (TrgVT.isVector() && 9722 isOperationCustom(N->getOpcode(), TrgVT) && 9723 N->getOperand(0).getValueType().getSizeInBits() <= 128) 9724 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 9725 return; 9726 } 9727 case ISD::BITCAST: 9728 // Don't handle bitcast here. 9729 return; 9730 } 9731 } 9732 9733 //===----------------------------------------------------------------------===// 9734 // Other Lowering Code 9735 //===----------------------------------------------------------------------===// 9736 9737 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9738 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9739 Function *Func = Intrinsic::getDeclaration(M, Id); 9740 return Builder.CreateCall(Func, {}); 9741 } 9742 9743 // The mappings for emitLeading/TrailingFence is taken from 9744 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9745 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9746 Instruction *Inst, 9747 AtomicOrdering Ord) const { 9748 if (Ord == AtomicOrdering::SequentiallyConsistent) 9749 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9750 if (isReleaseOrStronger(Ord)) 9751 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9752 return nullptr; 9753 } 9754 9755 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9756 Instruction *Inst, 9757 AtomicOrdering Ord) const { 9758 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9759 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9760 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9761 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9762 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9763 return Builder.CreateCall( 9764 Intrinsic::getDeclaration( 9765 Builder.GetInsertBlock()->getParent()->getParent(), 9766 Intrinsic::ppc_cfence, {Inst->getType()}), 9767 {Inst}); 9768 // FIXME: Can use isync for rmw operation. 9769 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9770 } 9771 return nullptr; 9772 } 9773 9774 MachineBasicBlock * 9775 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9776 unsigned AtomicSize, 9777 unsigned BinOpcode, 9778 unsigned CmpOpcode, 9779 unsigned CmpPred) const { 9780 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9781 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9782 9783 auto LoadMnemonic = PPC::LDARX; 9784 auto StoreMnemonic = PPC::STDCX; 9785 switch (AtomicSize) { 9786 default: 9787 llvm_unreachable("Unexpected size of atomic entity"); 9788 case 1: 9789 LoadMnemonic = PPC::LBARX; 9790 StoreMnemonic = PPC::STBCX; 9791 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9792 break; 9793 case 2: 9794 LoadMnemonic = PPC::LHARX; 9795 StoreMnemonic = PPC::STHCX; 9796 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9797 break; 9798 case 4: 9799 LoadMnemonic = PPC::LWARX; 9800 StoreMnemonic = PPC::STWCX; 9801 break; 9802 case 8: 9803 LoadMnemonic = PPC::LDARX; 9804 StoreMnemonic = PPC::STDCX; 9805 break; 9806 } 9807 9808 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9809 MachineFunction *F = BB->getParent(); 9810 MachineFunction::iterator It = ++BB->getIterator(); 9811 9812 unsigned dest = MI.getOperand(0).getReg(); 9813 unsigned ptrA = MI.getOperand(1).getReg(); 9814 unsigned ptrB = MI.getOperand(2).getReg(); 9815 unsigned incr = MI.getOperand(3).getReg(); 9816 DebugLoc dl = MI.getDebugLoc(); 9817 9818 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9819 MachineBasicBlock *loop2MBB = 9820 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9821 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9822 F->insert(It, loopMBB); 9823 if (CmpOpcode) 9824 F->insert(It, loop2MBB); 9825 F->insert(It, exitMBB); 9826 exitMBB->splice(exitMBB->begin(), BB, 9827 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9828 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9829 9830 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9831 unsigned TmpReg = (!BinOpcode) ? incr : 9832 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9833 : &PPC::GPRCRegClass); 9834 9835 // thisMBB: 9836 // ... 9837 // fallthrough --> loopMBB 9838 BB->addSuccessor(loopMBB); 9839 9840 // loopMBB: 9841 // l[wd]arx dest, ptr 9842 // add r0, dest, incr 9843 // st[wd]cx. r0, ptr 9844 // bne- loopMBB 9845 // fallthrough --> exitMBB 9846 9847 // For max/min... 9848 // loopMBB: 9849 // l[wd]arx dest, ptr 9850 // cmpl?[wd] incr, dest 9851 // bgt exitMBB 9852 // loop2MBB: 9853 // st[wd]cx. dest, ptr 9854 // bne- loopMBB 9855 // fallthrough --> exitMBB 9856 9857 BB = loopMBB; 9858 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9859 .addReg(ptrA).addReg(ptrB); 9860 if (BinOpcode) 9861 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9862 if (CmpOpcode) { 9863 // Signed comparisons of byte or halfword values must be sign-extended. 9864 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9865 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9866 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9867 ExtReg).addReg(dest); 9868 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9869 .addReg(incr).addReg(ExtReg); 9870 } else 9871 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9872 .addReg(incr).addReg(dest); 9873 9874 BuildMI(BB, dl, TII->get(PPC::BCC)) 9875 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9876 BB->addSuccessor(loop2MBB); 9877 BB->addSuccessor(exitMBB); 9878 BB = loop2MBB; 9879 } 9880 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9881 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9882 BuildMI(BB, dl, TII->get(PPC::BCC)) 9883 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9884 BB->addSuccessor(loopMBB); 9885 BB->addSuccessor(exitMBB); 9886 9887 // exitMBB: 9888 // ... 9889 BB = exitMBB; 9890 return BB; 9891 } 9892 9893 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 9894 MachineInstr &MI, MachineBasicBlock *BB, 9895 bool is8bit, // operation 9896 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 9897 // If we support part-word atomic mnemonics, just use them 9898 if (Subtarget.hasPartwordAtomics()) 9899 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 9900 CmpPred); 9901 9902 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9903 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9904 // In 64 bit mode we have to use 64 bits for addresses, even though the 9905 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9906 // registers without caring whether they're 32 or 64, but here we're 9907 // doing actual arithmetic on the addresses. 9908 bool is64bit = Subtarget.isPPC64(); 9909 bool isLittleEndian = Subtarget.isLittleEndian(); 9910 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9911 9912 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9913 MachineFunction *F = BB->getParent(); 9914 MachineFunction::iterator It = ++BB->getIterator(); 9915 9916 unsigned dest = MI.getOperand(0).getReg(); 9917 unsigned ptrA = MI.getOperand(1).getReg(); 9918 unsigned ptrB = MI.getOperand(2).getReg(); 9919 unsigned incr = MI.getOperand(3).getReg(); 9920 DebugLoc dl = MI.getDebugLoc(); 9921 9922 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9923 MachineBasicBlock *loop2MBB = 9924 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9925 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9926 F->insert(It, loopMBB); 9927 if (CmpOpcode) 9928 F->insert(It, loop2MBB); 9929 F->insert(It, exitMBB); 9930 exitMBB->splice(exitMBB->begin(), BB, 9931 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9932 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9933 9934 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9935 const TargetRegisterClass *RC = 9936 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9937 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 9938 9939 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9940 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 9941 unsigned ShiftReg = 9942 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 9943 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC); 9944 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 9945 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 9946 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 9947 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 9948 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 9949 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 9950 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 9951 unsigned Ptr1Reg; 9952 unsigned TmpReg = 9953 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 9954 9955 // thisMBB: 9956 // ... 9957 // fallthrough --> loopMBB 9958 BB->addSuccessor(loopMBB); 9959 9960 // The 4-byte load must be aligned, while a char or short may be 9961 // anywhere in the word. Hence all this nasty bookkeeping code. 9962 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9963 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9964 // xori shift, shift1, 24 [16] 9965 // rlwinm ptr, ptr1, 0, 0, 29 9966 // slw incr2, incr, shift 9967 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9968 // slw mask, mask2, shift 9969 // loopMBB: 9970 // lwarx tmpDest, ptr 9971 // add tmp, tmpDest, incr2 9972 // andc tmp2, tmpDest, mask 9973 // and tmp3, tmp, mask 9974 // or tmp4, tmp3, tmp2 9975 // stwcx. tmp4, ptr 9976 // bne- loopMBB 9977 // fallthrough --> exitMBB 9978 // srw dest, tmpDest, shift 9979 if (ptrA != ZeroReg) { 9980 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9981 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9982 .addReg(ptrA) 9983 .addReg(ptrB); 9984 } else { 9985 Ptr1Reg = ptrB; 9986 } 9987 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 9988 // mode. 9989 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 9990 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 9991 .addImm(3) 9992 .addImm(27) 9993 .addImm(is8bit ? 28 : 27); 9994 if (!isLittleEndian) 9995 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 9996 .addReg(Shift1Reg) 9997 .addImm(is8bit ? 24 : 16); 9998 if (is64bit) 9999 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10000 .addReg(Ptr1Reg) 10001 .addImm(0) 10002 .addImm(61); 10003 else 10004 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10005 .addReg(Ptr1Reg) 10006 .addImm(0) 10007 .addImm(0) 10008 .addImm(29); 10009 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10010 if (is8bit) 10011 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10012 else { 10013 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10014 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10015 .addReg(Mask3Reg) 10016 .addImm(65535); 10017 } 10018 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10019 .addReg(Mask2Reg) 10020 .addReg(ShiftReg); 10021 10022 BB = loopMBB; 10023 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10024 .addReg(ZeroReg) 10025 .addReg(PtrReg); 10026 if (BinOpcode) 10027 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10028 .addReg(Incr2Reg) 10029 .addReg(TmpDestReg); 10030 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10031 .addReg(TmpDestReg) 10032 .addReg(MaskReg); 10033 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10034 if (CmpOpcode) { 10035 // For unsigned comparisons, we can directly compare the shifted values. 10036 // For signed comparisons we shift and sign extend. 10037 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10038 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10039 .addReg(TmpDestReg) 10040 .addReg(MaskReg); 10041 unsigned ValueReg = SReg; 10042 unsigned CmpReg = Incr2Reg; 10043 if (CmpOpcode == PPC::CMPW) { 10044 ValueReg = RegInfo.createVirtualRegister(GPRC); 10045 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10046 .addReg(SReg) 10047 .addReg(ShiftReg); 10048 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10049 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10050 .addReg(ValueReg); 10051 ValueReg = ValueSReg; 10052 CmpReg = incr; 10053 } 10054 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10055 .addReg(CmpReg) 10056 .addReg(ValueReg); 10057 BuildMI(BB, dl, TII->get(PPC::BCC)) 10058 .addImm(CmpPred) 10059 .addReg(PPC::CR0) 10060 .addMBB(exitMBB); 10061 BB->addSuccessor(loop2MBB); 10062 BB->addSuccessor(exitMBB); 10063 BB = loop2MBB; 10064 } 10065 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10066 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10067 .addReg(Tmp4Reg) 10068 .addReg(ZeroReg) 10069 .addReg(PtrReg); 10070 BuildMI(BB, dl, TII->get(PPC::BCC)) 10071 .addImm(PPC::PRED_NE) 10072 .addReg(PPC::CR0) 10073 .addMBB(loopMBB); 10074 BB->addSuccessor(loopMBB); 10075 BB->addSuccessor(exitMBB); 10076 10077 // exitMBB: 10078 // ... 10079 BB = exitMBB; 10080 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10081 .addReg(TmpDestReg) 10082 .addReg(ShiftReg); 10083 return BB; 10084 } 10085 10086 llvm::MachineBasicBlock * 10087 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10088 MachineBasicBlock *MBB) const { 10089 DebugLoc DL = MI.getDebugLoc(); 10090 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10091 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10092 10093 MachineFunction *MF = MBB->getParent(); 10094 MachineRegisterInfo &MRI = MF->getRegInfo(); 10095 10096 const BasicBlock *BB = MBB->getBasicBlock(); 10097 MachineFunction::iterator I = ++MBB->getIterator(); 10098 10099 unsigned DstReg = MI.getOperand(0).getReg(); 10100 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10101 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10102 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10103 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10104 10105 MVT PVT = getPointerTy(MF->getDataLayout()); 10106 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10107 "Invalid Pointer Size!"); 10108 // For v = setjmp(buf), we generate 10109 // 10110 // thisMBB: 10111 // SjLjSetup mainMBB 10112 // bl mainMBB 10113 // v_restore = 1 10114 // b sinkMBB 10115 // 10116 // mainMBB: 10117 // buf[LabelOffset] = LR 10118 // v_main = 0 10119 // 10120 // sinkMBB: 10121 // v = phi(main, restore) 10122 // 10123 10124 MachineBasicBlock *thisMBB = MBB; 10125 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10126 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10127 MF->insert(I, mainMBB); 10128 MF->insert(I, sinkMBB); 10129 10130 MachineInstrBuilder MIB; 10131 10132 // Transfer the remainder of BB and its successor edges to sinkMBB. 10133 sinkMBB->splice(sinkMBB->begin(), MBB, 10134 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10135 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10136 10137 // Note that the structure of the jmp_buf used here is not compatible 10138 // with that used by libc, and is not designed to be. Specifically, it 10139 // stores only those 'reserved' registers that LLVM does not otherwise 10140 // understand how to spill. Also, by convention, by the time this 10141 // intrinsic is called, Clang has already stored the frame address in the 10142 // first slot of the buffer and stack address in the third. Following the 10143 // X86 target code, we'll store the jump address in the second slot. We also 10144 // need to save the TOC pointer (R2) to handle jumps between shared 10145 // libraries, and that will be stored in the fourth slot. The thread 10146 // identifier (R13) is not affected. 10147 10148 // thisMBB: 10149 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10150 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10151 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10152 10153 // Prepare IP either in reg. 10154 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10155 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10156 unsigned BufReg = MI.getOperand(1).getReg(); 10157 10158 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10159 setUsesTOCBasePtr(*MBB->getParent()); 10160 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10161 .addReg(PPC::X2) 10162 .addImm(TOCOffset) 10163 .addReg(BufReg) 10164 .cloneMemRefs(MI); 10165 } 10166 10167 // Naked functions never have a base pointer, and so we use r1. For all 10168 // other functions, this decision must be delayed until during PEI. 10169 unsigned BaseReg; 10170 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10171 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10172 else 10173 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10174 10175 MIB = BuildMI(*thisMBB, MI, DL, 10176 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10177 .addReg(BaseReg) 10178 .addImm(BPOffset) 10179 .addReg(BufReg) 10180 .cloneMemRefs(MI); 10181 10182 // Setup 10183 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10184 MIB.addRegMask(TRI->getNoPreservedMask()); 10185 10186 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10187 10188 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10189 .addMBB(mainMBB); 10190 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10191 10192 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10193 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10194 10195 // mainMBB: 10196 // mainDstReg = 0 10197 MIB = 10198 BuildMI(mainMBB, DL, 10199 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10200 10201 // Store IP 10202 if (Subtarget.isPPC64()) { 10203 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10204 .addReg(LabelReg) 10205 .addImm(LabelOffset) 10206 .addReg(BufReg); 10207 } else { 10208 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10209 .addReg(LabelReg) 10210 .addImm(LabelOffset) 10211 .addReg(BufReg); 10212 } 10213 MIB.cloneMemRefs(MI); 10214 10215 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10216 mainMBB->addSuccessor(sinkMBB); 10217 10218 // sinkMBB: 10219 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10220 TII->get(PPC::PHI), DstReg) 10221 .addReg(mainDstReg).addMBB(mainMBB) 10222 .addReg(restoreDstReg).addMBB(thisMBB); 10223 10224 MI.eraseFromParent(); 10225 return sinkMBB; 10226 } 10227 10228 MachineBasicBlock * 10229 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10230 MachineBasicBlock *MBB) const { 10231 DebugLoc DL = MI.getDebugLoc(); 10232 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10233 10234 MachineFunction *MF = MBB->getParent(); 10235 MachineRegisterInfo &MRI = MF->getRegInfo(); 10236 10237 MVT PVT = getPointerTy(MF->getDataLayout()); 10238 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10239 "Invalid Pointer Size!"); 10240 10241 const TargetRegisterClass *RC = 10242 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10243 unsigned Tmp = MRI.createVirtualRegister(RC); 10244 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10245 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10246 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10247 unsigned BP = 10248 (PVT == MVT::i64) 10249 ? PPC::X30 10250 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10251 : PPC::R30); 10252 10253 MachineInstrBuilder MIB; 10254 10255 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10256 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10257 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10258 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10259 10260 unsigned BufReg = MI.getOperand(0).getReg(); 10261 10262 // Reload FP (the jumped-to function may not have had a 10263 // frame pointer, and if so, then its r31 will be restored 10264 // as necessary). 10265 if (PVT == MVT::i64) { 10266 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10267 .addImm(0) 10268 .addReg(BufReg); 10269 } else { 10270 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10271 .addImm(0) 10272 .addReg(BufReg); 10273 } 10274 MIB.cloneMemRefs(MI); 10275 10276 // Reload IP 10277 if (PVT == MVT::i64) { 10278 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10279 .addImm(LabelOffset) 10280 .addReg(BufReg); 10281 } else { 10282 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10283 .addImm(LabelOffset) 10284 .addReg(BufReg); 10285 } 10286 MIB.cloneMemRefs(MI); 10287 10288 // Reload SP 10289 if (PVT == MVT::i64) { 10290 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10291 .addImm(SPOffset) 10292 .addReg(BufReg); 10293 } else { 10294 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10295 .addImm(SPOffset) 10296 .addReg(BufReg); 10297 } 10298 MIB.cloneMemRefs(MI); 10299 10300 // Reload BP 10301 if (PVT == MVT::i64) { 10302 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10303 .addImm(BPOffset) 10304 .addReg(BufReg); 10305 } else { 10306 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10307 .addImm(BPOffset) 10308 .addReg(BufReg); 10309 } 10310 MIB.cloneMemRefs(MI); 10311 10312 // Reload TOC 10313 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10314 setUsesTOCBasePtr(*MBB->getParent()); 10315 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10316 .addImm(TOCOffset) 10317 .addReg(BufReg) 10318 .cloneMemRefs(MI); 10319 } 10320 10321 // Jump 10322 BuildMI(*MBB, MI, DL, 10323 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10324 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10325 10326 MI.eraseFromParent(); 10327 return MBB; 10328 } 10329 10330 MachineBasicBlock * 10331 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10332 MachineBasicBlock *BB) const { 10333 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10334 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10335 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10336 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10337 // Call lowering should have added an r2 operand to indicate a dependence 10338 // on the TOC base pointer value. It can't however, because there is no 10339 // way to mark the dependence as implicit there, and so the stackmap code 10340 // will confuse it with a regular operand. Instead, add the dependence 10341 // here. 10342 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10343 } 10344 10345 return emitPatchPoint(MI, BB); 10346 } 10347 10348 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10349 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10350 return emitEHSjLjSetJmp(MI, BB); 10351 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10352 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10353 return emitEHSjLjLongJmp(MI, BB); 10354 } 10355 10356 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10357 10358 // To "insert" these instructions we actually have to insert their 10359 // control-flow patterns. 10360 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10361 MachineFunction::iterator It = ++BB->getIterator(); 10362 10363 MachineFunction *F = BB->getParent(); 10364 10365 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10366 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10367 MI.getOpcode() == PPC::SELECT_I8) { 10368 SmallVector<MachineOperand, 2> Cond; 10369 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10370 MI.getOpcode() == PPC::SELECT_CC_I8) 10371 Cond.push_back(MI.getOperand(4)); 10372 else 10373 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10374 Cond.push_back(MI.getOperand(1)); 10375 10376 DebugLoc dl = MI.getDebugLoc(); 10377 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10378 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10379 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10380 MI.getOpcode() == PPC::SELECT_CC_I8 || 10381 MI.getOpcode() == PPC::SELECT_CC_F4 || 10382 MI.getOpcode() == PPC::SELECT_CC_F8 || 10383 MI.getOpcode() == PPC::SELECT_CC_F16 || 10384 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10385 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10386 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10387 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10388 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10389 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10390 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10391 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10392 MI.getOpcode() == PPC::SELECT_CC_SPE || 10393 MI.getOpcode() == PPC::SELECT_I4 || 10394 MI.getOpcode() == PPC::SELECT_I8 || 10395 MI.getOpcode() == PPC::SELECT_F4 || 10396 MI.getOpcode() == PPC::SELECT_F8 || 10397 MI.getOpcode() == PPC::SELECT_F16 || 10398 MI.getOpcode() == PPC::SELECT_QFRC || 10399 MI.getOpcode() == PPC::SELECT_QSRC || 10400 MI.getOpcode() == PPC::SELECT_QBRC || 10401 MI.getOpcode() == PPC::SELECT_SPE || 10402 MI.getOpcode() == PPC::SELECT_SPE4 || 10403 MI.getOpcode() == PPC::SELECT_VRRC || 10404 MI.getOpcode() == PPC::SELECT_VSFRC || 10405 MI.getOpcode() == PPC::SELECT_VSSRC || 10406 MI.getOpcode() == PPC::SELECT_VSRC) { 10407 // The incoming instruction knows the destination vreg to set, the 10408 // condition code register to branch on, the true/false values to 10409 // select between, and a branch opcode to use. 10410 10411 // thisMBB: 10412 // ... 10413 // TrueVal = ... 10414 // cmpTY ccX, r1, r2 10415 // bCC copy1MBB 10416 // fallthrough --> copy0MBB 10417 MachineBasicBlock *thisMBB = BB; 10418 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10419 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10420 DebugLoc dl = MI.getDebugLoc(); 10421 F->insert(It, copy0MBB); 10422 F->insert(It, sinkMBB); 10423 10424 // Transfer the remainder of BB and its successor edges to sinkMBB. 10425 sinkMBB->splice(sinkMBB->begin(), BB, 10426 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10427 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10428 10429 // Next, add the true and fallthrough blocks as its successors. 10430 BB->addSuccessor(copy0MBB); 10431 BB->addSuccessor(sinkMBB); 10432 10433 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10434 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10435 MI.getOpcode() == PPC::SELECT_F16 || 10436 MI.getOpcode() == PPC::SELECT_SPE4 || 10437 MI.getOpcode() == PPC::SELECT_SPE || 10438 MI.getOpcode() == PPC::SELECT_QFRC || 10439 MI.getOpcode() == PPC::SELECT_QSRC || 10440 MI.getOpcode() == PPC::SELECT_QBRC || 10441 MI.getOpcode() == PPC::SELECT_VRRC || 10442 MI.getOpcode() == PPC::SELECT_VSFRC || 10443 MI.getOpcode() == PPC::SELECT_VSSRC || 10444 MI.getOpcode() == PPC::SELECT_VSRC) { 10445 BuildMI(BB, dl, TII->get(PPC::BC)) 10446 .addReg(MI.getOperand(1).getReg()) 10447 .addMBB(sinkMBB); 10448 } else { 10449 unsigned SelectPred = MI.getOperand(4).getImm(); 10450 BuildMI(BB, dl, TII->get(PPC::BCC)) 10451 .addImm(SelectPred) 10452 .addReg(MI.getOperand(1).getReg()) 10453 .addMBB(sinkMBB); 10454 } 10455 10456 // copy0MBB: 10457 // %FalseValue = ... 10458 // # fallthrough to sinkMBB 10459 BB = copy0MBB; 10460 10461 // Update machine-CFG edges 10462 BB->addSuccessor(sinkMBB); 10463 10464 // sinkMBB: 10465 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10466 // ... 10467 BB = sinkMBB; 10468 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10469 .addReg(MI.getOperand(3).getReg()) 10470 .addMBB(copy0MBB) 10471 .addReg(MI.getOperand(2).getReg()) 10472 .addMBB(thisMBB); 10473 } else if (MI.getOpcode() == PPC::ReadTB) { 10474 // To read the 64-bit time-base register on a 32-bit target, we read the 10475 // two halves. Should the counter have wrapped while it was being read, we 10476 // need to try again. 10477 // ... 10478 // readLoop: 10479 // mfspr Rx,TBU # load from TBU 10480 // mfspr Ry,TB # load from TB 10481 // mfspr Rz,TBU # load from TBU 10482 // cmpw crX,Rx,Rz # check if 'old'='new' 10483 // bne readLoop # branch if they're not equal 10484 // ... 10485 10486 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10487 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10488 DebugLoc dl = MI.getDebugLoc(); 10489 F->insert(It, readMBB); 10490 F->insert(It, sinkMBB); 10491 10492 // Transfer the remainder of BB and its successor edges to sinkMBB. 10493 sinkMBB->splice(sinkMBB->begin(), BB, 10494 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10495 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10496 10497 BB->addSuccessor(readMBB); 10498 BB = readMBB; 10499 10500 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10501 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10502 unsigned LoReg = MI.getOperand(0).getReg(); 10503 unsigned HiReg = MI.getOperand(1).getReg(); 10504 10505 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10506 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10507 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10508 10509 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10510 10511 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10512 .addReg(HiReg) 10513 .addReg(ReadAgainReg); 10514 BuildMI(BB, dl, TII->get(PPC::BCC)) 10515 .addImm(PPC::PRED_NE) 10516 .addReg(CmpReg) 10517 .addMBB(readMBB); 10518 10519 BB->addSuccessor(readMBB); 10520 BB->addSuccessor(sinkMBB); 10521 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10522 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10523 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10524 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10525 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10526 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10527 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10528 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10529 10530 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10531 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10532 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10533 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10535 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10536 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10537 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10538 10539 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10540 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10541 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10542 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10544 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10546 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10547 10548 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10549 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10550 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10551 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10553 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10555 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10556 10557 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10558 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10559 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10560 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10562 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10564 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10565 10566 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10567 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10568 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10569 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10571 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10573 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10574 10575 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10576 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10577 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10578 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10579 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10580 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10582 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10583 10584 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10585 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10586 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10587 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10588 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10589 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10591 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10592 10593 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10594 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10595 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10596 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10597 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10598 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10600 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10601 10602 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10603 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10604 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10605 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10606 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10607 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10608 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10609 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10610 10611 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10612 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10613 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10614 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10615 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10616 BB = EmitAtomicBinary(MI, BB, 4, 0); 10617 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10618 BB = EmitAtomicBinary(MI, BB, 8, 0); 10619 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10620 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10621 (Subtarget.hasPartwordAtomics() && 10622 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10623 (Subtarget.hasPartwordAtomics() && 10624 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10625 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10626 10627 auto LoadMnemonic = PPC::LDARX; 10628 auto StoreMnemonic = PPC::STDCX; 10629 switch (MI.getOpcode()) { 10630 default: 10631 llvm_unreachable("Compare and swap of unknown size"); 10632 case PPC::ATOMIC_CMP_SWAP_I8: 10633 LoadMnemonic = PPC::LBARX; 10634 StoreMnemonic = PPC::STBCX; 10635 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10636 break; 10637 case PPC::ATOMIC_CMP_SWAP_I16: 10638 LoadMnemonic = PPC::LHARX; 10639 StoreMnemonic = PPC::STHCX; 10640 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10641 break; 10642 case PPC::ATOMIC_CMP_SWAP_I32: 10643 LoadMnemonic = PPC::LWARX; 10644 StoreMnemonic = PPC::STWCX; 10645 break; 10646 case PPC::ATOMIC_CMP_SWAP_I64: 10647 LoadMnemonic = PPC::LDARX; 10648 StoreMnemonic = PPC::STDCX; 10649 break; 10650 } 10651 unsigned dest = MI.getOperand(0).getReg(); 10652 unsigned ptrA = MI.getOperand(1).getReg(); 10653 unsigned ptrB = MI.getOperand(2).getReg(); 10654 unsigned oldval = MI.getOperand(3).getReg(); 10655 unsigned newval = MI.getOperand(4).getReg(); 10656 DebugLoc dl = MI.getDebugLoc(); 10657 10658 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10659 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10660 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10661 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10662 F->insert(It, loop1MBB); 10663 F->insert(It, loop2MBB); 10664 F->insert(It, midMBB); 10665 F->insert(It, exitMBB); 10666 exitMBB->splice(exitMBB->begin(), BB, 10667 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10668 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10669 10670 // thisMBB: 10671 // ... 10672 // fallthrough --> loopMBB 10673 BB->addSuccessor(loop1MBB); 10674 10675 // loop1MBB: 10676 // l[bhwd]arx dest, ptr 10677 // cmp[wd] dest, oldval 10678 // bne- midMBB 10679 // loop2MBB: 10680 // st[bhwd]cx. newval, ptr 10681 // bne- loopMBB 10682 // b exitBB 10683 // midMBB: 10684 // st[bhwd]cx. dest, ptr 10685 // exitBB: 10686 BB = loop1MBB; 10687 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10688 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10689 .addReg(oldval) 10690 .addReg(dest); 10691 BuildMI(BB, dl, TII->get(PPC::BCC)) 10692 .addImm(PPC::PRED_NE) 10693 .addReg(PPC::CR0) 10694 .addMBB(midMBB); 10695 BB->addSuccessor(loop2MBB); 10696 BB->addSuccessor(midMBB); 10697 10698 BB = loop2MBB; 10699 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10700 .addReg(newval) 10701 .addReg(ptrA) 10702 .addReg(ptrB); 10703 BuildMI(BB, dl, TII->get(PPC::BCC)) 10704 .addImm(PPC::PRED_NE) 10705 .addReg(PPC::CR0) 10706 .addMBB(loop1MBB); 10707 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10708 BB->addSuccessor(loop1MBB); 10709 BB->addSuccessor(exitMBB); 10710 10711 BB = midMBB; 10712 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10713 .addReg(dest) 10714 .addReg(ptrA) 10715 .addReg(ptrB); 10716 BB->addSuccessor(exitMBB); 10717 10718 // exitMBB: 10719 // ... 10720 BB = exitMBB; 10721 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10722 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10723 // We must use 64-bit registers for addresses when targeting 64-bit, 10724 // since we're actually doing arithmetic on them. Other registers 10725 // can be 32-bit. 10726 bool is64bit = Subtarget.isPPC64(); 10727 bool isLittleEndian = Subtarget.isLittleEndian(); 10728 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10729 10730 unsigned dest = MI.getOperand(0).getReg(); 10731 unsigned ptrA = MI.getOperand(1).getReg(); 10732 unsigned ptrB = MI.getOperand(2).getReg(); 10733 unsigned oldval = MI.getOperand(3).getReg(); 10734 unsigned newval = MI.getOperand(4).getReg(); 10735 DebugLoc dl = MI.getDebugLoc(); 10736 10737 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10738 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10739 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10740 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10741 F->insert(It, loop1MBB); 10742 F->insert(It, loop2MBB); 10743 F->insert(It, midMBB); 10744 F->insert(It, exitMBB); 10745 exitMBB->splice(exitMBB->begin(), BB, 10746 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10747 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10748 10749 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10750 const TargetRegisterClass *RC = 10751 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10752 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10753 10754 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10755 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10756 unsigned ShiftReg = 10757 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10758 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 10759 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 10760 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 10761 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 10762 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10763 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10764 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10765 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10766 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10767 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10768 unsigned Ptr1Reg; 10769 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC); 10770 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10771 // thisMBB: 10772 // ... 10773 // fallthrough --> loopMBB 10774 BB->addSuccessor(loop1MBB); 10775 10776 // The 4-byte load must be aligned, while a char or short may be 10777 // anywhere in the word. Hence all this nasty bookkeeping code. 10778 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10779 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10780 // xori shift, shift1, 24 [16] 10781 // rlwinm ptr, ptr1, 0, 0, 29 10782 // slw newval2, newval, shift 10783 // slw oldval2, oldval,shift 10784 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10785 // slw mask, mask2, shift 10786 // and newval3, newval2, mask 10787 // and oldval3, oldval2, mask 10788 // loop1MBB: 10789 // lwarx tmpDest, ptr 10790 // and tmp, tmpDest, mask 10791 // cmpw tmp, oldval3 10792 // bne- midMBB 10793 // loop2MBB: 10794 // andc tmp2, tmpDest, mask 10795 // or tmp4, tmp2, newval3 10796 // stwcx. tmp4, ptr 10797 // bne- loop1MBB 10798 // b exitBB 10799 // midMBB: 10800 // stwcx. tmpDest, ptr 10801 // exitBB: 10802 // srw dest, tmpDest, shift 10803 if (ptrA != ZeroReg) { 10804 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10805 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10806 .addReg(ptrA) 10807 .addReg(ptrB); 10808 } else { 10809 Ptr1Reg = ptrB; 10810 } 10811 10812 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10813 // mode. 10814 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10815 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10816 .addImm(3) 10817 .addImm(27) 10818 .addImm(is8bit ? 28 : 27); 10819 if (!isLittleEndian) 10820 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10821 .addReg(Shift1Reg) 10822 .addImm(is8bit ? 24 : 16); 10823 if (is64bit) 10824 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10825 .addReg(Ptr1Reg) 10826 .addImm(0) 10827 .addImm(61); 10828 else 10829 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10830 .addReg(Ptr1Reg) 10831 .addImm(0) 10832 .addImm(0) 10833 .addImm(29); 10834 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10835 .addReg(newval) 10836 .addReg(ShiftReg); 10837 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10838 .addReg(oldval) 10839 .addReg(ShiftReg); 10840 if (is8bit) 10841 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10842 else { 10843 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10844 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10845 .addReg(Mask3Reg) 10846 .addImm(65535); 10847 } 10848 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10849 .addReg(Mask2Reg) 10850 .addReg(ShiftReg); 10851 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10852 .addReg(NewVal2Reg) 10853 .addReg(MaskReg); 10854 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10855 .addReg(OldVal2Reg) 10856 .addReg(MaskReg); 10857 10858 BB = loop1MBB; 10859 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10860 .addReg(ZeroReg) 10861 .addReg(PtrReg); 10862 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 10863 .addReg(TmpDestReg) 10864 .addReg(MaskReg); 10865 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10866 .addReg(TmpReg) 10867 .addReg(OldVal3Reg); 10868 BuildMI(BB, dl, TII->get(PPC::BCC)) 10869 .addImm(PPC::PRED_NE) 10870 .addReg(PPC::CR0) 10871 .addMBB(midMBB); 10872 BB->addSuccessor(loop2MBB); 10873 BB->addSuccessor(midMBB); 10874 10875 BB = loop2MBB; 10876 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10877 .addReg(TmpDestReg) 10878 .addReg(MaskReg); 10879 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 10880 .addReg(Tmp2Reg) 10881 .addReg(NewVal3Reg); 10882 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10883 .addReg(Tmp4Reg) 10884 .addReg(ZeroReg) 10885 .addReg(PtrReg); 10886 BuildMI(BB, dl, TII->get(PPC::BCC)) 10887 .addImm(PPC::PRED_NE) 10888 .addReg(PPC::CR0) 10889 .addMBB(loop1MBB); 10890 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10891 BB->addSuccessor(loop1MBB); 10892 BB->addSuccessor(exitMBB); 10893 10894 BB = midMBB; 10895 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10896 .addReg(TmpDestReg) 10897 .addReg(ZeroReg) 10898 .addReg(PtrReg); 10899 BB->addSuccessor(exitMBB); 10900 10901 // exitMBB: 10902 // ... 10903 BB = exitMBB; 10904 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10905 .addReg(TmpReg) 10906 .addReg(ShiftReg); 10907 } else if (MI.getOpcode() == PPC::FADDrtz) { 10908 // This pseudo performs an FADD with rounding mode temporarily forced 10909 // to round-to-zero. We emit this via custom inserter since the FPSCR 10910 // is not modeled at the SelectionDAG level. 10911 unsigned Dest = MI.getOperand(0).getReg(); 10912 unsigned Src1 = MI.getOperand(1).getReg(); 10913 unsigned Src2 = MI.getOperand(2).getReg(); 10914 DebugLoc dl = MI.getDebugLoc(); 10915 10916 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10917 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10918 10919 // Save FPSCR value. 10920 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10921 10922 // Set rounding mode to round-to-zero. 10923 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10924 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10925 10926 // Perform addition. 10927 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10928 10929 // Restore FPSCR value. 10930 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10931 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10932 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10933 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10934 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10935 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10936 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10937 ? PPC::ANDIo8 10938 : PPC::ANDIo; 10939 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10940 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10941 10942 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10943 unsigned Dest = RegInfo.createVirtualRegister( 10944 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 10945 10946 DebugLoc dl = MI.getDebugLoc(); 10947 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10948 .addReg(MI.getOperand(1).getReg()) 10949 .addImm(1); 10950 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10951 MI.getOperand(0).getReg()) 10952 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10953 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10954 DebugLoc Dl = MI.getDebugLoc(); 10955 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10956 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10957 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10958 return BB; 10959 } else if (MI.getOpcode() == PPC::SETRNDi) { 10960 DebugLoc dl = MI.getDebugLoc(); 10961 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 10962 10963 // Save FPSCR value. 10964 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 10965 10966 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 10967 // the following settings: 10968 // 00 Round to nearest 10969 // 01 Round to 0 10970 // 10 Round to +inf 10971 // 11 Round to -inf 10972 10973 // When the operand is immediate, using the two least significant bits of 10974 // the immediate to set the bits 62:63 of FPSCR. 10975 unsigned Mode = MI.getOperand(1).getImm(); 10976 BuildMI(*BB, MI, dl, TII->get(Mode & 1 ? PPC::MTFSB1 : PPC::MTFSB0)) 10977 .addImm(31); 10978 10979 BuildMI(*BB, MI, dl, TII->get(Mode & 2 ? PPC::MTFSB1 : PPC::MTFSB0)) 10980 .addImm(30); 10981 } else if (MI.getOpcode() == PPC::SETRND) { 10982 DebugLoc dl = MI.getDebugLoc(); 10983 10984 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 10985 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 10986 // If the target doesn't have DirectMove, we should use stack to do the 10987 // conversion, because the target doesn't have the instructions like mtvsrd 10988 // or mfvsrd to do this conversion directly. 10989 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 10990 if (Subtarget.hasDirectMove()) { 10991 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 10992 .addReg(SrcReg); 10993 } else { 10994 // Use stack to do the register copy. 10995 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 10996 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10997 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 10998 if (RC == &PPC::F8RCRegClass) { 10999 // Copy register from F8RCRegClass to G8RCRegclass. 11000 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11001 "Unsupported RegClass."); 11002 11003 StoreOp = PPC::STFD; 11004 LoadOp = PPC::LD; 11005 } else { 11006 // Copy register from G8RCRegClass to F8RCRegclass. 11007 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11008 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11009 "Unsupported RegClass."); 11010 } 11011 11012 MachineFrameInfo &MFI = F->getFrameInfo(); 11013 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11014 11015 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11016 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11017 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11018 MFI.getObjectAlignment(FrameIdx)); 11019 11020 // Store the SrcReg into the stack. 11021 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11022 .addReg(SrcReg) 11023 .addImm(0) 11024 .addFrameIndex(FrameIdx) 11025 .addMemOperand(MMOStore); 11026 11027 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11028 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11029 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11030 MFI.getObjectAlignment(FrameIdx)); 11031 11032 // Load from the stack where SrcReg is stored, and save to DestReg, 11033 // so we have done the RegClass conversion from RegClass::SrcReg to 11034 // RegClass::DestReg. 11035 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11036 .addImm(0) 11037 .addFrameIndex(FrameIdx) 11038 .addMemOperand(MMOLoad); 11039 } 11040 }; 11041 11042 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11043 11044 // Save FPSCR value. 11045 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11046 11047 // When the operand is gprc register, use two least significant bits of the 11048 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11049 // 11050 // copy OldFPSCRTmpReg, OldFPSCRReg 11051 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11052 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11053 // copy NewFPSCRReg, NewFPSCRTmpReg 11054 // mtfsf 255, NewFPSCRReg 11055 MachineOperand SrcOp = MI.getOperand(1); 11056 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11057 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11058 11059 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11060 11061 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11062 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11063 11064 // The first operand of INSERT_SUBREG should be a register which has 11065 // subregisters, we only care about its RegClass, so we should use an 11066 // IMPLICIT_DEF register. 11067 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11068 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11069 .addReg(ImDefReg) 11070 .add(SrcOp) 11071 .addImm(1); 11072 11073 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11074 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11075 .addReg(OldFPSCRTmpReg) 11076 .addReg(ExtSrcReg) 11077 .addImm(0) 11078 .addImm(62); 11079 11080 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11081 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11082 11083 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11084 // bits of FPSCR. 11085 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11086 .addImm(255) 11087 .addReg(NewFPSCRReg) 11088 .addImm(0) 11089 .addImm(0); 11090 } else { 11091 llvm_unreachable("Unexpected instr type to insert"); 11092 } 11093 11094 MI.eraseFromParent(); // The pseudo instruction is gone now. 11095 return BB; 11096 } 11097 11098 //===----------------------------------------------------------------------===// 11099 // Target Optimization Hooks 11100 //===----------------------------------------------------------------------===// 11101 11102 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11103 // For the estimates, convergence is quadratic, so we essentially double the 11104 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11105 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11106 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11107 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11108 if (VT.getScalarType() == MVT::f64) 11109 RefinementSteps++; 11110 return RefinementSteps; 11111 } 11112 11113 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11114 int Enabled, int &RefinementSteps, 11115 bool &UseOneConstNR, 11116 bool Reciprocal) const { 11117 EVT VT = Operand.getValueType(); 11118 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11119 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11120 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11121 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11122 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11123 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11124 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11125 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11126 11127 UseOneConstNR = true; 11128 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11129 } 11130 return SDValue(); 11131 } 11132 11133 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11134 int Enabled, 11135 int &RefinementSteps) const { 11136 EVT VT = Operand.getValueType(); 11137 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11138 (VT == MVT::f64 && Subtarget.hasFRE()) || 11139 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11140 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11141 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11142 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11143 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11144 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11145 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11146 } 11147 return SDValue(); 11148 } 11149 11150 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11151 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11152 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11153 // enabled for division), this functionality is redundant with the default 11154 // combiner logic (once the division -> reciprocal/multiply transformation 11155 // has taken place). As a result, this matters more for older cores than for 11156 // newer ones. 11157 11158 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11159 // reciprocal if there are two or more FDIVs (for embedded cores with only 11160 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11161 switch (Subtarget.getDarwinDirective()) { 11162 default: 11163 return 3; 11164 case PPC::DIR_440: 11165 case PPC::DIR_A2: 11166 case PPC::DIR_E500: 11167 case PPC::DIR_E500mc: 11168 case PPC::DIR_E5500: 11169 return 2; 11170 } 11171 } 11172 11173 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11174 // collapsed, and so we need to look through chains of them. 11175 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11176 int64_t& Offset, SelectionDAG &DAG) { 11177 if (DAG.isBaseWithConstantOffset(Loc)) { 11178 Base = Loc.getOperand(0); 11179 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11180 11181 // The base might itself be a base plus an offset, and if so, accumulate 11182 // that as well. 11183 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11184 } 11185 } 11186 11187 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11188 unsigned Bytes, int Dist, 11189 SelectionDAG &DAG) { 11190 if (VT.getSizeInBits() / 8 != Bytes) 11191 return false; 11192 11193 SDValue BaseLoc = Base->getBasePtr(); 11194 if (Loc.getOpcode() == ISD::FrameIndex) { 11195 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11196 return false; 11197 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11198 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11199 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11200 int FS = MFI.getObjectSize(FI); 11201 int BFS = MFI.getObjectSize(BFI); 11202 if (FS != BFS || FS != (int)Bytes) return false; 11203 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11204 } 11205 11206 SDValue Base1 = Loc, Base2 = BaseLoc; 11207 int64_t Offset1 = 0, Offset2 = 0; 11208 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11209 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11210 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11211 return true; 11212 11213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11214 const GlobalValue *GV1 = nullptr; 11215 const GlobalValue *GV2 = nullptr; 11216 Offset1 = 0; 11217 Offset2 = 0; 11218 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11219 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11220 if (isGA1 && isGA2 && GV1 == GV2) 11221 return Offset1 == (Offset2 + Dist*Bytes); 11222 return false; 11223 } 11224 11225 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11226 // not enforce equality of the chain operands. 11227 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11228 unsigned Bytes, int Dist, 11229 SelectionDAG &DAG) { 11230 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11231 EVT VT = LS->getMemoryVT(); 11232 SDValue Loc = LS->getBasePtr(); 11233 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11234 } 11235 11236 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11237 EVT VT; 11238 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11239 default: return false; 11240 case Intrinsic::ppc_qpx_qvlfd: 11241 case Intrinsic::ppc_qpx_qvlfda: 11242 VT = MVT::v4f64; 11243 break; 11244 case Intrinsic::ppc_qpx_qvlfs: 11245 case Intrinsic::ppc_qpx_qvlfsa: 11246 VT = MVT::v4f32; 11247 break; 11248 case Intrinsic::ppc_qpx_qvlfcd: 11249 case Intrinsic::ppc_qpx_qvlfcda: 11250 VT = MVT::v2f64; 11251 break; 11252 case Intrinsic::ppc_qpx_qvlfcs: 11253 case Intrinsic::ppc_qpx_qvlfcsa: 11254 VT = MVT::v2f32; 11255 break; 11256 case Intrinsic::ppc_qpx_qvlfiwa: 11257 case Intrinsic::ppc_qpx_qvlfiwz: 11258 case Intrinsic::ppc_altivec_lvx: 11259 case Intrinsic::ppc_altivec_lvxl: 11260 case Intrinsic::ppc_vsx_lxvw4x: 11261 case Intrinsic::ppc_vsx_lxvw4x_be: 11262 VT = MVT::v4i32; 11263 break; 11264 case Intrinsic::ppc_vsx_lxvd2x: 11265 case Intrinsic::ppc_vsx_lxvd2x_be: 11266 VT = MVT::v2f64; 11267 break; 11268 case Intrinsic::ppc_altivec_lvebx: 11269 VT = MVT::i8; 11270 break; 11271 case Intrinsic::ppc_altivec_lvehx: 11272 VT = MVT::i16; 11273 break; 11274 case Intrinsic::ppc_altivec_lvewx: 11275 VT = MVT::i32; 11276 break; 11277 } 11278 11279 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11280 } 11281 11282 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11283 EVT VT; 11284 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11285 default: return false; 11286 case Intrinsic::ppc_qpx_qvstfd: 11287 case Intrinsic::ppc_qpx_qvstfda: 11288 VT = MVT::v4f64; 11289 break; 11290 case Intrinsic::ppc_qpx_qvstfs: 11291 case Intrinsic::ppc_qpx_qvstfsa: 11292 VT = MVT::v4f32; 11293 break; 11294 case Intrinsic::ppc_qpx_qvstfcd: 11295 case Intrinsic::ppc_qpx_qvstfcda: 11296 VT = MVT::v2f64; 11297 break; 11298 case Intrinsic::ppc_qpx_qvstfcs: 11299 case Intrinsic::ppc_qpx_qvstfcsa: 11300 VT = MVT::v2f32; 11301 break; 11302 case Intrinsic::ppc_qpx_qvstfiw: 11303 case Intrinsic::ppc_qpx_qvstfiwa: 11304 case Intrinsic::ppc_altivec_stvx: 11305 case Intrinsic::ppc_altivec_stvxl: 11306 case Intrinsic::ppc_vsx_stxvw4x: 11307 VT = MVT::v4i32; 11308 break; 11309 case Intrinsic::ppc_vsx_stxvd2x: 11310 VT = MVT::v2f64; 11311 break; 11312 case Intrinsic::ppc_vsx_stxvw4x_be: 11313 VT = MVT::v4i32; 11314 break; 11315 case Intrinsic::ppc_vsx_stxvd2x_be: 11316 VT = MVT::v2f64; 11317 break; 11318 case Intrinsic::ppc_altivec_stvebx: 11319 VT = MVT::i8; 11320 break; 11321 case Intrinsic::ppc_altivec_stvehx: 11322 VT = MVT::i16; 11323 break; 11324 case Intrinsic::ppc_altivec_stvewx: 11325 VT = MVT::i32; 11326 break; 11327 } 11328 11329 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11330 } 11331 11332 return false; 11333 } 11334 11335 // Return true is there is a nearyby consecutive load to the one provided 11336 // (regardless of alignment). We search up and down the chain, looking though 11337 // token factors and other loads (but nothing else). As a result, a true result 11338 // indicates that it is safe to create a new consecutive load adjacent to the 11339 // load provided. 11340 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11341 SDValue Chain = LD->getChain(); 11342 EVT VT = LD->getMemoryVT(); 11343 11344 SmallSet<SDNode *, 16> LoadRoots; 11345 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11346 SmallSet<SDNode *, 16> Visited; 11347 11348 // First, search up the chain, branching to follow all token-factor operands. 11349 // If we find a consecutive load, then we're done, otherwise, record all 11350 // nodes just above the top-level loads and token factors. 11351 while (!Queue.empty()) { 11352 SDNode *ChainNext = Queue.pop_back_val(); 11353 if (!Visited.insert(ChainNext).second) 11354 continue; 11355 11356 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11357 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11358 return true; 11359 11360 if (!Visited.count(ChainLD->getChain().getNode())) 11361 Queue.push_back(ChainLD->getChain().getNode()); 11362 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11363 for (const SDUse &O : ChainNext->ops()) 11364 if (!Visited.count(O.getNode())) 11365 Queue.push_back(O.getNode()); 11366 } else 11367 LoadRoots.insert(ChainNext); 11368 } 11369 11370 // Second, search down the chain, starting from the top-level nodes recorded 11371 // in the first phase. These top-level nodes are the nodes just above all 11372 // loads and token factors. Starting with their uses, recursively look though 11373 // all loads (just the chain uses) and token factors to find a consecutive 11374 // load. 11375 Visited.clear(); 11376 Queue.clear(); 11377 11378 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11379 IE = LoadRoots.end(); I != IE; ++I) { 11380 Queue.push_back(*I); 11381 11382 while (!Queue.empty()) { 11383 SDNode *LoadRoot = Queue.pop_back_val(); 11384 if (!Visited.insert(LoadRoot).second) 11385 continue; 11386 11387 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11388 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11389 return true; 11390 11391 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11392 UE = LoadRoot->use_end(); UI != UE; ++UI) 11393 if (((isa<MemSDNode>(*UI) && 11394 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11395 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11396 Queue.push_back(*UI); 11397 } 11398 } 11399 11400 return false; 11401 } 11402 11403 /// This function is called when we have proved that a SETCC node can be replaced 11404 /// by subtraction (and other supporting instructions) so that the result of 11405 /// comparison is kept in a GPR instead of CR. This function is purely for 11406 /// codegen purposes and has some flags to guide the codegen process. 11407 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11408 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11409 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11410 11411 // Zero extend the operands to the largest legal integer. Originally, they 11412 // must be of a strictly smaller size. 11413 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11414 DAG.getConstant(Size, DL, MVT::i32)); 11415 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11416 DAG.getConstant(Size, DL, MVT::i32)); 11417 11418 // Swap if needed. Depends on the condition code. 11419 if (Swap) 11420 std::swap(Op0, Op1); 11421 11422 // Subtract extended integers. 11423 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11424 11425 // Move the sign bit to the least significant position and zero out the rest. 11426 // Now the least significant bit carries the result of original comparison. 11427 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11428 DAG.getConstant(Size - 1, DL, MVT::i32)); 11429 auto Final = Shifted; 11430 11431 // Complement the result if needed. Based on the condition code. 11432 if (Complement) 11433 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11434 DAG.getConstant(1, DL, MVT::i64)); 11435 11436 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11437 } 11438 11439 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11440 DAGCombinerInfo &DCI) const { 11441 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11442 11443 SelectionDAG &DAG = DCI.DAG; 11444 SDLoc DL(N); 11445 11446 // Size of integers being compared has a critical role in the following 11447 // analysis, so we prefer to do this when all types are legal. 11448 if (!DCI.isAfterLegalizeDAG()) 11449 return SDValue(); 11450 11451 // If all users of SETCC extend its value to a legal integer type 11452 // then we replace SETCC with a subtraction 11453 for (SDNode::use_iterator UI = N->use_begin(), 11454 UE = N->use_end(); UI != UE; ++UI) { 11455 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11456 return SDValue(); 11457 } 11458 11459 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11460 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11461 11462 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11463 11464 if (OpSize < Size) { 11465 switch (CC) { 11466 default: break; 11467 case ISD::SETULT: 11468 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11469 case ISD::SETULE: 11470 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11471 case ISD::SETUGT: 11472 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11473 case ISD::SETUGE: 11474 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11475 } 11476 } 11477 11478 return SDValue(); 11479 } 11480 11481 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11482 DAGCombinerInfo &DCI) const { 11483 SelectionDAG &DAG = DCI.DAG; 11484 SDLoc dl(N); 11485 11486 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11487 // If we're tracking CR bits, we need to be careful that we don't have: 11488 // trunc(binary-ops(zext(x), zext(y))) 11489 // or 11490 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11491 // such that we're unnecessarily moving things into GPRs when it would be 11492 // better to keep them in CR bits. 11493 11494 // Note that trunc here can be an actual i1 trunc, or can be the effective 11495 // truncation that comes from a setcc or select_cc. 11496 if (N->getOpcode() == ISD::TRUNCATE && 11497 N->getValueType(0) != MVT::i1) 11498 return SDValue(); 11499 11500 if (N->getOperand(0).getValueType() != MVT::i32 && 11501 N->getOperand(0).getValueType() != MVT::i64) 11502 return SDValue(); 11503 11504 if (N->getOpcode() == ISD::SETCC || 11505 N->getOpcode() == ISD::SELECT_CC) { 11506 // If we're looking at a comparison, then we need to make sure that the 11507 // high bits (all except for the first) don't matter the result. 11508 ISD::CondCode CC = 11509 cast<CondCodeSDNode>(N->getOperand( 11510 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11511 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11512 11513 if (ISD::isSignedIntSetCC(CC)) { 11514 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11515 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11516 return SDValue(); 11517 } else if (ISD::isUnsignedIntSetCC(CC)) { 11518 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11519 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11520 !DAG.MaskedValueIsZero(N->getOperand(1), 11521 APInt::getHighBitsSet(OpBits, OpBits-1))) 11522 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11523 : SDValue()); 11524 } else { 11525 // This is neither a signed nor an unsigned comparison, just make sure 11526 // that the high bits are equal. 11527 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11528 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11529 11530 // We don't really care about what is known about the first bit (if 11531 // anything), so clear it in all masks prior to comparing them. 11532 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11533 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11534 11535 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11536 return SDValue(); 11537 } 11538 } 11539 11540 // We now know that the higher-order bits are irrelevant, we just need to 11541 // make sure that all of the intermediate operations are bit operations, and 11542 // all inputs are extensions. 11543 if (N->getOperand(0).getOpcode() != ISD::AND && 11544 N->getOperand(0).getOpcode() != ISD::OR && 11545 N->getOperand(0).getOpcode() != ISD::XOR && 11546 N->getOperand(0).getOpcode() != ISD::SELECT && 11547 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11548 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11549 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11550 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11551 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11552 return SDValue(); 11553 11554 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11555 N->getOperand(1).getOpcode() != ISD::AND && 11556 N->getOperand(1).getOpcode() != ISD::OR && 11557 N->getOperand(1).getOpcode() != ISD::XOR && 11558 N->getOperand(1).getOpcode() != ISD::SELECT && 11559 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11560 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11561 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11562 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11563 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11564 return SDValue(); 11565 11566 SmallVector<SDValue, 4> Inputs; 11567 SmallVector<SDValue, 8> BinOps, PromOps; 11568 SmallPtrSet<SDNode *, 16> Visited; 11569 11570 for (unsigned i = 0; i < 2; ++i) { 11571 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11572 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11573 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11574 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11575 isa<ConstantSDNode>(N->getOperand(i))) 11576 Inputs.push_back(N->getOperand(i)); 11577 else 11578 BinOps.push_back(N->getOperand(i)); 11579 11580 if (N->getOpcode() == ISD::TRUNCATE) 11581 break; 11582 } 11583 11584 // Visit all inputs, collect all binary operations (and, or, xor and 11585 // select) that are all fed by extensions. 11586 while (!BinOps.empty()) { 11587 SDValue BinOp = BinOps.back(); 11588 BinOps.pop_back(); 11589 11590 if (!Visited.insert(BinOp.getNode()).second) 11591 continue; 11592 11593 PromOps.push_back(BinOp); 11594 11595 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11596 // The condition of the select is not promoted. 11597 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11598 continue; 11599 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11600 continue; 11601 11602 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11603 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11604 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11605 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11606 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11607 Inputs.push_back(BinOp.getOperand(i)); 11608 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11609 BinOp.getOperand(i).getOpcode() == ISD::OR || 11610 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11611 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11612 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11613 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11614 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11615 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11616 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11617 BinOps.push_back(BinOp.getOperand(i)); 11618 } else { 11619 // We have an input that is not an extension or another binary 11620 // operation; we'll abort this transformation. 11621 return SDValue(); 11622 } 11623 } 11624 } 11625 11626 // Make sure that this is a self-contained cluster of operations (which 11627 // is not quite the same thing as saying that everything has only one 11628 // use). 11629 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11630 if (isa<ConstantSDNode>(Inputs[i])) 11631 continue; 11632 11633 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11634 UE = Inputs[i].getNode()->use_end(); 11635 UI != UE; ++UI) { 11636 SDNode *User = *UI; 11637 if (User != N && !Visited.count(User)) 11638 return SDValue(); 11639 11640 // Make sure that we're not going to promote the non-output-value 11641 // operand(s) or SELECT or SELECT_CC. 11642 // FIXME: Although we could sometimes handle this, and it does occur in 11643 // practice that one of the condition inputs to the select is also one of 11644 // the outputs, we currently can't deal with this. 11645 if (User->getOpcode() == ISD::SELECT) { 11646 if (User->getOperand(0) == Inputs[i]) 11647 return SDValue(); 11648 } else if (User->getOpcode() == ISD::SELECT_CC) { 11649 if (User->getOperand(0) == Inputs[i] || 11650 User->getOperand(1) == Inputs[i]) 11651 return SDValue(); 11652 } 11653 } 11654 } 11655 11656 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11657 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11658 UE = PromOps[i].getNode()->use_end(); 11659 UI != UE; ++UI) { 11660 SDNode *User = *UI; 11661 if (User != N && !Visited.count(User)) 11662 return SDValue(); 11663 11664 // Make sure that we're not going to promote the non-output-value 11665 // operand(s) or SELECT or SELECT_CC. 11666 // FIXME: Although we could sometimes handle this, and it does occur in 11667 // practice that one of the condition inputs to the select is also one of 11668 // the outputs, we currently can't deal with this. 11669 if (User->getOpcode() == ISD::SELECT) { 11670 if (User->getOperand(0) == PromOps[i]) 11671 return SDValue(); 11672 } else if (User->getOpcode() == ISD::SELECT_CC) { 11673 if (User->getOperand(0) == PromOps[i] || 11674 User->getOperand(1) == PromOps[i]) 11675 return SDValue(); 11676 } 11677 } 11678 } 11679 11680 // Replace all inputs with the extension operand. 11681 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11682 // Constants may have users outside the cluster of to-be-promoted nodes, 11683 // and so we need to replace those as we do the promotions. 11684 if (isa<ConstantSDNode>(Inputs[i])) 11685 continue; 11686 else 11687 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11688 } 11689 11690 std::list<HandleSDNode> PromOpHandles; 11691 for (auto &PromOp : PromOps) 11692 PromOpHandles.emplace_back(PromOp); 11693 11694 // Replace all operations (these are all the same, but have a different 11695 // (i1) return type). DAG.getNode will validate that the types of 11696 // a binary operator match, so go through the list in reverse so that 11697 // we've likely promoted both operands first. Any intermediate truncations or 11698 // extensions disappear. 11699 while (!PromOpHandles.empty()) { 11700 SDValue PromOp = PromOpHandles.back().getValue(); 11701 PromOpHandles.pop_back(); 11702 11703 if (PromOp.getOpcode() == ISD::TRUNCATE || 11704 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11705 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11706 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11707 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11708 PromOp.getOperand(0).getValueType() != MVT::i1) { 11709 // The operand is not yet ready (see comment below). 11710 PromOpHandles.emplace_front(PromOp); 11711 continue; 11712 } 11713 11714 SDValue RepValue = PromOp.getOperand(0); 11715 if (isa<ConstantSDNode>(RepValue)) 11716 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11717 11718 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11719 continue; 11720 } 11721 11722 unsigned C; 11723 switch (PromOp.getOpcode()) { 11724 default: C = 0; break; 11725 case ISD::SELECT: C = 1; break; 11726 case ISD::SELECT_CC: C = 2; break; 11727 } 11728 11729 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11730 PromOp.getOperand(C).getValueType() != MVT::i1) || 11731 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11732 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11733 // The to-be-promoted operands of this node have not yet been 11734 // promoted (this should be rare because we're going through the 11735 // list backward, but if one of the operands has several users in 11736 // this cluster of to-be-promoted nodes, it is possible). 11737 PromOpHandles.emplace_front(PromOp); 11738 continue; 11739 } 11740 11741 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11742 PromOp.getNode()->op_end()); 11743 11744 // If there are any constant inputs, make sure they're replaced now. 11745 for (unsigned i = 0; i < 2; ++i) 11746 if (isa<ConstantSDNode>(Ops[C+i])) 11747 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11748 11749 DAG.ReplaceAllUsesOfValueWith(PromOp, 11750 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11751 } 11752 11753 // Now we're left with the initial truncation itself. 11754 if (N->getOpcode() == ISD::TRUNCATE) 11755 return N->getOperand(0); 11756 11757 // Otherwise, this is a comparison. The operands to be compared have just 11758 // changed type (to i1), but everything else is the same. 11759 return SDValue(N, 0); 11760 } 11761 11762 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11763 DAGCombinerInfo &DCI) const { 11764 SelectionDAG &DAG = DCI.DAG; 11765 SDLoc dl(N); 11766 11767 // If we're tracking CR bits, we need to be careful that we don't have: 11768 // zext(binary-ops(trunc(x), trunc(y))) 11769 // or 11770 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11771 // such that we're unnecessarily moving things into CR bits that can more 11772 // efficiently stay in GPRs. Note that if we're not certain that the high 11773 // bits are set as required by the final extension, we still may need to do 11774 // some masking to get the proper behavior. 11775 11776 // This same functionality is important on PPC64 when dealing with 11777 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11778 // the return values of functions. Because it is so similar, it is handled 11779 // here as well. 11780 11781 if (N->getValueType(0) != MVT::i32 && 11782 N->getValueType(0) != MVT::i64) 11783 return SDValue(); 11784 11785 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11786 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11787 return SDValue(); 11788 11789 if (N->getOperand(0).getOpcode() != ISD::AND && 11790 N->getOperand(0).getOpcode() != ISD::OR && 11791 N->getOperand(0).getOpcode() != ISD::XOR && 11792 N->getOperand(0).getOpcode() != ISD::SELECT && 11793 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11794 return SDValue(); 11795 11796 SmallVector<SDValue, 4> Inputs; 11797 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11798 SmallPtrSet<SDNode *, 16> Visited; 11799 11800 // Visit all inputs, collect all binary operations (and, or, xor and 11801 // select) that are all fed by truncations. 11802 while (!BinOps.empty()) { 11803 SDValue BinOp = BinOps.back(); 11804 BinOps.pop_back(); 11805 11806 if (!Visited.insert(BinOp.getNode()).second) 11807 continue; 11808 11809 PromOps.push_back(BinOp); 11810 11811 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11812 // The condition of the select is not promoted. 11813 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11814 continue; 11815 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11816 continue; 11817 11818 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11819 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11820 Inputs.push_back(BinOp.getOperand(i)); 11821 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11822 BinOp.getOperand(i).getOpcode() == ISD::OR || 11823 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11824 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11825 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11826 BinOps.push_back(BinOp.getOperand(i)); 11827 } else { 11828 // We have an input that is not a truncation or another binary 11829 // operation; we'll abort this transformation. 11830 return SDValue(); 11831 } 11832 } 11833 } 11834 11835 // The operands of a select that must be truncated when the select is 11836 // promoted because the operand is actually part of the to-be-promoted set. 11837 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11838 11839 // Make sure that this is a self-contained cluster of operations (which 11840 // is not quite the same thing as saying that everything has only one 11841 // use). 11842 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11843 if (isa<ConstantSDNode>(Inputs[i])) 11844 continue; 11845 11846 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11847 UE = Inputs[i].getNode()->use_end(); 11848 UI != UE; ++UI) { 11849 SDNode *User = *UI; 11850 if (User != N && !Visited.count(User)) 11851 return SDValue(); 11852 11853 // If we're going to promote the non-output-value operand(s) or SELECT or 11854 // SELECT_CC, record them for truncation. 11855 if (User->getOpcode() == ISD::SELECT) { 11856 if (User->getOperand(0) == Inputs[i]) 11857 SelectTruncOp[0].insert(std::make_pair(User, 11858 User->getOperand(0).getValueType())); 11859 } else if (User->getOpcode() == ISD::SELECT_CC) { 11860 if (User->getOperand(0) == Inputs[i]) 11861 SelectTruncOp[0].insert(std::make_pair(User, 11862 User->getOperand(0).getValueType())); 11863 if (User->getOperand(1) == Inputs[i]) 11864 SelectTruncOp[1].insert(std::make_pair(User, 11865 User->getOperand(1).getValueType())); 11866 } 11867 } 11868 } 11869 11870 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11871 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11872 UE = PromOps[i].getNode()->use_end(); 11873 UI != UE; ++UI) { 11874 SDNode *User = *UI; 11875 if (User != N && !Visited.count(User)) 11876 return SDValue(); 11877 11878 // If we're going to promote the non-output-value operand(s) or SELECT or 11879 // SELECT_CC, record them for truncation. 11880 if (User->getOpcode() == ISD::SELECT) { 11881 if (User->getOperand(0) == PromOps[i]) 11882 SelectTruncOp[0].insert(std::make_pair(User, 11883 User->getOperand(0).getValueType())); 11884 } else if (User->getOpcode() == ISD::SELECT_CC) { 11885 if (User->getOperand(0) == PromOps[i]) 11886 SelectTruncOp[0].insert(std::make_pair(User, 11887 User->getOperand(0).getValueType())); 11888 if (User->getOperand(1) == PromOps[i]) 11889 SelectTruncOp[1].insert(std::make_pair(User, 11890 User->getOperand(1).getValueType())); 11891 } 11892 } 11893 } 11894 11895 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11896 bool ReallyNeedsExt = false; 11897 if (N->getOpcode() != ISD::ANY_EXTEND) { 11898 // If all of the inputs are not already sign/zero extended, then 11899 // we'll still need to do that at the end. 11900 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11901 if (isa<ConstantSDNode>(Inputs[i])) 11902 continue; 11903 11904 unsigned OpBits = 11905 Inputs[i].getOperand(0).getValueSizeInBits(); 11906 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11907 11908 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11909 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11910 APInt::getHighBitsSet(OpBits, 11911 OpBits-PromBits))) || 11912 (N->getOpcode() == ISD::SIGN_EXTEND && 11913 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11914 (OpBits-(PromBits-1)))) { 11915 ReallyNeedsExt = true; 11916 break; 11917 } 11918 } 11919 } 11920 11921 // Replace all inputs, either with the truncation operand, or a 11922 // truncation or extension to the final output type. 11923 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11924 // Constant inputs need to be replaced with the to-be-promoted nodes that 11925 // use them because they might have users outside of the cluster of 11926 // promoted nodes. 11927 if (isa<ConstantSDNode>(Inputs[i])) 11928 continue; 11929 11930 SDValue InSrc = Inputs[i].getOperand(0); 11931 if (Inputs[i].getValueType() == N->getValueType(0)) 11932 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11933 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11934 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11935 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11936 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11937 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11938 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11939 else 11940 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11941 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11942 } 11943 11944 std::list<HandleSDNode> PromOpHandles; 11945 for (auto &PromOp : PromOps) 11946 PromOpHandles.emplace_back(PromOp); 11947 11948 // Replace all operations (these are all the same, but have a different 11949 // (promoted) return type). DAG.getNode will validate that the types of 11950 // a binary operator match, so go through the list in reverse so that 11951 // we've likely promoted both operands first. 11952 while (!PromOpHandles.empty()) { 11953 SDValue PromOp = PromOpHandles.back().getValue(); 11954 PromOpHandles.pop_back(); 11955 11956 unsigned C; 11957 switch (PromOp.getOpcode()) { 11958 default: C = 0; break; 11959 case ISD::SELECT: C = 1; break; 11960 case ISD::SELECT_CC: C = 2; break; 11961 } 11962 11963 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11964 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11965 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11966 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11967 // The to-be-promoted operands of this node have not yet been 11968 // promoted (this should be rare because we're going through the 11969 // list backward, but if one of the operands has several users in 11970 // this cluster of to-be-promoted nodes, it is possible). 11971 PromOpHandles.emplace_front(PromOp); 11972 continue; 11973 } 11974 11975 // For SELECT and SELECT_CC nodes, we do a similar check for any 11976 // to-be-promoted comparison inputs. 11977 if (PromOp.getOpcode() == ISD::SELECT || 11978 PromOp.getOpcode() == ISD::SELECT_CC) { 11979 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11980 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11981 (SelectTruncOp[1].count(PromOp.getNode()) && 11982 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11983 PromOpHandles.emplace_front(PromOp); 11984 continue; 11985 } 11986 } 11987 11988 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11989 PromOp.getNode()->op_end()); 11990 11991 // If this node has constant inputs, then they'll need to be promoted here. 11992 for (unsigned i = 0; i < 2; ++i) { 11993 if (!isa<ConstantSDNode>(Ops[C+i])) 11994 continue; 11995 if (Ops[C+i].getValueType() == N->getValueType(0)) 11996 continue; 11997 11998 if (N->getOpcode() == ISD::SIGN_EXTEND) 11999 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12000 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12001 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12002 else 12003 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12004 } 12005 12006 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12007 // truncate them again to the original value type. 12008 if (PromOp.getOpcode() == ISD::SELECT || 12009 PromOp.getOpcode() == ISD::SELECT_CC) { 12010 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12011 if (SI0 != SelectTruncOp[0].end()) 12012 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12013 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12014 if (SI1 != SelectTruncOp[1].end()) 12015 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12016 } 12017 12018 DAG.ReplaceAllUsesOfValueWith(PromOp, 12019 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12020 } 12021 12022 // Now we're left with the initial extension itself. 12023 if (!ReallyNeedsExt) 12024 return N->getOperand(0); 12025 12026 // To zero extend, just mask off everything except for the first bit (in the 12027 // i1 case). 12028 if (N->getOpcode() == ISD::ZERO_EXTEND) 12029 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12030 DAG.getConstant(APInt::getLowBitsSet( 12031 N->getValueSizeInBits(0), PromBits), 12032 dl, N->getValueType(0))); 12033 12034 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12035 "Invalid extension type"); 12036 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12037 SDValue ShiftCst = 12038 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12039 return DAG.getNode( 12040 ISD::SRA, dl, N->getValueType(0), 12041 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12042 ShiftCst); 12043 } 12044 12045 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12046 DAGCombinerInfo &DCI) const { 12047 assert(N->getOpcode() == ISD::SETCC && 12048 "Should be called with a SETCC node"); 12049 12050 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12051 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12052 SDValue LHS = N->getOperand(0); 12053 SDValue RHS = N->getOperand(1); 12054 12055 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12056 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12057 LHS.hasOneUse()) 12058 std::swap(LHS, RHS); 12059 12060 // x == 0-y --> x+y == 0 12061 // x != 0-y --> x+y != 0 12062 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12063 RHS.hasOneUse()) { 12064 SDLoc DL(N); 12065 SelectionDAG &DAG = DCI.DAG; 12066 EVT VT = N->getValueType(0); 12067 EVT OpVT = LHS.getValueType(); 12068 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12069 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12070 } 12071 } 12072 12073 return DAGCombineTruncBoolExt(N, DCI); 12074 } 12075 12076 // Is this an extending load from an f32 to an f64? 12077 static bool isFPExtLoad(SDValue Op) { 12078 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12079 return LD->getExtensionType() == ISD::EXTLOAD && 12080 Op.getValueType() == MVT::f64; 12081 return false; 12082 } 12083 12084 /// Reduces the number of fp-to-int conversion when building a vector. 12085 /// 12086 /// If this vector is built out of floating to integer conversions, 12087 /// transform it to a vector built out of floating point values followed by a 12088 /// single floating to integer conversion of the vector. 12089 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12090 /// becomes (fptosi (build_vector ($A, $B, ...))) 12091 SDValue PPCTargetLowering:: 12092 combineElementTruncationToVectorTruncation(SDNode *N, 12093 DAGCombinerInfo &DCI) const { 12094 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12095 "Should be called with a BUILD_VECTOR node"); 12096 12097 SelectionDAG &DAG = DCI.DAG; 12098 SDLoc dl(N); 12099 12100 SDValue FirstInput = N->getOperand(0); 12101 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12102 "The input operand must be an fp-to-int conversion."); 12103 12104 // This combine happens after legalization so the fp_to_[su]i nodes are 12105 // already converted to PPCSISD nodes. 12106 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12107 if (FirstConversion == PPCISD::FCTIDZ || 12108 FirstConversion == PPCISD::FCTIDUZ || 12109 FirstConversion == PPCISD::FCTIWZ || 12110 FirstConversion == PPCISD::FCTIWUZ) { 12111 bool IsSplat = true; 12112 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12113 FirstConversion == PPCISD::FCTIWUZ; 12114 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12115 SmallVector<SDValue, 4> Ops; 12116 EVT TargetVT = N->getValueType(0); 12117 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12118 SDValue NextOp = N->getOperand(i); 12119 if (NextOp.getOpcode() != PPCISD::MFVSR) 12120 return SDValue(); 12121 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12122 if (NextConversion != FirstConversion) 12123 return SDValue(); 12124 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12125 // This is not valid if the input was originally double precision. It is 12126 // also not profitable to do unless this is an extending load in which 12127 // case doing this combine will allow us to combine consecutive loads. 12128 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12129 return SDValue(); 12130 if (N->getOperand(i) != FirstInput) 12131 IsSplat = false; 12132 } 12133 12134 // If this is a splat, we leave it as-is since there will be only a single 12135 // fp-to-int conversion followed by a splat of the integer. This is better 12136 // for 32-bit and smaller ints and neutral for 64-bit ints. 12137 if (IsSplat) 12138 return SDValue(); 12139 12140 // Now that we know we have the right type of node, get its operands 12141 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12142 SDValue In = N->getOperand(i).getOperand(0); 12143 if (Is32Bit) { 12144 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12145 // here, we know that all inputs are extending loads so this is safe). 12146 if (In.isUndef()) 12147 Ops.push_back(DAG.getUNDEF(SrcVT)); 12148 else { 12149 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12150 MVT::f32, In.getOperand(0), 12151 DAG.getIntPtrConstant(1, dl)); 12152 Ops.push_back(Trunc); 12153 } 12154 } else 12155 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12156 } 12157 12158 unsigned Opcode; 12159 if (FirstConversion == PPCISD::FCTIDZ || 12160 FirstConversion == PPCISD::FCTIWZ) 12161 Opcode = ISD::FP_TO_SINT; 12162 else 12163 Opcode = ISD::FP_TO_UINT; 12164 12165 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12166 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12167 return DAG.getNode(Opcode, dl, TargetVT, BV); 12168 } 12169 return SDValue(); 12170 } 12171 12172 /// Reduce the number of loads when building a vector. 12173 /// 12174 /// Building a vector out of multiple loads can be converted to a load 12175 /// of the vector type if the loads are consecutive. If the loads are 12176 /// consecutive but in descending order, a shuffle is added at the end 12177 /// to reorder the vector. 12178 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12179 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12180 "Should be called with a BUILD_VECTOR node"); 12181 12182 SDLoc dl(N); 12183 bool InputsAreConsecutiveLoads = true; 12184 bool InputsAreReverseConsecutive = true; 12185 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12186 SDValue FirstInput = N->getOperand(0); 12187 bool IsRoundOfExtLoad = false; 12188 12189 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12190 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12191 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12192 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12193 } 12194 // Not a build vector of (possibly fp_rounded) loads. 12195 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12196 N->getNumOperands() == 1) 12197 return SDValue(); 12198 12199 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12200 // If any inputs are fp_round(extload), they all must be. 12201 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12202 return SDValue(); 12203 12204 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12205 N->getOperand(i); 12206 if (NextInput.getOpcode() != ISD::LOAD) 12207 return SDValue(); 12208 12209 SDValue PreviousInput = 12210 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12211 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12212 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12213 12214 // If any inputs are fp_round(extload), they all must be. 12215 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12216 return SDValue(); 12217 12218 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12219 InputsAreConsecutiveLoads = false; 12220 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12221 InputsAreReverseConsecutive = false; 12222 12223 // Exit early if the loads are neither consecutive nor reverse consecutive. 12224 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12225 return SDValue(); 12226 } 12227 12228 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12229 "The loads cannot be both consecutive and reverse consecutive."); 12230 12231 SDValue FirstLoadOp = 12232 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12233 SDValue LastLoadOp = 12234 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12235 N->getOperand(N->getNumOperands()-1); 12236 12237 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12238 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12239 if (InputsAreConsecutiveLoads) { 12240 assert(LD1 && "Input needs to be a LoadSDNode."); 12241 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12242 LD1->getBasePtr(), LD1->getPointerInfo(), 12243 LD1->getAlignment()); 12244 } 12245 if (InputsAreReverseConsecutive) { 12246 assert(LDL && "Input needs to be a LoadSDNode."); 12247 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12248 LDL->getBasePtr(), LDL->getPointerInfo(), 12249 LDL->getAlignment()); 12250 SmallVector<int, 16> Ops; 12251 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12252 Ops.push_back(i); 12253 12254 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12255 DAG.getUNDEF(N->getValueType(0)), Ops); 12256 } 12257 return SDValue(); 12258 } 12259 12260 // This function adds the required vector_shuffle needed to get 12261 // the elements of the vector extract in the correct position 12262 // as specified by the CorrectElems encoding. 12263 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12264 SDValue Input, uint64_t Elems, 12265 uint64_t CorrectElems) { 12266 SDLoc dl(N); 12267 12268 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12269 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12270 12271 // Knowing the element indices being extracted from the original 12272 // vector and the order in which they're being inserted, just put 12273 // them at element indices required for the instruction. 12274 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12275 if (DAG.getDataLayout().isLittleEndian()) 12276 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12277 else 12278 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12279 CorrectElems = CorrectElems >> 8; 12280 Elems = Elems >> 8; 12281 } 12282 12283 SDValue Shuffle = 12284 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12285 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12286 12287 EVT Ty = N->getValueType(0); 12288 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12289 return BV; 12290 } 12291 12292 // Look for build vector patterns where input operands come from sign 12293 // extended vector_extract elements of specific indices. If the correct indices 12294 // aren't used, add a vector shuffle to fix up the indices and create a new 12295 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12296 // during instruction selection. 12297 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12298 // This array encodes the indices that the vector sign extend instructions 12299 // extract from when extending from one type to another for both BE and LE. 12300 // The right nibble of each byte corresponds to the LE incides. 12301 // and the left nibble of each byte corresponds to the BE incides. 12302 // For example: 0x3074B8FC byte->word 12303 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12304 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12305 // For example: 0x000070F8 byte->double word 12306 // For LE: the allowed indices are: 0x0,0x8 12307 // For BE: the allowed indices are: 0x7,0xF 12308 uint64_t TargetElems[] = { 12309 0x3074B8FC, // b->w 12310 0x000070F8, // b->d 12311 0x10325476, // h->w 12312 0x00003074, // h->d 12313 0x00001032, // w->d 12314 }; 12315 12316 uint64_t Elems = 0; 12317 int Index; 12318 SDValue Input; 12319 12320 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12321 if (!Op) 12322 return false; 12323 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12324 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12325 return false; 12326 12327 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12328 // of the right width. 12329 SDValue Extract = Op.getOperand(0); 12330 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12331 Extract = Extract.getOperand(0); 12332 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12333 return false; 12334 12335 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12336 if (!ExtOp) 12337 return false; 12338 12339 Index = ExtOp->getZExtValue(); 12340 if (Input && Input != Extract.getOperand(0)) 12341 return false; 12342 12343 if (!Input) 12344 Input = Extract.getOperand(0); 12345 12346 Elems = Elems << 8; 12347 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12348 Elems |= Index; 12349 12350 return true; 12351 }; 12352 12353 // If the build vector operands aren't sign extended vector extracts, 12354 // of the same input vector, then return. 12355 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12356 if (!isSExtOfVecExtract(N->getOperand(i))) { 12357 return SDValue(); 12358 } 12359 } 12360 12361 // If the vector extract indicies are not correct, add the appropriate 12362 // vector_shuffle. 12363 int TgtElemArrayIdx; 12364 int InputSize = Input.getValueType().getScalarSizeInBits(); 12365 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12366 if (InputSize + OutputSize == 40) 12367 TgtElemArrayIdx = 0; 12368 else if (InputSize + OutputSize == 72) 12369 TgtElemArrayIdx = 1; 12370 else if (InputSize + OutputSize == 48) 12371 TgtElemArrayIdx = 2; 12372 else if (InputSize + OutputSize == 80) 12373 TgtElemArrayIdx = 3; 12374 else if (InputSize + OutputSize == 96) 12375 TgtElemArrayIdx = 4; 12376 else 12377 return SDValue(); 12378 12379 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12380 CorrectElems = DAG.getDataLayout().isLittleEndian() 12381 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12382 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12383 if (Elems != CorrectElems) { 12384 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12385 } 12386 12387 // Regular lowering will catch cases where a shuffle is not needed. 12388 return SDValue(); 12389 } 12390 12391 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12392 DAGCombinerInfo &DCI) const { 12393 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12394 "Should be called with a BUILD_VECTOR node"); 12395 12396 SelectionDAG &DAG = DCI.DAG; 12397 SDLoc dl(N); 12398 12399 if (!Subtarget.hasVSX()) 12400 return SDValue(); 12401 12402 // The target independent DAG combiner will leave a build_vector of 12403 // float-to-int conversions intact. We can generate MUCH better code for 12404 // a float-to-int conversion of a vector of floats. 12405 SDValue FirstInput = N->getOperand(0); 12406 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12407 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12408 if (Reduced) 12409 return Reduced; 12410 } 12411 12412 // If we're building a vector out of consecutive loads, just load that 12413 // vector type. 12414 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12415 if (Reduced) 12416 return Reduced; 12417 12418 // If we're building a vector out of extended elements from another vector 12419 // we have P9 vector integer extend instructions. The code assumes legal 12420 // input types (i.e. it can't handle things like v4i16) so do not run before 12421 // legalization. 12422 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12423 Reduced = combineBVOfVecSExt(N, DAG); 12424 if (Reduced) 12425 return Reduced; 12426 } 12427 12428 12429 if (N->getValueType(0) != MVT::v2f64) 12430 return SDValue(); 12431 12432 // Looking for: 12433 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12434 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12435 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12436 return SDValue(); 12437 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12438 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12439 return SDValue(); 12440 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12441 return SDValue(); 12442 12443 SDValue Ext1 = FirstInput.getOperand(0); 12444 SDValue Ext2 = N->getOperand(1).getOperand(0); 12445 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12446 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12447 return SDValue(); 12448 12449 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12450 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12451 if (!Ext1Op || !Ext2Op) 12452 return SDValue(); 12453 if (Ext1.getValueType() != MVT::i32 || 12454 Ext2.getValueType() != MVT::i32) 12455 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 12456 return SDValue(); 12457 12458 int FirstElem = Ext1Op->getZExtValue(); 12459 int SecondElem = Ext2Op->getZExtValue(); 12460 int SubvecIdx; 12461 if (FirstElem == 0 && SecondElem == 1) 12462 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12463 else if (FirstElem == 2 && SecondElem == 3) 12464 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12465 else 12466 return SDValue(); 12467 12468 SDValue SrcVec = Ext1.getOperand(0); 12469 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12470 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12471 return DAG.getNode(NodeType, dl, MVT::v2f64, 12472 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12473 } 12474 12475 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12476 DAGCombinerInfo &DCI) const { 12477 assert((N->getOpcode() == ISD::SINT_TO_FP || 12478 N->getOpcode() == ISD::UINT_TO_FP) && 12479 "Need an int -> FP conversion node here"); 12480 12481 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12482 return SDValue(); 12483 12484 SelectionDAG &DAG = DCI.DAG; 12485 SDLoc dl(N); 12486 SDValue Op(N, 0); 12487 12488 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12489 // from the hardware. 12490 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12491 return SDValue(); 12492 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12493 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12494 return SDValue(); 12495 12496 SDValue FirstOperand(Op.getOperand(0)); 12497 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12498 (FirstOperand.getValueType() == MVT::i8 || 12499 FirstOperand.getValueType() == MVT::i16); 12500 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12501 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12502 bool DstDouble = Op.getValueType() == MVT::f64; 12503 unsigned ConvOp = Signed ? 12504 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12505 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12506 SDValue WidthConst = 12507 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12508 dl, false); 12509 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12510 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12511 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12512 DAG.getVTList(MVT::f64, MVT::Other), 12513 Ops, MVT::i8, LDN->getMemOperand()); 12514 12515 // For signed conversion, we need to sign-extend the value in the VSR 12516 if (Signed) { 12517 SDValue ExtOps[] = { Ld, WidthConst }; 12518 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12519 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12520 } else 12521 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12522 } 12523 12524 12525 // For i32 intermediate values, unfortunately, the conversion functions 12526 // leave the upper 32 bits of the value are undefined. Within the set of 12527 // scalar instructions, we have no method for zero- or sign-extending the 12528 // value. Thus, we cannot handle i32 intermediate values here. 12529 if (Op.getOperand(0).getValueType() == MVT::i32) 12530 return SDValue(); 12531 12532 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12533 "UINT_TO_FP is supported only with FPCVT"); 12534 12535 // If we have FCFIDS, then use it when converting to single-precision. 12536 // Otherwise, convert to double-precision and then round. 12537 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12538 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12539 : PPCISD::FCFIDS) 12540 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12541 : PPCISD::FCFID); 12542 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12543 ? MVT::f32 12544 : MVT::f64; 12545 12546 // If we're converting from a float, to an int, and back to a float again, 12547 // then we don't need the store/load pair at all. 12548 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12549 Subtarget.hasFPCVT()) || 12550 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12551 SDValue Src = Op.getOperand(0).getOperand(0); 12552 if (Src.getValueType() == MVT::f32) { 12553 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12554 DCI.AddToWorklist(Src.getNode()); 12555 } else if (Src.getValueType() != MVT::f64) { 12556 // Make sure that we don't pick up a ppc_fp128 source value. 12557 return SDValue(); 12558 } 12559 12560 unsigned FCTOp = 12561 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12562 PPCISD::FCTIDUZ; 12563 12564 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12565 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12566 12567 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12568 FP = DAG.getNode(ISD::FP_ROUND, dl, 12569 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12570 DCI.AddToWorklist(FP.getNode()); 12571 } 12572 12573 return FP; 12574 } 12575 12576 return SDValue(); 12577 } 12578 12579 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12580 // builtins) into loads with swaps. 12581 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12582 DAGCombinerInfo &DCI) const { 12583 SelectionDAG &DAG = DCI.DAG; 12584 SDLoc dl(N); 12585 SDValue Chain; 12586 SDValue Base; 12587 MachineMemOperand *MMO; 12588 12589 switch (N->getOpcode()) { 12590 default: 12591 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12592 case ISD::LOAD: { 12593 LoadSDNode *LD = cast<LoadSDNode>(N); 12594 Chain = LD->getChain(); 12595 Base = LD->getBasePtr(); 12596 MMO = LD->getMemOperand(); 12597 // If the MMO suggests this isn't a load of a full vector, leave 12598 // things alone. For a built-in, we have to make the change for 12599 // correctness, so if there is a size problem that will be a bug. 12600 if (MMO->getSize() < 16) 12601 return SDValue(); 12602 break; 12603 } 12604 case ISD::INTRINSIC_W_CHAIN: { 12605 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12606 Chain = Intrin->getChain(); 12607 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12608 // us what we want. Get operand 2 instead. 12609 Base = Intrin->getOperand(2); 12610 MMO = Intrin->getMemOperand(); 12611 break; 12612 } 12613 } 12614 12615 MVT VecTy = N->getValueType(0).getSimpleVT(); 12616 12617 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12618 // aligned and the type is a vector with elements up to 4 bytes 12619 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12620 && VecTy.getScalarSizeInBits() <= 32 ) { 12621 return SDValue(); 12622 } 12623 12624 SDValue LoadOps[] = { Chain, Base }; 12625 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12626 DAG.getVTList(MVT::v2f64, MVT::Other), 12627 LoadOps, MVT::v2f64, MMO); 12628 12629 DCI.AddToWorklist(Load.getNode()); 12630 Chain = Load.getValue(1); 12631 SDValue Swap = DAG.getNode( 12632 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12633 DCI.AddToWorklist(Swap.getNode()); 12634 12635 // Add a bitcast if the resulting load type doesn't match v2f64. 12636 if (VecTy != MVT::v2f64) { 12637 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12638 DCI.AddToWorklist(N.getNode()); 12639 // Package {bitcast value, swap's chain} to match Load's shape. 12640 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12641 N, Swap.getValue(1)); 12642 } 12643 12644 return Swap; 12645 } 12646 12647 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12648 // builtins) into stores with swaps. 12649 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12650 DAGCombinerInfo &DCI) const { 12651 SelectionDAG &DAG = DCI.DAG; 12652 SDLoc dl(N); 12653 SDValue Chain; 12654 SDValue Base; 12655 unsigned SrcOpnd; 12656 MachineMemOperand *MMO; 12657 12658 switch (N->getOpcode()) { 12659 default: 12660 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12661 case ISD::STORE: { 12662 StoreSDNode *ST = cast<StoreSDNode>(N); 12663 Chain = ST->getChain(); 12664 Base = ST->getBasePtr(); 12665 MMO = ST->getMemOperand(); 12666 SrcOpnd = 1; 12667 // If the MMO suggests this isn't a store of a full vector, leave 12668 // things alone. For a built-in, we have to make the change for 12669 // correctness, so if there is a size problem that will be a bug. 12670 if (MMO->getSize() < 16) 12671 return SDValue(); 12672 break; 12673 } 12674 case ISD::INTRINSIC_VOID: { 12675 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12676 Chain = Intrin->getChain(); 12677 // Intrin->getBasePtr() oddly does not get what we want. 12678 Base = Intrin->getOperand(3); 12679 MMO = Intrin->getMemOperand(); 12680 SrcOpnd = 2; 12681 break; 12682 } 12683 } 12684 12685 SDValue Src = N->getOperand(SrcOpnd); 12686 MVT VecTy = Src.getValueType().getSimpleVT(); 12687 12688 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12689 // aligned and the type is a vector with elements up to 4 bytes 12690 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12691 && VecTy.getScalarSizeInBits() <= 32 ) { 12692 return SDValue(); 12693 } 12694 12695 // All stores are done as v2f64 and possible bit cast. 12696 if (VecTy != MVT::v2f64) { 12697 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12698 DCI.AddToWorklist(Src.getNode()); 12699 } 12700 12701 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12702 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12703 DCI.AddToWorklist(Swap.getNode()); 12704 Chain = Swap.getValue(1); 12705 SDValue StoreOps[] = { Chain, Swap, Base }; 12706 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12707 DAG.getVTList(MVT::Other), 12708 StoreOps, VecTy, MMO); 12709 DCI.AddToWorklist(Store.getNode()); 12710 return Store; 12711 } 12712 12713 // Handle DAG combine for STORE (FP_TO_INT F). 12714 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12715 DAGCombinerInfo &DCI) const { 12716 12717 SelectionDAG &DAG = DCI.DAG; 12718 SDLoc dl(N); 12719 unsigned Opcode = N->getOperand(1).getOpcode(); 12720 12721 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12722 && "Not a FP_TO_INT Instruction!"); 12723 12724 SDValue Val = N->getOperand(1).getOperand(0); 12725 EVT Op1VT = N->getOperand(1).getValueType(); 12726 EVT ResVT = Val.getValueType(); 12727 12728 // Floating point types smaller than 32 bits are not legal on Power. 12729 if (ResVT.getScalarSizeInBits() < 32) 12730 return SDValue(); 12731 12732 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12733 bool ValidTypeForStoreFltAsInt = 12734 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12735 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12736 12737 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12738 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12739 return SDValue(); 12740 12741 // Extend f32 values to f64 12742 if (ResVT.getScalarSizeInBits() == 32) { 12743 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12744 DCI.AddToWorklist(Val.getNode()); 12745 } 12746 12747 // Set signed or unsigned conversion opcode. 12748 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12749 PPCISD::FP_TO_SINT_IN_VSR : 12750 PPCISD::FP_TO_UINT_IN_VSR; 12751 12752 Val = DAG.getNode(ConvOpcode, 12753 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12754 DCI.AddToWorklist(Val.getNode()); 12755 12756 // Set number of bytes being converted. 12757 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12758 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12759 DAG.getIntPtrConstant(ByteSize, dl, false), 12760 DAG.getValueType(Op1VT) }; 12761 12762 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12763 DAG.getVTList(MVT::Other), Ops, 12764 cast<StoreSDNode>(N)->getMemoryVT(), 12765 cast<StoreSDNode>(N)->getMemOperand()); 12766 12767 DCI.AddToWorklist(Val.getNode()); 12768 return Val; 12769 } 12770 12771 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12772 DAGCombinerInfo &DCI) const { 12773 SelectionDAG &DAG = DCI.DAG; 12774 SDLoc dl(N); 12775 switch (N->getOpcode()) { 12776 default: break; 12777 case ISD::ADD: 12778 return combineADD(N, DCI); 12779 case ISD::SHL: 12780 return combineSHL(N, DCI); 12781 case ISD::SRA: 12782 return combineSRA(N, DCI); 12783 case ISD::SRL: 12784 return combineSRL(N, DCI); 12785 case ISD::MUL: 12786 return combineMUL(N, DCI); 12787 case PPCISD::SHL: 12788 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12789 return N->getOperand(0); 12790 break; 12791 case PPCISD::SRL: 12792 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12793 return N->getOperand(0); 12794 break; 12795 case PPCISD::SRA: 12796 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12797 if (C->isNullValue() || // 0 >>s V -> 0. 12798 C->isAllOnesValue()) // -1 >>s V -> -1. 12799 return N->getOperand(0); 12800 } 12801 break; 12802 case ISD::SIGN_EXTEND: 12803 case ISD::ZERO_EXTEND: 12804 case ISD::ANY_EXTEND: 12805 return DAGCombineExtBoolTrunc(N, DCI); 12806 case ISD::TRUNCATE: 12807 return combineTRUNCATE(N, DCI); 12808 case ISD::SETCC: 12809 if (SDValue CSCC = combineSetCC(N, DCI)) 12810 return CSCC; 12811 LLVM_FALLTHROUGH; 12812 case ISD::SELECT_CC: 12813 return DAGCombineTruncBoolExt(N, DCI); 12814 case ISD::SINT_TO_FP: 12815 case ISD::UINT_TO_FP: 12816 return combineFPToIntToFP(N, DCI); 12817 case ISD::STORE: { 12818 12819 EVT Op1VT = N->getOperand(1).getValueType(); 12820 unsigned Opcode = N->getOperand(1).getOpcode(); 12821 12822 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12823 SDValue Val= combineStoreFPToInt(N, DCI); 12824 if (Val) 12825 return Val; 12826 } 12827 12828 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12829 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12830 N->getOperand(1).getNode()->hasOneUse() && 12831 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12832 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12833 12834 // STBRX can only handle simple types and it makes no sense to store less 12835 // two bytes in byte-reversed order. 12836 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12837 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 12838 break; 12839 12840 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12841 // Do an any-extend to 32-bits if this is a half-word input. 12842 if (BSwapOp.getValueType() == MVT::i16) 12843 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12844 12845 // If the type of BSWAP operand is wider than stored memory width 12846 // it need to be shifted to the right side before STBRX. 12847 if (Op1VT.bitsGT(mVT)) { 12848 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12849 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12850 DAG.getConstant(Shift, dl, MVT::i32)); 12851 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12852 if (Op1VT == MVT::i64) 12853 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12854 } 12855 12856 SDValue Ops[] = { 12857 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12858 }; 12859 return 12860 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12861 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12862 cast<StoreSDNode>(N)->getMemOperand()); 12863 } 12864 12865 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12866 // So it can increase the chance of CSE constant construction. 12867 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12868 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12869 // Need to sign-extended to 64-bits to handle negative values. 12870 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12871 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12872 MemVT.getSizeInBits()); 12873 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12874 12875 // DAG.getTruncStore() can't be used here because it doesn't accept 12876 // the general (base + offset) addressing mode. 12877 // So we use UpdateNodeOperands and setTruncatingStore instead. 12878 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12879 N->getOperand(3)); 12880 cast<StoreSDNode>(N)->setTruncatingStore(true); 12881 return SDValue(N, 0); 12882 } 12883 12884 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12885 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12886 if (Op1VT.isSimple()) { 12887 MVT StoreVT = Op1VT.getSimpleVT(); 12888 if (Subtarget.needsSwapsForVSXMemOps() && 12889 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12890 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12891 return expandVSXStoreForLE(N, DCI); 12892 } 12893 break; 12894 } 12895 case ISD::LOAD: { 12896 LoadSDNode *LD = cast<LoadSDNode>(N); 12897 EVT VT = LD->getValueType(0); 12898 12899 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12900 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12901 if (VT.isSimple()) { 12902 MVT LoadVT = VT.getSimpleVT(); 12903 if (Subtarget.needsSwapsForVSXMemOps() && 12904 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12905 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12906 return expandVSXLoadForLE(N, DCI); 12907 } 12908 12909 // We sometimes end up with a 64-bit integer load, from which we extract 12910 // two single-precision floating-point numbers. This happens with 12911 // std::complex<float>, and other similar structures, because of the way we 12912 // canonicalize structure copies. However, if we lack direct moves, 12913 // then the final bitcasts from the extracted integer values to the 12914 // floating-point numbers turn into store/load pairs. Even with direct moves, 12915 // just loading the two floating-point numbers is likely better. 12916 auto ReplaceTwoFloatLoad = [&]() { 12917 if (VT != MVT::i64) 12918 return false; 12919 12920 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12921 LD->isVolatile()) 12922 return false; 12923 12924 // We're looking for a sequence like this: 12925 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12926 // t16: i64 = srl t13, Constant:i32<32> 12927 // t17: i32 = truncate t16 12928 // t18: f32 = bitcast t17 12929 // t19: i32 = truncate t13 12930 // t20: f32 = bitcast t19 12931 12932 if (!LD->hasNUsesOfValue(2, 0)) 12933 return false; 12934 12935 auto UI = LD->use_begin(); 12936 while (UI.getUse().getResNo() != 0) ++UI; 12937 SDNode *Trunc = *UI++; 12938 while (UI.getUse().getResNo() != 0) ++UI; 12939 SDNode *RightShift = *UI; 12940 if (Trunc->getOpcode() != ISD::TRUNCATE) 12941 std::swap(Trunc, RightShift); 12942 12943 if (Trunc->getOpcode() != ISD::TRUNCATE || 12944 Trunc->getValueType(0) != MVT::i32 || 12945 !Trunc->hasOneUse()) 12946 return false; 12947 if (RightShift->getOpcode() != ISD::SRL || 12948 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12949 RightShift->getConstantOperandVal(1) != 32 || 12950 !RightShift->hasOneUse()) 12951 return false; 12952 12953 SDNode *Trunc2 = *RightShift->use_begin(); 12954 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12955 Trunc2->getValueType(0) != MVT::i32 || 12956 !Trunc2->hasOneUse()) 12957 return false; 12958 12959 SDNode *Bitcast = *Trunc->use_begin(); 12960 SDNode *Bitcast2 = *Trunc2->use_begin(); 12961 12962 if (Bitcast->getOpcode() != ISD::BITCAST || 12963 Bitcast->getValueType(0) != MVT::f32) 12964 return false; 12965 if (Bitcast2->getOpcode() != ISD::BITCAST || 12966 Bitcast2->getValueType(0) != MVT::f32) 12967 return false; 12968 12969 if (Subtarget.isLittleEndian()) 12970 std::swap(Bitcast, Bitcast2); 12971 12972 // Bitcast has the second float (in memory-layout order) and Bitcast2 12973 // has the first one. 12974 12975 SDValue BasePtr = LD->getBasePtr(); 12976 if (LD->isIndexed()) { 12977 assert(LD->getAddressingMode() == ISD::PRE_INC && 12978 "Non-pre-inc AM on PPC?"); 12979 BasePtr = 12980 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12981 LD->getOffset()); 12982 } 12983 12984 auto MMOFlags = 12985 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12986 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12987 LD->getPointerInfo(), LD->getAlignment(), 12988 MMOFlags, LD->getAAInfo()); 12989 SDValue AddPtr = 12990 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12991 BasePtr, DAG.getIntPtrConstant(4, dl)); 12992 SDValue FloatLoad2 = DAG.getLoad( 12993 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12994 LD->getPointerInfo().getWithOffset(4), 12995 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12996 12997 if (LD->isIndexed()) { 12998 // Note that DAGCombine should re-form any pre-increment load(s) from 12999 // what is produced here if that makes sense. 13000 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13001 } 13002 13003 DCI.CombineTo(Bitcast2, FloatLoad); 13004 DCI.CombineTo(Bitcast, FloatLoad2); 13005 13006 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13007 SDValue(FloatLoad2.getNode(), 1)); 13008 return true; 13009 }; 13010 13011 if (ReplaceTwoFloatLoad()) 13012 return SDValue(N, 0); 13013 13014 EVT MemVT = LD->getMemoryVT(); 13015 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13016 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13017 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13018 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13019 if (LD->isUnindexed() && VT.isVector() && 13020 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13021 // P8 and later hardware should just use LOAD. 13022 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13023 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13024 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13025 LD->getAlignment() >= ScalarABIAlignment)) && 13026 LD->getAlignment() < ABIAlignment) { 13027 // This is a type-legal unaligned Altivec or QPX load. 13028 SDValue Chain = LD->getChain(); 13029 SDValue Ptr = LD->getBasePtr(); 13030 bool isLittleEndian = Subtarget.isLittleEndian(); 13031 13032 // This implements the loading of unaligned vectors as described in 13033 // the venerable Apple Velocity Engine overview. Specifically: 13034 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13035 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13036 // 13037 // The general idea is to expand a sequence of one or more unaligned 13038 // loads into an alignment-based permutation-control instruction (lvsl 13039 // or lvsr), a series of regular vector loads (which always truncate 13040 // their input address to an aligned address), and a series of 13041 // permutations. The results of these permutations are the requested 13042 // loaded values. The trick is that the last "extra" load is not taken 13043 // from the address you might suspect (sizeof(vector) bytes after the 13044 // last requested load), but rather sizeof(vector) - 1 bytes after the 13045 // last requested vector. The point of this is to avoid a page fault if 13046 // the base address happened to be aligned. This works because if the 13047 // base address is aligned, then adding less than a full vector length 13048 // will cause the last vector in the sequence to be (re)loaded. 13049 // Otherwise, the next vector will be fetched as you might suspect was 13050 // necessary. 13051 13052 // We might be able to reuse the permutation generation from 13053 // a different base address offset from this one by an aligned amount. 13054 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13055 // optimization later. 13056 Intrinsic::ID Intr, IntrLD, IntrPerm; 13057 MVT PermCntlTy, PermTy, LDTy; 13058 if (Subtarget.hasAltivec()) { 13059 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13060 Intrinsic::ppc_altivec_lvsl; 13061 IntrLD = Intrinsic::ppc_altivec_lvx; 13062 IntrPerm = Intrinsic::ppc_altivec_vperm; 13063 PermCntlTy = MVT::v16i8; 13064 PermTy = MVT::v4i32; 13065 LDTy = MVT::v4i32; 13066 } else { 13067 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13068 Intrinsic::ppc_qpx_qvlpcls; 13069 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13070 Intrinsic::ppc_qpx_qvlfs; 13071 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13072 PermCntlTy = MVT::v4f64; 13073 PermTy = MVT::v4f64; 13074 LDTy = MemVT.getSimpleVT(); 13075 } 13076 13077 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13078 13079 // Create the new MMO for the new base load. It is like the original MMO, 13080 // but represents an area in memory almost twice the vector size centered 13081 // on the original address. If the address is unaligned, we might start 13082 // reading up to (sizeof(vector)-1) bytes below the address of the 13083 // original unaligned load. 13084 MachineFunction &MF = DAG.getMachineFunction(); 13085 MachineMemOperand *BaseMMO = 13086 MF.getMachineMemOperand(LD->getMemOperand(), 13087 -(long)MemVT.getStoreSize()+1, 13088 2*MemVT.getStoreSize()-1); 13089 13090 // Create the new base load. 13091 SDValue LDXIntID = 13092 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13093 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13094 SDValue BaseLoad = 13095 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13096 DAG.getVTList(PermTy, MVT::Other), 13097 BaseLoadOps, LDTy, BaseMMO); 13098 13099 // Note that the value of IncOffset (which is provided to the next 13100 // load's pointer info offset value, and thus used to calculate the 13101 // alignment), and the value of IncValue (which is actually used to 13102 // increment the pointer value) are different! This is because we 13103 // require the next load to appear to be aligned, even though it 13104 // is actually offset from the base pointer by a lesser amount. 13105 int IncOffset = VT.getSizeInBits() / 8; 13106 int IncValue = IncOffset; 13107 13108 // Walk (both up and down) the chain looking for another load at the real 13109 // (aligned) offset (the alignment of the other load does not matter in 13110 // this case). If found, then do not use the offset reduction trick, as 13111 // that will prevent the loads from being later combined (as they would 13112 // otherwise be duplicates). 13113 if (!findConsecutiveLoad(LD, DAG)) 13114 --IncValue; 13115 13116 SDValue Increment = 13117 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13118 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13119 13120 MachineMemOperand *ExtraMMO = 13121 MF.getMachineMemOperand(LD->getMemOperand(), 13122 1, 2*MemVT.getStoreSize()-1); 13123 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13124 SDValue ExtraLoad = 13125 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13126 DAG.getVTList(PermTy, MVT::Other), 13127 ExtraLoadOps, LDTy, ExtraMMO); 13128 13129 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13130 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13131 13132 // Because vperm has a big-endian bias, we must reverse the order 13133 // of the input vectors and complement the permute control vector 13134 // when generating little endian code. We have already handled the 13135 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13136 // and ExtraLoad here. 13137 SDValue Perm; 13138 if (isLittleEndian) 13139 Perm = BuildIntrinsicOp(IntrPerm, 13140 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13141 else 13142 Perm = BuildIntrinsicOp(IntrPerm, 13143 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13144 13145 if (VT != PermTy) 13146 Perm = Subtarget.hasAltivec() ? 13147 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13148 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13149 DAG.getTargetConstant(1, dl, MVT::i64)); 13150 // second argument is 1 because this rounding 13151 // is always exact. 13152 13153 // The output of the permutation is our loaded result, the TokenFactor is 13154 // our new chain. 13155 DCI.CombineTo(N, Perm, TF); 13156 return SDValue(N, 0); 13157 } 13158 } 13159 break; 13160 case ISD::INTRINSIC_WO_CHAIN: { 13161 bool isLittleEndian = Subtarget.isLittleEndian(); 13162 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13163 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13164 : Intrinsic::ppc_altivec_lvsl); 13165 if ((IID == Intr || 13166 IID == Intrinsic::ppc_qpx_qvlpcld || 13167 IID == Intrinsic::ppc_qpx_qvlpcls) && 13168 N->getOperand(1)->getOpcode() == ISD::ADD) { 13169 SDValue Add = N->getOperand(1); 13170 13171 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13172 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13173 13174 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13175 APInt::getAllOnesValue(Bits /* alignment */) 13176 .zext(Add.getScalarValueSizeInBits()))) { 13177 SDNode *BasePtr = Add->getOperand(0).getNode(); 13178 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13179 UE = BasePtr->use_end(); 13180 UI != UE; ++UI) { 13181 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13182 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13183 // We've found another LVSL/LVSR, and this address is an aligned 13184 // multiple of that one. The results will be the same, so use the 13185 // one we've just found instead. 13186 13187 return SDValue(*UI, 0); 13188 } 13189 } 13190 } 13191 13192 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13193 SDNode *BasePtr = Add->getOperand(0).getNode(); 13194 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13195 UE = BasePtr->use_end(); UI != UE; ++UI) { 13196 if (UI->getOpcode() == ISD::ADD && 13197 isa<ConstantSDNode>(UI->getOperand(1)) && 13198 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13199 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13200 (1ULL << Bits) == 0) { 13201 SDNode *OtherAdd = *UI; 13202 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13203 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13204 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13205 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13206 return SDValue(*VI, 0); 13207 } 13208 } 13209 } 13210 } 13211 } 13212 } 13213 13214 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13215 // Expose the vabsduw/h/b opportunity for down stream 13216 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13217 (IID == Intrinsic::ppc_altivec_vmaxsw || 13218 IID == Intrinsic::ppc_altivec_vmaxsh || 13219 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13220 SDValue V1 = N->getOperand(1); 13221 SDValue V2 = N->getOperand(2); 13222 if ((V1.getSimpleValueType() == MVT::v4i32 || 13223 V1.getSimpleValueType() == MVT::v8i16 || 13224 V1.getSimpleValueType() == MVT::v16i8) && 13225 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13226 // (0-a, a) 13227 if (V1.getOpcode() == ISD::SUB && 13228 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13229 V1.getOperand(1) == V2) { 13230 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13231 } 13232 // (a, 0-a) 13233 if (V2.getOpcode() == ISD::SUB && 13234 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13235 V2.getOperand(1) == V1) { 13236 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13237 } 13238 // (x-y, y-x) 13239 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13240 V1.getOperand(0) == V2.getOperand(1) && 13241 V1.getOperand(1) == V2.getOperand(0)) { 13242 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13243 } 13244 } 13245 } 13246 } 13247 13248 break; 13249 case ISD::INTRINSIC_W_CHAIN: 13250 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13251 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13252 if (Subtarget.needsSwapsForVSXMemOps()) { 13253 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13254 default: 13255 break; 13256 case Intrinsic::ppc_vsx_lxvw4x: 13257 case Intrinsic::ppc_vsx_lxvd2x: 13258 return expandVSXLoadForLE(N, DCI); 13259 } 13260 } 13261 break; 13262 case ISD::INTRINSIC_VOID: 13263 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13264 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13265 if (Subtarget.needsSwapsForVSXMemOps()) { 13266 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13267 default: 13268 break; 13269 case Intrinsic::ppc_vsx_stxvw4x: 13270 case Intrinsic::ppc_vsx_stxvd2x: 13271 return expandVSXStoreForLE(N, DCI); 13272 } 13273 } 13274 break; 13275 case ISD::BSWAP: 13276 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13277 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13278 N->getOperand(0).hasOneUse() && 13279 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13280 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13281 N->getValueType(0) == MVT::i64))) { 13282 SDValue Load = N->getOperand(0); 13283 LoadSDNode *LD = cast<LoadSDNode>(Load); 13284 // Create the byte-swapping load. 13285 SDValue Ops[] = { 13286 LD->getChain(), // Chain 13287 LD->getBasePtr(), // Ptr 13288 DAG.getValueType(N->getValueType(0)) // VT 13289 }; 13290 SDValue BSLoad = 13291 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13292 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13293 MVT::i64 : MVT::i32, MVT::Other), 13294 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13295 13296 // If this is an i16 load, insert the truncate. 13297 SDValue ResVal = BSLoad; 13298 if (N->getValueType(0) == MVT::i16) 13299 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13300 13301 // First, combine the bswap away. This makes the value produced by the 13302 // load dead. 13303 DCI.CombineTo(N, ResVal); 13304 13305 // Next, combine the load away, we give it a bogus result value but a real 13306 // chain result. The result value is dead because the bswap is dead. 13307 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13308 13309 // Return N so it doesn't get rechecked! 13310 return SDValue(N, 0); 13311 } 13312 break; 13313 case PPCISD::VCMP: 13314 // If a VCMPo node already exists with exactly the same operands as this 13315 // node, use its result instead of this node (VCMPo computes both a CR6 and 13316 // a normal output). 13317 // 13318 if (!N->getOperand(0).hasOneUse() && 13319 !N->getOperand(1).hasOneUse() && 13320 !N->getOperand(2).hasOneUse()) { 13321 13322 // Scan all of the users of the LHS, looking for VCMPo's that match. 13323 SDNode *VCMPoNode = nullptr; 13324 13325 SDNode *LHSN = N->getOperand(0).getNode(); 13326 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13327 UI != E; ++UI) 13328 if (UI->getOpcode() == PPCISD::VCMPo && 13329 UI->getOperand(1) == N->getOperand(1) && 13330 UI->getOperand(2) == N->getOperand(2) && 13331 UI->getOperand(0) == N->getOperand(0)) { 13332 VCMPoNode = *UI; 13333 break; 13334 } 13335 13336 // If there is no VCMPo node, or if the flag value has a single use, don't 13337 // transform this. 13338 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13339 break; 13340 13341 // Look at the (necessarily single) use of the flag value. If it has a 13342 // chain, this transformation is more complex. Note that multiple things 13343 // could use the value result, which we should ignore. 13344 SDNode *FlagUser = nullptr; 13345 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13346 FlagUser == nullptr; ++UI) { 13347 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13348 SDNode *User = *UI; 13349 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13350 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13351 FlagUser = User; 13352 break; 13353 } 13354 } 13355 } 13356 13357 // If the user is a MFOCRF instruction, we know this is safe. 13358 // Otherwise we give up for right now. 13359 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13360 return SDValue(VCMPoNode, 0); 13361 } 13362 break; 13363 case ISD::BRCOND: { 13364 SDValue Cond = N->getOperand(1); 13365 SDValue Target = N->getOperand(2); 13366 13367 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13368 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13369 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13370 13371 // We now need to make the intrinsic dead (it cannot be instruction 13372 // selected). 13373 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13374 assert(Cond.getNode()->hasOneUse() && 13375 "Counter decrement has more than one use"); 13376 13377 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13378 N->getOperand(0), Target); 13379 } 13380 } 13381 break; 13382 case ISD::BR_CC: { 13383 // If this is a branch on an altivec predicate comparison, lower this so 13384 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13385 // lowering is done pre-legalize, because the legalizer lowers the predicate 13386 // compare down to code that is difficult to reassemble. 13387 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13388 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13389 13390 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13391 // value. If so, pass-through the AND to get to the intrinsic. 13392 if (LHS.getOpcode() == ISD::AND && 13393 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13394 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13395 Intrinsic::ppc_is_decremented_ctr_nonzero && 13396 isa<ConstantSDNode>(LHS.getOperand(1)) && 13397 !isNullConstant(LHS.getOperand(1))) 13398 LHS = LHS.getOperand(0); 13399 13400 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13401 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13402 Intrinsic::ppc_is_decremented_ctr_nonzero && 13403 isa<ConstantSDNode>(RHS)) { 13404 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13405 "Counter decrement comparison is not EQ or NE"); 13406 13407 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13408 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13409 (CC == ISD::SETNE && !Val); 13410 13411 // We now need to make the intrinsic dead (it cannot be instruction 13412 // selected). 13413 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13414 assert(LHS.getNode()->hasOneUse() && 13415 "Counter decrement has more than one use"); 13416 13417 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13418 N->getOperand(0), N->getOperand(4)); 13419 } 13420 13421 int CompareOpc; 13422 bool isDot; 13423 13424 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13425 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13426 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13427 assert(isDot && "Can't compare against a vector result!"); 13428 13429 // If this is a comparison against something other than 0/1, then we know 13430 // that the condition is never/always true. 13431 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13432 if (Val != 0 && Val != 1) { 13433 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13434 return N->getOperand(0); 13435 // Always !=, turn it into an unconditional branch. 13436 return DAG.getNode(ISD::BR, dl, MVT::Other, 13437 N->getOperand(0), N->getOperand(4)); 13438 } 13439 13440 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13441 13442 // Create the PPCISD altivec 'dot' comparison node. 13443 SDValue Ops[] = { 13444 LHS.getOperand(2), // LHS of compare 13445 LHS.getOperand(3), // RHS of compare 13446 DAG.getConstant(CompareOpc, dl, MVT::i32) 13447 }; 13448 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13449 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13450 13451 // Unpack the result based on how the target uses it. 13452 PPC::Predicate CompOpc; 13453 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13454 default: // Can't happen, don't crash on invalid number though. 13455 case 0: // Branch on the value of the EQ bit of CR6. 13456 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13457 break; 13458 case 1: // Branch on the inverted value of the EQ bit of CR6. 13459 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13460 break; 13461 case 2: // Branch on the value of the LT bit of CR6. 13462 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13463 break; 13464 case 3: // Branch on the inverted value of the LT bit of CR6. 13465 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13466 break; 13467 } 13468 13469 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13470 DAG.getConstant(CompOpc, dl, MVT::i32), 13471 DAG.getRegister(PPC::CR6, MVT::i32), 13472 N->getOperand(4), CompNode.getValue(1)); 13473 } 13474 break; 13475 } 13476 case ISD::BUILD_VECTOR: 13477 return DAGCombineBuildVector(N, DCI); 13478 case ISD::ABS: 13479 return combineABS(N, DCI); 13480 case ISD::VSELECT: 13481 return combineVSelect(N, DCI); 13482 } 13483 13484 return SDValue(); 13485 } 13486 13487 SDValue 13488 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13489 SelectionDAG &DAG, 13490 SmallVectorImpl<SDNode *> &Created) const { 13491 // fold (sdiv X, pow2) 13492 EVT VT = N->getValueType(0); 13493 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13494 return SDValue(); 13495 if ((VT != MVT::i32 && VT != MVT::i64) || 13496 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13497 return SDValue(); 13498 13499 SDLoc DL(N); 13500 SDValue N0 = N->getOperand(0); 13501 13502 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13503 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13504 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13505 13506 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13507 Created.push_back(Op.getNode()); 13508 13509 if (IsNegPow2) { 13510 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13511 Created.push_back(Op.getNode()); 13512 } 13513 13514 return Op; 13515 } 13516 13517 //===----------------------------------------------------------------------===// 13518 // Inline Assembly Support 13519 //===----------------------------------------------------------------------===// 13520 13521 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13522 KnownBits &Known, 13523 const APInt &DemandedElts, 13524 const SelectionDAG &DAG, 13525 unsigned Depth) const { 13526 Known.resetAll(); 13527 switch (Op.getOpcode()) { 13528 default: break; 13529 case PPCISD::LBRX: { 13530 // lhbrx is known to have the top bits cleared out. 13531 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13532 Known.Zero = 0xFFFF0000; 13533 break; 13534 } 13535 case ISD::INTRINSIC_WO_CHAIN: { 13536 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13537 default: break; 13538 case Intrinsic::ppc_altivec_vcmpbfp_p: 13539 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13540 case Intrinsic::ppc_altivec_vcmpequb_p: 13541 case Intrinsic::ppc_altivec_vcmpequh_p: 13542 case Intrinsic::ppc_altivec_vcmpequw_p: 13543 case Intrinsic::ppc_altivec_vcmpequd_p: 13544 case Intrinsic::ppc_altivec_vcmpgefp_p: 13545 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13546 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13547 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13548 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13549 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13550 case Intrinsic::ppc_altivec_vcmpgtub_p: 13551 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13552 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13553 case Intrinsic::ppc_altivec_vcmpgtud_p: 13554 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13555 break; 13556 } 13557 } 13558 } 13559 } 13560 13561 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13562 switch (Subtarget.getDarwinDirective()) { 13563 default: break; 13564 case PPC::DIR_970: 13565 case PPC::DIR_PWR4: 13566 case PPC::DIR_PWR5: 13567 case PPC::DIR_PWR5X: 13568 case PPC::DIR_PWR6: 13569 case PPC::DIR_PWR6X: 13570 case PPC::DIR_PWR7: 13571 case PPC::DIR_PWR8: 13572 case PPC::DIR_PWR9: { 13573 if (!ML) 13574 break; 13575 13576 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13577 13578 // For small loops (between 5 and 8 instructions), align to a 32-byte 13579 // boundary so that the entire loop fits in one instruction-cache line. 13580 uint64_t LoopSize = 0; 13581 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13582 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13583 LoopSize += TII->getInstSizeInBytes(*J); 13584 if (LoopSize > 32) 13585 break; 13586 } 13587 13588 if (LoopSize > 16 && LoopSize <= 32) 13589 return 5; 13590 13591 break; 13592 } 13593 } 13594 13595 return TargetLowering::getPrefLoopAlignment(ML); 13596 } 13597 13598 /// getConstraintType - Given a constraint, return the type of 13599 /// constraint it is for this target. 13600 PPCTargetLowering::ConstraintType 13601 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13602 if (Constraint.size() == 1) { 13603 switch (Constraint[0]) { 13604 default: break; 13605 case 'b': 13606 case 'r': 13607 case 'f': 13608 case 'd': 13609 case 'v': 13610 case 'y': 13611 return C_RegisterClass; 13612 case 'Z': 13613 // FIXME: While Z does indicate a memory constraint, it specifically 13614 // indicates an r+r address (used in conjunction with the 'y' modifier 13615 // in the replacement string). Currently, we're forcing the base 13616 // register to be r0 in the asm printer (which is interpreted as zero) 13617 // and forming the complete address in the second register. This is 13618 // suboptimal. 13619 return C_Memory; 13620 } 13621 } else if (Constraint == "wc") { // individual CR bits. 13622 return C_RegisterClass; 13623 } else if (Constraint == "wa" || Constraint == "wd" || 13624 Constraint == "wf" || Constraint == "ws" || 13625 Constraint == "wi") { 13626 return C_RegisterClass; // VSX registers. 13627 } 13628 return TargetLowering::getConstraintType(Constraint); 13629 } 13630 13631 /// Examine constraint type and operand type and determine a weight value. 13632 /// This object must already have been set up with the operand type 13633 /// and the current alternative constraint selected. 13634 TargetLowering::ConstraintWeight 13635 PPCTargetLowering::getSingleConstraintMatchWeight( 13636 AsmOperandInfo &info, const char *constraint) const { 13637 ConstraintWeight weight = CW_Invalid; 13638 Value *CallOperandVal = info.CallOperandVal; 13639 // If we don't have a value, we can't do a match, 13640 // but allow it at the lowest weight. 13641 if (!CallOperandVal) 13642 return CW_Default; 13643 Type *type = CallOperandVal->getType(); 13644 13645 // Look at the constraint type. 13646 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13647 return CW_Register; // an individual CR bit. 13648 else if ((StringRef(constraint) == "wa" || 13649 StringRef(constraint) == "wd" || 13650 StringRef(constraint) == "wf") && 13651 type->isVectorTy()) 13652 return CW_Register; 13653 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13654 return CW_Register; 13655 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13656 return CW_Register; // just hold 64-bit integers data. 13657 13658 switch (*constraint) { 13659 default: 13660 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13661 break; 13662 case 'b': 13663 if (type->isIntegerTy()) 13664 weight = CW_Register; 13665 break; 13666 case 'f': 13667 if (type->isFloatTy()) 13668 weight = CW_Register; 13669 break; 13670 case 'd': 13671 if (type->isDoubleTy()) 13672 weight = CW_Register; 13673 break; 13674 case 'v': 13675 if (type->isVectorTy()) 13676 weight = CW_Register; 13677 break; 13678 case 'y': 13679 weight = CW_Register; 13680 break; 13681 case 'Z': 13682 weight = CW_Memory; 13683 break; 13684 } 13685 return weight; 13686 } 13687 13688 std::pair<unsigned, const TargetRegisterClass *> 13689 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13690 StringRef Constraint, 13691 MVT VT) const { 13692 if (Constraint.size() == 1) { 13693 // GCC RS6000 Constraint Letters 13694 switch (Constraint[0]) { 13695 case 'b': // R1-R31 13696 if (VT == MVT::i64 && Subtarget.isPPC64()) 13697 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13698 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13699 case 'r': // R0-R31 13700 if (VT == MVT::i64 && Subtarget.isPPC64()) 13701 return std::make_pair(0U, &PPC::G8RCRegClass); 13702 return std::make_pair(0U, &PPC::GPRCRegClass); 13703 // 'd' and 'f' constraints are both defined to be "the floating point 13704 // registers", where one is for 32-bit and the other for 64-bit. We don't 13705 // really care overly much here so just give them all the same reg classes. 13706 case 'd': 13707 case 'f': 13708 if (Subtarget.hasSPE()) { 13709 if (VT == MVT::f32 || VT == MVT::i32) 13710 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13711 if (VT == MVT::f64 || VT == MVT::i64) 13712 return std::make_pair(0U, &PPC::SPERCRegClass); 13713 } else { 13714 if (VT == MVT::f32 || VT == MVT::i32) 13715 return std::make_pair(0U, &PPC::F4RCRegClass); 13716 if (VT == MVT::f64 || VT == MVT::i64) 13717 return std::make_pair(0U, &PPC::F8RCRegClass); 13718 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13719 return std::make_pair(0U, &PPC::QFRCRegClass); 13720 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13721 return std::make_pair(0U, &PPC::QSRCRegClass); 13722 } 13723 break; 13724 case 'v': 13725 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13726 return std::make_pair(0U, &PPC::QFRCRegClass); 13727 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13728 return std::make_pair(0U, &PPC::QSRCRegClass); 13729 if (Subtarget.hasAltivec()) 13730 return std::make_pair(0U, &PPC::VRRCRegClass); 13731 break; 13732 case 'y': // crrc 13733 return std::make_pair(0U, &PPC::CRRCRegClass); 13734 } 13735 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13736 // An individual CR bit. 13737 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13738 } else if ((Constraint == "wa" || Constraint == "wd" || 13739 Constraint == "wf" || Constraint == "wi") && 13740 Subtarget.hasVSX()) { 13741 return std::make_pair(0U, &PPC::VSRCRegClass); 13742 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13743 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13744 return std::make_pair(0U, &PPC::VSSRCRegClass); 13745 else 13746 return std::make_pair(0U, &PPC::VSFRCRegClass); 13747 } 13748 13749 std::pair<unsigned, const TargetRegisterClass *> R = 13750 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13751 13752 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13753 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13754 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13755 // register. 13756 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13757 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13758 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13759 PPC::GPRCRegClass.contains(R.first)) 13760 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13761 PPC::sub_32, &PPC::G8RCRegClass), 13762 &PPC::G8RCRegClass); 13763 13764 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13765 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13766 R.first = PPC::CR0; 13767 R.second = &PPC::CRRCRegClass; 13768 } 13769 13770 return R; 13771 } 13772 13773 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13774 /// vector. If it is invalid, don't add anything to Ops. 13775 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13776 std::string &Constraint, 13777 std::vector<SDValue>&Ops, 13778 SelectionDAG &DAG) const { 13779 SDValue Result; 13780 13781 // Only support length 1 constraints. 13782 if (Constraint.length() > 1) return; 13783 13784 char Letter = Constraint[0]; 13785 switch (Letter) { 13786 default: break; 13787 case 'I': 13788 case 'J': 13789 case 'K': 13790 case 'L': 13791 case 'M': 13792 case 'N': 13793 case 'O': 13794 case 'P': { 13795 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13796 if (!CST) return; // Must be an immediate to match. 13797 SDLoc dl(Op); 13798 int64_t Value = CST->getSExtValue(); 13799 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13800 // numbers are printed as such. 13801 switch (Letter) { 13802 default: llvm_unreachable("Unknown constraint letter!"); 13803 case 'I': // "I" is a signed 16-bit constant. 13804 if (isInt<16>(Value)) 13805 Result = DAG.getTargetConstant(Value, dl, TCVT); 13806 break; 13807 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13808 if (isShiftedUInt<16, 16>(Value)) 13809 Result = DAG.getTargetConstant(Value, dl, TCVT); 13810 break; 13811 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13812 if (isShiftedInt<16, 16>(Value)) 13813 Result = DAG.getTargetConstant(Value, dl, TCVT); 13814 break; 13815 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13816 if (isUInt<16>(Value)) 13817 Result = DAG.getTargetConstant(Value, dl, TCVT); 13818 break; 13819 case 'M': // "M" is a constant that is greater than 31. 13820 if (Value > 31) 13821 Result = DAG.getTargetConstant(Value, dl, TCVT); 13822 break; 13823 case 'N': // "N" is a positive constant that is an exact power of two. 13824 if (Value > 0 && isPowerOf2_64(Value)) 13825 Result = DAG.getTargetConstant(Value, dl, TCVT); 13826 break; 13827 case 'O': // "O" is the constant zero. 13828 if (Value == 0) 13829 Result = DAG.getTargetConstant(Value, dl, TCVT); 13830 break; 13831 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13832 if (isInt<16>(-Value)) 13833 Result = DAG.getTargetConstant(Value, dl, TCVT); 13834 break; 13835 } 13836 break; 13837 } 13838 } 13839 13840 if (Result.getNode()) { 13841 Ops.push_back(Result); 13842 return; 13843 } 13844 13845 // Handle standard constraint letters. 13846 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13847 } 13848 13849 // isLegalAddressingMode - Return true if the addressing mode represented 13850 // by AM is legal for this target, for a load/store of the specified type. 13851 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13852 const AddrMode &AM, Type *Ty, 13853 unsigned AS, Instruction *I) const { 13854 // PPC does not allow r+i addressing modes for vectors! 13855 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13856 return false; 13857 13858 // PPC allows a sign-extended 16-bit immediate field. 13859 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13860 return false; 13861 13862 // No global is ever allowed as a base. 13863 if (AM.BaseGV) 13864 return false; 13865 13866 // PPC only support r+r, 13867 switch (AM.Scale) { 13868 case 0: // "r+i" or just "i", depending on HasBaseReg. 13869 break; 13870 case 1: 13871 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13872 return false; 13873 // Otherwise we have r+r or r+i. 13874 break; 13875 case 2: 13876 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13877 return false; 13878 // Allow 2*r as r+r. 13879 break; 13880 default: 13881 // No other scales are supported. 13882 return false; 13883 } 13884 13885 return true; 13886 } 13887 13888 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13889 SelectionDAG &DAG) const { 13890 MachineFunction &MF = DAG.getMachineFunction(); 13891 MachineFrameInfo &MFI = MF.getFrameInfo(); 13892 MFI.setReturnAddressIsTaken(true); 13893 13894 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13895 return SDValue(); 13896 13897 SDLoc dl(Op); 13898 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13899 13900 // Make sure the function does not optimize away the store of the RA to 13901 // the stack. 13902 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13903 FuncInfo->setLRStoreRequired(); 13904 bool isPPC64 = Subtarget.isPPC64(); 13905 auto PtrVT = getPointerTy(MF.getDataLayout()); 13906 13907 if (Depth > 0) { 13908 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13909 SDValue Offset = 13910 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13911 isPPC64 ? MVT::i64 : MVT::i32); 13912 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13913 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13914 MachinePointerInfo()); 13915 } 13916 13917 // Just load the return address off the stack. 13918 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13919 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13920 MachinePointerInfo()); 13921 } 13922 13923 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13924 SelectionDAG &DAG) const { 13925 SDLoc dl(Op); 13926 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13927 13928 MachineFunction &MF = DAG.getMachineFunction(); 13929 MachineFrameInfo &MFI = MF.getFrameInfo(); 13930 MFI.setFrameAddressIsTaken(true); 13931 13932 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13933 bool isPPC64 = PtrVT == MVT::i64; 13934 13935 // Naked functions never have a frame pointer, and so we use r1. For all 13936 // other functions, this decision must be delayed until during PEI. 13937 unsigned FrameReg; 13938 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13939 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13940 else 13941 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13942 13943 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13944 PtrVT); 13945 while (Depth--) 13946 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13947 FrameAddr, MachinePointerInfo()); 13948 return FrameAddr; 13949 } 13950 13951 // FIXME? Maybe this could be a TableGen attribute on some registers and 13952 // this table could be generated automatically from RegInfo. 13953 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13954 SelectionDAG &DAG) const { 13955 bool isPPC64 = Subtarget.isPPC64(); 13956 bool isDarwinABI = Subtarget.isDarwinABI(); 13957 13958 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13959 (!isPPC64 && VT != MVT::i32)) 13960 report_fatal_error("Invalid register global variable type"); 13961 13962 bool is64Bit = isPPC64 && VT == MVT::i64; 13963 unsigned Reg = StringSwitch<unsigned>(RegName) 13964 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13965 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13966 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13967 (is64Bit ? PPC::X13 : PPC::R13)) 13968 .Default(0); 13969 13970 if (Reg) 13971 return Reg; 13972 report_fatal_error("Invalid register name global variable"); 13973 } 13974 13975 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 13976 // 32-bit SVR4 ABI access everything as got-indirect. 13977 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 13978 return true; 13979 13980 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 13981 // If it is small or large code model, module locals are accessed 13982 // indirectly by loading their address from .toc/.got. The difference 13983 // is that for large code model we have ADDISTocHa + LDtocL and for 13984 // small code model we simply have LDtoc. 13985 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 13986 return true; 13987 13988 // JumpTable and BlockAddress are accessed as got-indirect. 13989 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 13990 return true; 13991 13992 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 13993 const GlobalValue *GV = G->getGlobal(); 13994 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 13995 // The NLP flag indicates that a global access has to use an 13996 // extra indirection. 13997 if (GVFlags & PPCII::MO_NLP_FLAG) 13998 return true; 13999 } 14000 14001 return false; 14002 } 14003 14004 bool 14005 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14006 // The PowerPC target isn't yet aware of offsets. 14007 return false; 14008 } 14009 14010 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14011 const CallInst &I, 14012 MachineFunction &MF, 14013 unsigned Intrinsic) const { 14014 switch (Intrinsic) { 14015 case Intrinsic::ppc_qpx_qvlfd: 14016 case Intrinsic::ppc_qpx_qvlfs: 14017 case Intrinsic::ppc_qpx_qvlfcd: 14018 case Intrinsic::ppc_qpx_qvlfcs: 14019 case Intrinsic::ppc_qpx_qvlfiwa: 14020 case Intrinsic::ppc_qpx_qvlfiwz: 14021 case Intrinsic::ppc_altivec_lvx: 14022 case Intrinsic::ppc_altivec_lvxl: 14023 case Intrinsic::ppc_altivec_lvebx: 14024 case Intrinsic::ppc_altivec_lvehx: 14025 case Intrinsic::ppc_altivec_lvewx: 14026 case Intrinsic::ppc_vsx_lxvd2x: 14027 case Intrinsic::ppc_vsx_lxvw4x: { 14028 EVT VT; 14029 switch (Intrinsic) { 14030 case Intrinsic::ppc_altivec_lvebx: 14031 VT = MVT::i8; 14032 break; 14033 case Intrinsic::ppc_altivec_lvehx: 14034 VT = MVT::i16; 14035 break; 14036 case Intrinsic::ppc_altivec_lvewx: 14037 VT = MVT::i32; 14038 break; 14039 case Intrinsic::ppc_vsx_lxvd2x: 14040 VT = MVT::v2f64; 14041 break; 14042 case Intrinsic::ppc_qpx_qvlfd: 14043 VT = MVT::v4f64; 14044 break; 14045 case Intrinsic::ppc_qpx_qvlfs: 14046 VT = MVT::v4f32; 14047 break; 14048 case Intrinsic::ppc_qpx_qvlfcd: 14049 VT = MVT::v2f64; 14050 break; 14051 case Intrinsic::ppc_qpx_qvlfcs: 14052 VT = MVT::v2f32; 14053 break; 14054 default: 14055 VT = MVT::v4i32; 14056 break; 14057 } 14058 14059 Info.opc = ISD::INTRINSIC_W_CHAIN; 14060 Info.memVT = VT; 14061 Info.ptrVal = I.getArgOperand(0); 14062 Info.offset = -VT.getStoreSize()+1; 14063 Info.size = 2*VT.getStoreSize()-1; 14064 Info.align = 1; 14065 Info.flags = MachineMemOperand::MOLoad; 14066 return true; 14067 } 14068 case Intrinsic::ppc_qpx_qvlfda: 14069 case Intrinsic::ppc_qpx_qvlfsa: 14070 case Intrinsic::ppc_qpx_qvlfcda: 14071 case Intrinsic::ppc_qpx_qvlfcsa: 14072 case Intrinsic::ppc_qpx_qvlfiwaa: 14073 case Intrinsic::ppc_qpx_qvlfiwza: { 14074 EVT VT; 14075 switch (Intrinsic) { 14076 case Intrinsic::ppc_qpx_qvlfda: 14077 VT = MVT::v4f64; 14078 break; 14079 case Intrinsic::ppc_qpx_qvlfsa: 14080 VT = MVT::v4f32; 14081 break; 14082 case Intrinsic::ppc_qpx_qvlfcda: 14083 VT = MVT::v2f64; 14084 break; 14085 case Intrinsic::ppc_qpx_qvlfcsa: 14086 VT = MVT::v2f32; 14087 break; 14088 default: 14089 VT = MVT::v4i32; 14090 break; 14091 } 14092 14093 Info.opc = ISD::INTRINSIC_W_CHAIN; 14094 Info.memVT = VT; 14095 Info.ptrVal = I.getArgOperand(0); 14096 Info.offset = 0; 14097 Info.size = VT.getStoreSize(); 14098 Info.align = 1; 14099 Info.flags = MachineMemOperand::MOLoad; 14100 return true; 14101 } 14102 case Intrinsic::ppc_qpx_qvstfd: 14103 case Intrinsic::ppc_qpx_qvstfs: 14104 case Intrinsic::ppc_qpx_qvstfcd: 14105 case Intrinsic::ppc_qpx_qvstfcs: 14106 case Intrinsic::ppc_qpx_qvstfiw: 14107 case Intrinsic::ppc_altivec_stvx: 14108 case Intrinsic::ppc_altivec_stvxl: 14109 case Intrinsic::ppc_altivec_stvebx: 14110 case Intrinsic::ppc_altivec_stvehx: 14111 case Intrinsic::ppc_altivec_stvewx: 14112 case Intrinsic::ppc_vsx_stxvd2x: 14113 case Intrinsic::ppc_vsx_stxvw4x: { 14114 EVT VT; 14115 switch (Intrinsic) { 14116 case Intrinsic::ppc_altivec_stvebx: 14117 VT = MVT::i8; 14118 break; 14119 case Intrinsic::ppc_altivec_stvehx: 14120 VT = MVT::i16; 14121 break; 14122 case Intrinsic::ppc_altivec_stvewx: 14123 VT = MVT::i32; 14124 break; 14125 case Intrinsic::ppc_vsx_stxvd2x: 14126 VT = MVT::v2f64; 14127 break; 14128 case Intrinsic::ppc_qpx_qvstfd: 14129 VT = MVT::v4f64; 14130 break; 14131 case Intrinsic::ppc_qpx_qvstfs: 14132 VT = MVT::v4f32; 14133 break; 14134 case Intrinsic::ppc_qpx_qvstfcd: 14135 VT = MVT::v2f64; 14136 break; 14137 case Intrinsic::ppc_qpx_qvstfcs: 14138 VT = MVT::v2f32; 14139 break; 14140 default: 14141 VT = MVT::v4i32; 14142 break; 14143 } 14144 14145 Info.opc = ISD::INTRINSIC_VOID; 14146 Info.memVT = VT; 14147 Info.ptrVal = I.getArgOperand(1); 14148 Info.offset = -VT.getStoreSize()+1; 14149 Info.size = 2*VT.getStoreSize()-1; 14150 Info.align = 1; 14151 Info.flags = MachineMemOperand::MOStore; 14152 return true; 14153 } 14154 case Intrinsic::ppc_qpx_qvstfda: 14155 case Intrinsic::ppc_qpx_qvstfsa: 14156 case Intrinsic::ppc_qpx_qvstfcda: 14157 case Intrinsic::ppc_qpx_qvstfcsa: 14158 case Intrinsic::ppc_qpx_qvstfiwa: { 14159 EVT VT; 14160 switch (Intrinsic) { 14161 case Intrinsic::ppc_qpx_qvstfda: 14162 VT = MVT::v4f64; 14163 break; 14164 case Intrinsic::ppc_qpx_qvstfsa: 14165 VT = MVT::v4f32; 14166 break; 14167 case Intrinsic::ppc_qpx_qvstfcda: 14168 VT = MVT::v2f64; 14169 break; 14170 case Intrinsic::ppc_qpx_qvstfcsa: 14171 VT = MVT::v2f32; 14172 break; 14173 default: 14174 VT = MVT::v4i32; 14175 break; 14176 } 14177 14178 Info.opc = ISD::INTRINSIC_VOID; 14179 Info.memVT = VT; 14180 Info.ptrVal = I.getArgOperand(1); 14181 Info.offset = 0; 14182 Info.size = VT.getStoreSize(); 14183 Info.align = 1; 14184 Info.flags = MachineMemOperand::MOStore; 14185 return true; 14186 } 14187 default: 14188 break; 14189 } 14190 14191 return false; 14192 } 14193 14194 /// getOptimalMemOpType - Returns the target specific optimal type for load 14195 /// and store operations as a result of memset, memcpy, and memmove 14196 /// lowering. If DstAlign is zero that means it's safe to destination 14197 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14198 /// means there isn't a need to check it against alignment requirement, 14199 /// probably because the source does not need to be loaded. If 'IsMemset' is 14200 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14201 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14202 /// source is constant so it does not need to be loaded. 14203 /// It returns EVT::Other if the type should be determined using generic 14204 /// target-independent logic. 14205 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 14206 unsigned DstAlign, unsigned SrcAlign, 14207 bool IsMemset, bool ZeroMemset, 14208 bool MemcpyStrSrc, 14209 MachineFunction &MF) const { 14210 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14211 const Function &F = MF.getFunction(); 14212 // When expanding a memset, require at least two QPX instructions to cover 14213 // the cost of loading the value to be stored from the constant pool. 14214 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14215 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14216 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 14217 return MVT::v4f64; 14218 } 14219 14220 // We should use Altivec/VSX loads and stores when available. For unaligned 14221 // addresses, unaligned VSX loads are only fast starting with the P8. 14222 if (Subtarget.hasAltivec() && Size >= 16 && 14223 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14224 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14225 return MVT::v4i32; 14226 } 14227 14228 if (Subtarget.isPPC64()) { 14229 return MVT::i64; 14230 } 14231 14232 return MVT::i32; 14233 } 14234 14235 /// Returns true if it is beneficial to convert a load of a constant 14236 /// to just the constant itself. 14237 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14238 Type *Ty) const { 14239 assert(Ty->isIntegerTy()); 14240 14241 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14242 return !(BitSize == 0 || BitSize > 64); 14243 } 14244 14245 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14246 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14247 return false; 14248 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14249 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14250 return NumBits1 == 64 && NumBits2 == 32; 14251 } 14252 14253 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14254 if (!VT1.isInteger() || !VT2.isInteger()) 14255 return false; 14256 unsigned NumBits1 = VT1.getSizeInBits(); 14257 unsigned NumBits2 = VT2.getSizeInBits(); 14258 return NumBits1 == 64 && NumBits2 == 32; 14259 } 14260 14261 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14262 // Generally speaking, zexts are not free, but they are free when they can be 14263 // folded with other operations. 14264 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14265 EVT MemVT = LD->getMemoryVT(); 14266 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14267 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14268 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14269 LD->getExtensionType() == ISD::ZEXTLOAD)) 14270 return true; 14271 } 14272 14273 // FIXME: Add other cases... 14274 // - 32-bit shifts with a zext to i64 14275 // - zext after ctlz, bswap, etc. 14276 // - zext after and by a constant mask 14277 14278 return TargetLowering::isZExtFree(Val, VT2); 14279 } 14280 14281 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14282 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14283 "invalid fpext types"); 14284 // Extending to float128 is not free. 14285 if (DestVT == MVT::f128) 14286 return false; 14287 return true; 14288 } 14289 14290 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14291 return isInt<16>(Imm) || isUInt<16>(Imm); 14292 } 14293 14294 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14295 return isInt<16>(Imm) || isUInt<16>(Imm); 14296 } 14297 14298 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14299 unsigned, 14300 unsigned, 14301 bool *Fast) const { 14302 if (DisablePPCUnaligned) 14303 return false; 14304 14305 // PowerPC supports unaligned memory access for simple non-vector types. 14306 // Although accessing unaligned addresses is not as efficient as accessing 14307 // aligned addresses, it is generally more efficient than manual expansion, 14308 // and generally only traps for software emulation when crossing page 14309 // boundaries. 14310 14311 if (!VT.isSimple()) 14312 return false; 14313 14314 if (VT.getSimpleVT().isVector()) { 14315 if (Subtarget.hasVSX()) { 14316 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14317 VT != MVT::v4f32 && VT != MVT::v4i32) 14318 return false; 14319 } else { 14320 return false; 14321 } 14322 } 14323 14324 if (VT == MVT::ppcf128) 14325 return false; 14326 14327 if (Fast) 14328 *Fast = true; 14329 14330 return true; 14331 } 14332 14333 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14334 VT = VT.getScalarType(); 14335 14336 if (!VT.isSimple()) 14337 return false; 14338 14339 switch (VT.getSimpleVT().SimpleTy) { 14340 case MVT::f32: 14341 case MVT::f64: 14342 return true; 14343 case MVT::f128: 14344 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14345 default: 14346 break; 14347 } 14348 14349 return false; 14350 } 14351 14352 const MCPhysReg * 14353 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14354 // LR is a callee-save register, but we must treat it as clobbered by any call 14355 // site. Hence we include LR in the scratch registers, which are in turn added 14356 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14357 // to CTR, which is used by any indirect call. 14358 static const MCPhysReg ScratchRegs[] = { 14359 PPC::X12, PPC::LR8, PPC::CTR8, 0 14360 }; 14361 14362 return ScratchRegs; 14363 } 14364 14365 unsigned PPCTargetLowering::getExceptionPointerRegister( 14366 const Constant *PersonalityFn) const { 14367 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14368 } 14369 14370 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14371 const Constant *PersonalityFn) const { 14372 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14373 } 14374 14375 bool 14376 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14377 EVT VT , unsigned DefinedValues) const { 14378 if (VT == MVT::v2i64) 14379 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14380 14381 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14382 return true; 14383 14384 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14385 } 14386 14387 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14388 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14389 return TargetLowering::getSchedulingPreference(N); 14390 14391 return Sched::ILP; 14392 } 14393 14394 // Create a fast isel object. 14395 FastISel * 14396 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14397 const TargetLibraryInfo *LibInfo) const { 14398 return PPC::createFastISel(FuncInfo, LibInfo); 14399 } 14400 14401 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14402 if (Subtarget.isDarwinABI()) return; 14403 if (!Subtarget.isPPC64()) return; 14404 14405 // Update IsSplitCSR in PPCFunctionInfo 14406 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14407 PFI->setIsSplitCSR(true); 14408 } 14409 14410 void PPCTargetLowering::insertCopiesSplitCSR( 14411 MachineBasicBlock *Entry, 14412 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14413 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14414 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14415 if (!IStart) 14416 return; 14417 14418 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14419 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14420 MachineBasicBlock::iterator MBBI = Entry->begin(); 14421 for (const MCPhysReg *I = IStart; *I; ++I) { 14422 const TargetRegisterClass *RC = nullptr; 14423 if (PPC::G8RCRegClass.contains(*I)) 14424 RC = &PPC::G8RCRegClass; 14425 else if (PPC::F8RCRegClass.contains(*I)) 14426 RC = &PPC::F8RCRegClass; 14427 else if (PPC::CRRCRegClass.contains(*I)) 14428 RC = &PPC::CRRCRegClass; 14429 else if (PPC::VRRCRegClass.contains(*I)) 14430 RC = &PPC::VRRCRegClass; 14431 else 14432 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14433 14434 unsigned NewVR = MRI->createVirtualRegister(RC); 14435 // Create copy from CSR to a virtual register. 14436 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14437 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14438 // nounwind. If we want to generalize this later, we may need to emit 14439 // CFI pseudo-instructions. 14440 assert(Entry->getParent()->getFunction().hasFnAttribute( 14441 Attribute::NoUnwind) && 14442 "Function should be nounwind in insertCopiesSplitCSR!"); 14443 Entry->addLiveIn(*I); 14444 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14445 .addReg(*I); 14446 14447 // Insert the copy-back instructions right before the terminator. 14448 for (auto *Exit : Exits) 14449 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14450 TII->get(TargetOpcode::COPY), *I) 14451 .addReg(NewVR); 14452 } 14453 } 14454 14455 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14456 bool PPCTargetLowering::useLoadStackGuardNode() const { 14457 if (!Subtarget.isTargetLinux()) 14458 return TargetLowering::useLoadStackGuardNode(); 14459 return true; 14460 } 14461 14462 // Override to disable global variable loading on Linux. 14463 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14464 if (!Subtarget.isTargetLinux()) 14465 return TargetLowering::insertSSPDeclarations(M); 14466 } 14467 14468 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14469 bool ForCodeSize) const { 14470 if (!VT.isSimple() || !Subtarget.hasVSX()) 14471 return false; 14472 14473 switch(VT.getSimpleVT().SimpleTy) { 14474 default: 14475 // For FP types that are currently not supported by PPC backend, return 14476 // false. Examples: f16, f80. 14477 return false; 14478 case MVT::f32: 14479 case MVT::f64: 14480 case MVT::ppcf128: 14481 return Imm.isPosZero(); 14482 } 14483 } 14484 14485 // For vector shift operation op, fold 14486 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14487 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14488 SelectionDAG &DAG) { 14489 SDValue N0 = N->getOperand(0); 14490 SDValue N1 = N->getOperand(1); 14491 EVT VT = N0.getValueType(); 14492 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14493 unsigned Opcode = N->getOpcode(); 14494 unsigned TargetOpcode; 14495 14496 switch (Opcode) { 14497 default: 14498 llvm_unreachable("Unexpected shift operation"); 14499 case ISD::SHL: 14500 TargetOpcode = PPCISD::SHL; 14501 break; 14502 case ISD::SRL: 14503 TargetOpcode = PPCISD::SRL; 14504 break; 14505 case ISD::SRA: 14506 TargetOpcode = PPCISD::SRA; 14507 break; 14508 } 14509 14510 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14511 N1->getOpcode() == ISD::AND) 14512 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14513 if (Mask->getZExtValue() == OpSizeInBits - 1) 14514 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14515 14516 return SDValue(); 14517 } 14518 14519 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14520 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14521 return Value; 14522 14523 SDValue N0 = N->getOperand(0); 14524 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14525 if (!Subtarget.isISA3_0() || 14526 N0.getOpcode() != ISD::SIGN_EXTEND || 14527 N0.getOperand(0).getValueType() != MVT::i32 || 14528 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14529 return SDValue(); 14530 14531 // We can't save an operation here if the value is already extended, and 14532 // the existing shift is easier to combine. 14533 SDValue ExtsSrc = N0.getOperand(0); 14534 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14535 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14536 return SDValue(); 14537 14538 SDLoc DL(N0); 14539 SDValue ShiftBy = SDValue(CN1, 0); 14540 // We want the shift amount to be i32 on the extswli, but the shift could 14541 // have an i64. 14542 if (ShiftBy.getValueType() == MVT::i64) 14543 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14544 14545 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14546 ShiftBy); 14547 } 14548 14549 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14550 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14551 return Value; 14552 14553 return SDValue(); 14554 } 14555 14556 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14557 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14558 return Value; 14559 14560 return SDValue(); 14561 } 14562 14563 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14564 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14565 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14566 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14567 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14568 const PPCSubtarget &Subtarget) { 14569 if (!Subtarget.isPPC64()) 14570 return SDValue(); 14571 14572 SDValue LHS = N->getOperand(0); 14573 SDValue RHS = N->getOperand(1); 14574 14575 auto isZextOfCompareWithConstant = [](SDValue Op) { 14576 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14577 Op.getValueType() != MVT::i64) 14578 return false; 14579 14580 SDValue Cmp = Op.getOperand(0); 14581 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14582 Cmp.getOperand(0).getValueType() != MVT::i64) 14583 return false; 14584 14585 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14586 int64_t NegConstant = 0 - Constant->getSExtValue(); 14587 // Due to the limitations of the addi instruction, 14588 // -C is required to be [-32768, 32767]. 14589 return isInt<16>(NegConstant); 14590 } 14591 14592 return false; 14593 }; 14594 14595 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14596 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14597 14598 // If there is a pattern, canonicalize a zext operand to the RHS. 14599 if (LHSHasPattern && !RHSHasPattern) 14600 std::swap(LHS, RHS); 14601 else if (!LHSHasPattern && !RHSHasPattern) 14602 return SDValue(); 14603 14604 SDLoc DL(N); 14605 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14606 SDValue Cmp = RHS.getOperand(0); 14607 SDValue Z = Cmp.getOperand(0); 14608 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14609 14610 assert(Constant && "Constant Should not be a null pointer."); 14611 int64_t NegConstant = 0 - Constant->getSExtValue(); 14612 14613 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14614 default: break; 14615 case ISD::SETNE: { 14616 // when C == 0 14617 // --> addze X, (addic Z, -1).carry 14618 // / 14619 // add X, (zext(setne Z, C))-- 14620 // \ when -32768 <= -C <= 32767 && C != 0 14621 // --> addze X, (addic (addi Z, -C), -1).carry 14622 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14623 DAG.getConstant(NegConstant, DL, MVT::i64)); 14624 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14625 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14626 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14627 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14628 SDValue(Addc.getNode(), 1)); 14629 } 14630 case ISD::SETEQ: { 14631 // when C == 0 14632 // --> addze X, (subfic Z, 0).carry 14633 // / 14634 // add X, (zext(sete Z, C))-- 14635 // \ when -32768 <= -C <= 32767 && C != 0 14636 // --> addze X, (subfic (addi Z, -C), 0).carry 14637 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14638 DAG.getConstant(NegConstant, DL, MVT::i64)); 14639 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14640 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14641 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14642 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14643 SDValue(Subc.getNode(), 1)); 14644 } 14645 } 14646 14647 return SDValue(); 14648 } 14649 14650 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14651 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14652 return Value; 14653 14654 return SDValue(); 14655 } 14656 14657 // Detect TRUNCATE operations on bitcasts of float128 values. 14658 // What we are looking for here is the situtation where we extract a subset 14659 // of bits from a 128 bit float. 14660 // This can be of two forms: 14661 // 1) BITCAST of f128 feeding TRUNCATE 14662 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14663 // The reason this is required is because we do not have a legal i128 type 14664 // and so we want to prevent having to store the f128 and then reload part 14665 // of it. 14666 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14667 DAGCombinerInfo &DCI) const { 14668 // If we are using CRBits then try that first. 14669 if (Subtarget.useCRBits()) { 14670 // Check if CRBits did anything and return that if it did. 14671 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14672 return CRTruncValue; 14673 } 14674 14675 SDLoc dl(N); 14676 SDValue Op0 = N->getOperand(0); 14677 14678 // Looking for a truncate of i128 to i64. 14679 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14680 return SDValue(); 14681 14682 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14683 14684 // SRL feeding TRUNCATE. 14685 if (Op0.getOpcode() == ISD::SRL) { 14686 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14687 // The right shift has to be by 64 bits. 14688 if (!ConstNode || ConstNode->getZExtValue() != 64) 14689 return SDValue(); 14690 14691 // Switch the element number to extract. 14692 EltToExtract = EltToExtract ? 0 : 1; 14693 // Update Op0 past the SRL. 14694 Op0 = Op0.getOperand(0); 14695 } 14696 14697 // BITCAST feeding a TRUNCATE possibly via SRL. 14698 if (Op0.getOpcode() == ISD::BITCAST && 14699 Op0.getValueType() == MVT::i128 && 14700 Op0.getOperand(0).getValueType() == MVT::f128) { 14701 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14702 return DCI.DAG.getNode( 14703 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14704 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14705 } 14706 return SDValue(); 14707 } 14708 14709 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 14710 SelectionDAG &DAG = DCI.DAG; 14711 14712 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 14713 if (!ConstOpOrElement) 14714 return SDValue(); 14715 14716 // An imul is usually smaller than the alternative sequence for legal type. 14717 if (DAG.getMachineFunction().getFunction().hasMinSize() && 14718 isOperationLegal(ISD::MUL, N->getValueType(0))) 14719 return SDValue(); 14720 14721 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 14722 switch (this->Subtarget.getDarwinDirective()) { 14723 default: 14724 // TODO: enhance the condition for subtarget before pwr8 14725 return false; 14726 case PPC::DIR_PWR8: 14727 // type mul add shl 14728 // scalar 4 1 1 14729 // vector 7 2 2 14730 return true; 14731 case PPC::DIR_PWR9: 14732 // type mul add shl 14733 // scalar 5 2 2 14734 // vector 7 2 2 14735 14736 // The cycle RATIO of related operations are showed as a table above. 14737 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 14738 // scalar and vector type. For 2 instrs patterns, add/sub + shl 14739 // are 4, it is always profitable; but for 3 instrs patterns 14740 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 14741 // So we should only do it for vector type. 14742 return IsAddOne && IsNeg ? VT.isVector() : true; 14743 } 14744 }; 14745 14746 EVT VT = N->getValueType(0); 14747 SDLoc DL(N); 14748 14749 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 14750 bool IsNeg = MulAmt.isNegative(); 14751 APInt MulAmtAbs = MulAmt.abs(); 14752 14753 if ((MulAmtAbs - 1).isPowerOf2()) { 14754 // (mul x, 2^N + 1) => (add (shl x, N), x) 14755 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 14756 14757 if (!IsProfitable(IsNeg, true, VT)) 14758 return SDValue(); 14759 14760 SDValue Op0 = N->getOperand(0); 14761 SDValue Op1 = 14762 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14763 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 14764 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 14765 14766 if (!IsNeg) 14767 return Res; 14768 14769 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 14770 } else if ((MulAmtAbs + 1).isPowerOf2()) { 14771 // (mul x, 2^N - 1) => (sub (shl x, N), x) 14772 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 14773 14774 if (!IsProfitable(IsNeg, false, VT)) 14775 return SDValue(); 14776 14777 SDValue Op0 = N->getOperand(0); 14778 SDValue Op1 = 14779 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14780 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 14781 14782 if (!IsNeg) 14783 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 14784 else 14785 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 14786 14787 } else { 14788 return SDValue(); 14789 } 14790 } 14791 14792 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14793 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14794 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14795 return false; 14796 14797 // If not a tail call then no need to proceed. 14798 if (!CI->isTailCall()) 14799 return false; 14800 14801 // If tail calls are disabled for the caller then we are done. 14802 const Function *Caller = CI->getParent()->getParent(); 14803 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14804 if (Attr.getValueAsString() == "true") 14805 return false; 14806 14807 // If sibling calls have been disabled and tail-calls aren't guaranteed 14808 // there is no reason to duplicate. 14809 auto &TM = getTargetMachine(); 14810 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14811 return false; 14812 14813 // Can't tail call a function called indirectly, or if it has variadic args. 14814 const Function *Callee = CI->getCalledFunction(); 14815 if (!Callee || Callee->isVarArg()) 14816 return false; 14817 14818 // Make sure the callee and caller calling conventions are eligible for tco. 14819 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14820 CI->getCallingConv())) 14821 return false; 14822 14823 // If the function is local then we have a good chance at tail-calling it 14824 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14825 } 14826 14827 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14828 if (!Subtarget.hasVSX()) 14829 return false; 14830 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14831 return true; 14832 return VT == MVT::f32 || VT == MVT::f64 || 14833 VT == MVT::v4f32 || VT == MVT::v2f64; 14834 } 14835 14836 bool PPCTargetLowering:: 14837 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14838 const Value *Mask = AndI.getOperand(1); 14839 // If the mask is suitable for andi. or andis. we should sink the and. 14840 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14841 // Can't handle constants wider than 64-bits. 14842 if (CI->getBitWidth() > 64) 14843 return false; 14844 int64_t ConstVal = CI->getZExtValue(); 14845 return isUInt<16>(ConstVal) || 14846 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14847 } 14848 14849 // For non-constant masks, we can always use the record-form and. 14850 return true; 14851 } 14852 14853 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 14854 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 14855 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 14856 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 14857 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 14858 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 14859 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 14860 assert(Subtarget.hasP9Altivec() && 14861 "Only combine this when P9 altivec supported!"); 14862 EVT VT = N->getValueType(0); 14863 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14864 return SDValue(); 14865 14866 SelectionDAG &DAG = DCI.DAG; 14867 SDLoc dl(N); 14868 if (N->getOperand(0).getOpcode() == ISD::SUB) { 14869 // Even for signed integers, if it's known to be positive (as signed 14870 // integer) due to zero-extended inputs. 14871 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 14872 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 14873 if ((SubOpcd0 == ISD::ZERO_EXTEND || 14874 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 14875 (SubOpcd1 == ISD::ZERO_EXTEND || 14876 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 14877 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14878 N->getOperand(0)->getOperand(0), 14879 N->getOperand(0)->getOperand(1), 14880 DAG.getTargetConstant(0, dl, MVT::i32)); 14881 } 14882 14883 // For type v4i32, it can be optimized with xvnegsp + vabsduw 14884 if (N->getOperand(0).getValueType() == MVT::v4i32 && 14885 N->getOperand(0).hasOneUse()) { 14886 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14887 N->getOperand(0)->getOperand(0), 14888 N->getOperand(0)->getOperand(1), 14889 DAG.getTargetConstant(1, dl, MVT::i32)); 14890 } 14891 } 14892 14893 return SDValue(); 14894 } 14895 14896 // For type v4i32/v8ii16/v16i8, transform 14897 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 14898 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 14899 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 14900 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 14901 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 14902 DAGCombinerInfo &DCI) const { 14903 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 14904 assert(Subtarget.hasP9Altivec() && 14905 "Only combine this when P9 altivec supported!"); 14906 14907 SelectionDAG &DAG = DCI.DAG; 14908 SDLoc dl(N); 14909 SDValue Cond = N->getOperand(0); 14910 SDValue TrueOpnd = N->getOperand(1); 14911 SDValue FalseOpnd = N->getOperand(2); 14912 EVT VT = N->getOperand(1).getValueType(); 14913 14914 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 14915 FalseOpnd.getOpcode() != ISD::SUB) 14916 return SDValue(); 14917 14918 // ABSD only available for type v4i32/v8i16/v16i8 14919 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14920 return SDValue(); 14921 14922 // At least to save one more dependent computation 14923 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 14924 return SDValue(); 14925 14926 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14927 14928 // Can only handle unsigned comparison here 14929 switch (CC) { 14930 default: 14931 return SDValue(); 14932 case ISD::SETUGT: 14933 case ISD::SETUGE: 14934 break; 14935 case ISD::SETULT: 14936 case ISD::SETULE: 14937 std::swap(TrueOpnd, FalseOpnd); 14938 break; 14939 } 14940 14941 SDValue CmpOpnd1 = Cond.getOperand(0); 14942 SDValue CmpOpnd2 = Cond.getOperand(1); 14943 14944 // SETCC CmpOpnd1 CmpOpnd2 cond 14945 // TrueOpnd = CmpOpnd1 - CmpOpnd2 14946 // FalseOpnd = CmpOpnd2 - CmpOpnd1 14947 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 14948 TrueOpnd.getOperand(1) == CmpOpnd2 && 14949 FalseOpnd.getOperand(0) == CmpOpnd2 && 14950 FalseOpnd.getOperand(1) == CmpOpnd1) { 14951 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 14952 CmpOpnd1, CmpOpnd2, 14953 DAG.getTargetConstant(0, dl, MVT::i32)); 14954 } 14955 14956 return SDValue(); 14957 } 14958