1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/MachineValueType.h" 51 #include "llvm/CodeGen/RuntimeLibcalls.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/TargetInstrInfo.h" 55 #include "llvm/CodeGen/TargetLowering.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/Support/AtomicOrdering.h" 77 #include "llvm/Support/BranchProbability.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CodeGen.h" 80 #include "llvm/Support/CommandLine.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/KnownBits.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetMachine.h" 89 #include "llvm/Target/TargetOptions.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 118 119 // FIXME: Remove this once the bug has been fixed! 120 extern cl::opt<bool> ANDIGlueBug; 121 122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 123 const PPCSubtarget &STI) 124 : TargetLowering(TM), Subtarget(STI) { 125 // Use _setjmp/_longjmp instead of setjmp/longjmp. 126 setUseUnderscoreSetJmp(true); 127 setUseUnderscoreLongJmp(true); 128 129 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 130 // arguments are at least 4/8 bytes aligned. 131 bool isPPC64 = Subtarget.isPPC64(); 132 setMinStackArgumentAlignment(isPPC64 ? 8:4); 133 134 // Set up the register classes. 135 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 136 if (!useSoftFloat()) { 137 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 138 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 139 } 140 141 // Match BITREVERSE to customized fast code sequence in the td file. 142 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 143 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 144 145 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 146 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 147 148 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 149 for (MVT VT : MVT::integer_valuetypes()) { 150 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 152 } 153 154 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 155 156 // PowerPC has pre-inc load and store's. 157 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 158 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 159 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 160 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 161 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 162 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 163 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 164 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 165 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 166 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 167 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 168 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 169 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 170 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 171 172 if (Subtarget.useCRBits()) { 173 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 174 175 if (isPPC64 || Subtarget.hasFPCVT()) { 176 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 177 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 178 isPPC64 ? MVT::i64 : MVT::i32); 179 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 180 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 181 isPPC64 ? MVT::i64 : MVT::i32); 182 } else { 183 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 184 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 185 } 186 187 // PowerPC does not support direct load/store of condition registers. 188 setOperationAction(ISD::LOAD, MVT::i1, Custom); 189 setOperationAction(ISD::STORE, MVT::i1, Custom); 190 191 // FIXME: Remove this once the ANDI glue bug is fixed: 192 if (ANDIGlueBug) 193 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 194 195 for (MVT VT : MVT::integer_valuetypes()) { 196 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 197 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 198 setTruncStoreAction(VT, MVT::i1, Expand); 199 } 200 201 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 202 } 203 204 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 205 // PPC (the libcall is not available). 206 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 207 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 208 209 // We do not currently implement these libm ops for PowerPC. 210 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 211 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 212 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 213 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 214 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 215 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 216 217 // PowerPC has no SREM/UREM instructions unless we are on P9 218 // On P9 we may use a hardware instruction to compute the remainder. 219 // The instructions are not legalized directly because in the cases where the 220 // result of both the remainder and the division is required it is more 221 // efficient to compute the remainder from the result of the division rather 222 // than use the remainder instruction. 223 if (Subtarget.isISA3_0()) { 224 setOperationAction(ISD::SREM, MVT::i32, Custom); 225 setOperationAction(ISD::UREM, MVT::i32, Custom); 226 setOperationAction(ISD::SREM, MVT::i64, Custom); 227 setOperationAction(ISD::UREM, MVT::i64, Custom); 228 } else { 229 setOperationAction(ISD::SREM, MVT::i32, Expand); 230 setOperationAction(ISD::UREM, MVT::i32, Expand); 231 setOperationAction(ISD::SREM, MVT::i64, Expand); 232 setOperationAction(ISD::UREM, MVT::i64, Expand); 233 } 234 235 if (Subtarget.hasP9Vector()) { 236 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 237 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 238 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 239 } 240 241 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 242 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 243 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 244 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 245 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 247 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 248 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 249 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 250 251 // We don't support sin/cos/sqrt/fmod/pow 252 setOperationAction(ISD::FSIN , MVT::f64, Expand); 253 setOperationAction(ISD::FCOS , MVT::f64, Expand); 254 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 255 setOperationAction(ISD::FREM , MVT::f64, Expand); 256 setOperationAction(ISD::FPOW , MVT::f64, Expand); 257 setOperationAction(ISD::FMA , MVT::f64, Legal); 258 setOperationAction(ISD::FSIN , MVT::f32, Expand); 259 setOperationAction(ISD::FCOS , MVT::f32, Expand); 260 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 261 setOperationAction(ISD::FREM , MVT::f32, Expand); 262 setOperationAction(ISD::FPOW , MVT::f32, Expand); 263 setOperationAction(ISD::FMA , MVT::f32, Legal); 264 265 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 266 267 // If we're enabling GP optimizations, use hardware square root 268 if (!Subtarget.hasFSQRT() && 269 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 270 Subtarget.hasFRE())) 271 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 272 273 if (!Subtarget.hasFSQRT() && 274 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 275 Subtarget.hasFRES())) 276 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 277 278 if (Subtarget.hasFCPSGN()) { 279 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 280 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 281 } else { 282 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 283 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 284 } 285 286 if (Subtarget.hasFPRND()) { 287 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 288 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 289 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 290 setOperationAction(ISD::FROUND, MVT::f64, Legal); 291 292 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 293 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 294 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 295 setOperationAction(ISD::FROUND, MVT::f32, Legal); 296 } 297 298 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 299 // to speed up scalar BSWAP64. 300 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 301 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 302 if (Subtarget.isISA3_0()) { 303 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 304 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 305 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 306 } else { 307 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 308 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 309 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 310 } 311 312 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 313 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 314 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 315 } else { 316 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 317 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 318 } 319 320 // PowerPC does not have ROTR 321 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 322 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 323 324 if (!Subtarget.useCRBits()) { 325 // PowerPC does not have Select 326 setOperationAction(ISD::SELECT, MVT::i32, Expand); 327 setOperationAction(ISD::SELECT, MVT::i64, Expand); 328 setOperationAction(ISD::SELECT, MVT::f32, Expand); 329 setOperationAction(ISD::SELECT, MVT::f64, Expand); 330 } 331 332 // PowerPC wants to turn select_cc of FP into fsel when possible. 333 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 334 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 335 336 // PowerPC wants to optimize integer setcc a bit 337 if (!Subtarget.useCRBits()) 338 setOperationAction(ISD::SETCC, MVT::i32, Custom); 339 340 // PowerPC does not have BRCOND which requires SetCC 341 if (!Subtarget.useCRBits()) 342 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 343 344 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 345 346 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 347 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 348 349 // PowerPC does not have [U|S]INT_TO_FP 350 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 351 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 352 353 if (Subtarget.hasDirectMove() && isPPC64) { 354 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 355 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 356 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 357 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 358 } else { 359 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 360 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 361 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 362 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 363 } 364 365 // We cannot sextinreg(i1). Expand to shifts. 366 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 367 368 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 369 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 370 // support continuation, user-level threading, and etc.. As a result, no 371 // other SjLj exception interfaces are implemented and please don't build 372 // your own exception handling based on them. 373 // LLVM/Clang supports zero-cost DWARF exception handling. 374 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 375 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 376 377 // We want to legalize GlobalAddress and ConstantPool nodes into the 378 // appropriate instructions to materialize the address. 379 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 380 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 381 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 382 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 383 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 384 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 385 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 386 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 387 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 388 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 389 390 // TRAP is legal. 391 setOperationAction(ISD::TRAP, MVT::Other, Legal); 392 393 // TRAMPOLINE is custom lowered. 394 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 395 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 396 397 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 398 setOperationAction(ISD::VASTART , MVT::Other, Custom); 399 400 if (Subtarget.isSVR4ABI()) { 401 if (isPPC64) { 402 // VAARG always uses double-word chunks, so promote anything smaller. 403 setOperationAction(ISD::VAARG, MVT::i1, Promote); 404 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 405 setOperationAction(ISD::VAARG, MVT::i8, Promote); 406 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 407 setOperationAction(ISD::VAARG, MVT::i16, Promote); 408 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 409 setOperationAction(ISD::VAARG, MVT::i32, Promote); 410 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 411 setOperationAction(ISD::VAARG, MVT::Other, Expand); 412 } else { 413 // VAARG is custom lowered with the 32-bit SVR4 ABI. 414 setOperationAction(ISD::VAARG, MVT::Other, Custom); 415 setOperationAction(ISD::VAARG, MVT::i64, Custom); 416 } 417 } else 418 setOperationAction(ISD::VAARG, MVT::Other, Expand); 419 420 if (Subtarget.isSVR4ABI() && !isPPC64) 421 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 422 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 423 else 424 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 425 426 // Use the default implementation. 427 setOperationAction(ISD::VAEND , MVT::Other, Expand); 428 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 429 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 430 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 431 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 432 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 433 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 434 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 435 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 436 437 // We want to custom lower some of our intrinsics. 438 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 439 440 // To handle counter-based loop conditions. 441 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 442 443 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 444 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 445 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 446 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 447 448 // Comparisons that require checking two conditions. 449 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 450 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 451 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 452 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 453 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 454 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 455 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 456 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 457 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 458 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 459 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 460 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 461 462 if (Subtarget.has64BitSupport()) { 463 // They also have instructions for converting between i64 and fp. 464 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 465 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 466 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 467 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 468 // This is just the low 32 bits of a (signed) fp->i64 conversion. 469 // We cannot do this with Promote because i64 is not a legal type. 470 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 471 472 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 473 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 474 } else { 475 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 476 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 477 } 478 479 // With the instructions enabled under FPCVT, we can do everything. 480 if (Subtarget.hasFPCVT()) { 481 if (Subtarget.has64BitSupport()) { 482 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 483 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 484 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 485 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 486 } 487 488 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 489 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 490 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 491 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 492 } 493 494 if (Subtarget.use64BitRegs()) { 495 // 64-bit PowerPC implementations can support i64 types directly 496 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 497 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 498 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 499 // 64-bit PowerPC wants to expand i128 shifts itself. 500 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 501 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 502 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 503 } else { 504 // 32-bit PowerPC wants to expand i64 shifts itself. 505 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 506 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 507 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 508 } 509 510 if (Subtarget.hasAltivec()) { 511 // First set operation action for all vector types to expand. Then we 512 // will selectively turn on ones that can be effectively codegen'd. 513 for (MVT VT : MVT::vector_valuetypes()) { 514 // add/sub are legal for all supported vector VT's. 515 setOperationAction(ISD::ADD, VT, Legal); 516 setOperationAction(ISD::SUB, VT, Legal); 517 518 // Vector instructions introduced in P8 519 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 520 setOperationAction(ISD::CTPOP, VT, Legal); 521 setOperationAction(ISD::CTLZ, VT, Legal); 522 } 523 else { 524 setOperationAction(ISD::CTPOP, VT, Expand); 525 setOperationAction(ISD::CTLZ, VT, Expand); 526 } 527 528 // Vector instructions introduced in P9 529 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 530 setOperationAction(ISD::CTTZ, VT, Legal); 531 else 532 setOperationAction(ISD::CTTZ, VT, Expand); 533 534 // We promote all shuffles to v16i8. 535 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 536 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 537 538 // We promote all non-typed operations to v4i32. 539 setOperationAction(ISD::AND , VT, Promote); 540 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 541 setOperationAction(ISD::OR , VT, Promote); 542 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 543 setOperationAction(ISD::XOR , VT, Promote); 544 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 545 setOperationAction(ISD::LOAD , VT, Promote); 546 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 547 setOperationAction(ISD::SELECT, VT, Promote); 548 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 549 setOperationAction(ISD::SELECT_CC, VT, Promote); 550 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 551 setOperationAction(ISD::STORE, VT, Promote); 552 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 553 554 // No other operations are legal. 555 setOperationAction(ISD::MUL , VT, Expand); 556 setOperationAction(ISD::SDIV, VT, Expand); 557 setOperationAction(ISD::SREM, VT, Expand); 558 setOperationAction(ISD::UDIV, VT, Expand); 559 setOperationAction(ISD::UREM, VT, Expand); 560 setOperationAction(ISD::FDIV, VT, Expand); 561 setOperationAction(ISD::FREM, VT, Expand); 562 setOperationAction(ISD::FNEG, VT, Expand); 563 setOperationAction(ISD::FSQRT, VT, Expand); 564 setOperationAction(ISD::FLOG, VT, Expand); 565 setOperationAction(ISD::FLOG10, VT, Expand); 566 setOperationAction(ISD::FLOG2, VT, Expand); 567 setOperationAction(ISD::FEXP, VT, Expand); 568 setOperationAction(ISD::FEXP2, VT, Expand); 569 setOperationAction(ISD::FSIN, VT, Expand); 570 setOperationAction(ISD::FCOS, VT, Expand); 571 setOperationAction(ISD::FABS, VT, Expand); 572 setOperationAction(ISD::FFLOOR, VT, Expand); 573 setOperationAction(ISD::FCEIL, VT, Expand); 574 setOperationAction(ISD::FTRUNC, VT, Expand); 575 setOperationAction(ISD::FRINT, VT, Expand); 576 setOperationAction(ISD::FNEARBYINT, VT, Expand); 577 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 578 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 579 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 580 setOperationAction(ISD::MULHU, VT, Expand); 581 setOperationAction(ISD::MULHS, VT, Expand); 582 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 583 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 584 setOperationAction(ISD::UDIVREM, VT, Expand); 585 setOperationAction(ISD::SDIVREM, VT, Expand); 586 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 587 setOperationAction(ISD::FPOW, VT, Expand); 588 setOperationAction(ISD::BSWAP, VT, Expand); 589 setOperationAction(ISD::VSELECT, VT, Expand); 590 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 591 setOperationAction(ISD::ROTL, VT, Expand); 592 setOperationAction(ISD::ROTR, VT, Expand); 593 594 for (MVT InnerVT : MVT::vector_valuetypes()) { 595 setTruncStoreAction(VT, InnerVT, Expand); 596 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 597 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 598 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 599 } 600 } 601 602 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 603 // with merges, splats, etc. 604 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 605 606 setOperationAction(ISD::AND , MVT::v4i32, Legal); 607 setOperationAction(ISD::OR , MVT::v4i32, Legal); 608 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 609 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 610 setOperationAction(ISD::SELECT, MVT::v4i32, 611 Subtarget.useCRBits() ? Legal : Expand); 612 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 613 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 614 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 615 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 616 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 617 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 618 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 619 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 620 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 621 622 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 623 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 624 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 625 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 626 627 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 628 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 629 630 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 631 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 632 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 633 } 634 635 if (Subtarget.hasP8Altivec()) 636 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 637 else 638 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 639 640 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 641 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 642 643 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 644 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 645 646 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 647 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 648 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 649 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 650 651 // Altivec does not contain unordered floating-point compare instructions 652 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 653 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 654 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 655 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 656 657 if (Subtarget.hasVSX()) { 658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 659 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 660 if (Subtarget.hasP8Vector()) { 661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 663 } 664 if (Subtarget.hasDirectMove() && isPPC64) { 665 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 666 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 667 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 673 } 674 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 675 676 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 677 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 678 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 679 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 680 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 681 682 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 683 684 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 685 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 686 687 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 688 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 689 690 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 691 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 692 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 693 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 694 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 695 696 // Share the Altivec comparison restrictions. 697 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 698 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 699 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 700 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 701 702 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 703 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 704 705 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 706 707 if (Subtarget.hasP8Vector()) 708 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 709 710 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 711 712 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 713 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 714 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 715 716 if (Subtarget.hasP8Altivec()) { 717 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 718 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 719 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 720 721 // 128 bit shifts can be accomplished via 3 instructions for SHL and 722 // SRL, but not for SRA because of the instructions available: 723 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 724 // doing 725 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 726 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 727 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 728 729 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 730 } 731 else { 732 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 733 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 734 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 735 736 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 737 738 // VSX v2i64 only supports non-arithmetic operations. 739 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 740 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 741 } 742 743 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 744 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 745 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 746 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 747 748 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 749 750 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 751 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 752 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 753 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 754 755 // Vector operation legalization checks the result type of 756 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 757 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 758 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 759 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 760 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 761 762 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 763 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 764 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 765 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 766 767 if (Subtarget.hasDirectMove()) 768 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 769 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 770 771 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 772 } 773 774 if (Subtarget.hasP8Altivec()) { 775 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 776 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 777 } 778 779 if (Subtarget.hasP9Vector()) { 780 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 781 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 782 783 // 128 bit shifts can be accomplished via 3 instructions for SHL and 784 // SRL, but not for SRA because of the instructions available: 785 // VS{RL} and VS{RL}O. 786 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 787 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 788 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 789 790 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 791 setOperationAction(ISD::FADD, MVT::f128, Legal); 792 setOperationAction(ISD::FSUB, MVT::f128, Legal); 793 setOperationAction(ISD::FDIV, MVT::f128, Legal); 794 setOperationAction(ISD::FMUL, MVT::f128, Legal); 795 796 } 797 798 if (Subtarget.hasP9Altivec()) { 799 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 800 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 801 } 802 } 803 804 if (Subtarget.hasQPX()) { 805 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 806 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 807 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 808 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 809 810 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 811 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 812 813 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 814 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 815 816 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 817 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 818 819 if (!Subtarget.useCRBits()) 820 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 821 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 822 823 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 824 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 825 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 826 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 827 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 829 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 830 831 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 832 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 833 834 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 835 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 836 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 837 838 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 839 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 840 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 841 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 842 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 843 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 844 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 845 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 846 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 847 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 848 849 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 850 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 851 852 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 853 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 854 855 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 856 857 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 858 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 859 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 860 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 861 862 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 863 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 864 865 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 866 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 867 868 if (!Subtarget.useCRBits()) 869 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 870 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 871 872 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 873 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 874 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 875 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 876 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 877 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 878 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 879 880 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 881 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 882 883 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 884 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 885 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 886 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 887 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 888 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 889 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 890 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 891 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 892 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 893 894 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 895 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 896 897 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 898 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 899 900 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 901 902 setOperationAction(ISD::AND , MVT::v4i1, Legal); 903 setOperationAction(ISD::OR , MVT::v4i1, Legal); 904 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 905 906 if (!Subtarget.useCRBits()) 907 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 908 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 909 910 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 911 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 912 913 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 914 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 915 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 916 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 917 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 918 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 920 921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 923 924 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 925 926 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 927 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 928 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 929 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 930 931 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 932 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 933 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 934 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 935 936 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 937 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 938 939 // These need to set FE_INEXACT, and so cannot be vectorized here. 940 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 941 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 942 943 if (TM.Options.UnsafeFPMath) { 944 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 945 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 946 947 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 948 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 949 } else { 950 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 951 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 952 953 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 954 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 955 } 956 } 957 958 if (Subtarget.has64BitSupport()) 959 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 960 961 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 962 963 if (!isPPC64) { 964 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 965 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 966 } 967 968 setBooleanContents(ZeroOrOneBooleanContent); 969 970 if (Subtarget.hasAltivec()) { 971 // Altivec instructions set fields to all zeros or all ones. 972 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 973 } 974 975 if (!isPPC64) { 976 // These libcalls are not available in 32-bit. 977 setLibcallName(RTLIB::SHL_I128, nullptr); 978 setLibcallName(RTLIB::SRL_I128, nullptr); 979 setLibcallName(RTLIB::SRA_I128, nullptr); 980 } 981 982 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 983 984 // We have target-specific dag combine patterns for the following nodes: 985 setTargetDAGCombine(ISD::SHL); 986 setTargetDAGCombine(ISD::SRA); 987 setTargetDAGCombine(ISD::SRL); 988 setTargetDAGCombine(ISD::SINT_TO_FP); 989 setTargetDAGCombine(ISD::BUILD_VECTOR); 990 if (Subtarget.hasFPCVT()) 991 setTargetDAGCombine(ISD::UINT_TO_FP); 992 setTargetDAGCombine(ISD::LOAD); 993 setTargetDAGCombine(ISD::STORE); 994 setTargetDAGCombine(ISD::BR_CC); 995 if (Subtarget.useCRBits()) 996 setTargetDAGCombine(ISD::BRCOND); 997 setTargetDAGCombine(ISD::BSWAP); 998 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 999 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1000 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1001 1002 setTargetDAGCombine(ISD::SIGN_EXTEND); 1003 setTargetDAGCombine(ISD::ZERO_EXTEND); 1004 setTargetDAGCombine(ISD::ANY_EXTEND); 1005 1006 if (Subtarget.useCRBits()) { 1007 setTargetDAGCombine(ISD::TRUNCATE); 1008 setTargetDAGCombine(ISD::SETCC); 1009 setTargetDAGCombine(ISD::SELECT_CC); 1010 } 1011 1012 // Use reciprocal estimates. 1013 if (TM.Options.UnsafeFPMath) { 1014 setTargetDAGCombine(ISD::FDIV); 1015 setTargetDAGCombine(ISD::FSQRT); 1016 } 1017 1018 // Darwin long double math library functions have $LDBL128 appended. 1019 if (Subtarget.isDarwin()) { 1020 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1021 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1022 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1023 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1024 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1025 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1026 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1027 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1028 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1029 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1030 } 1031 1032 // With 32 condition bits, we don't need to sink (and duplicate) compares 1033 // aggressively in CodeGenPrep. 1034 if (Subtarget.useCRBits()) { 1035 setHasMultipleConditionRegisters(); 1036 setJumpIsExpensive(); 1037 } 1038 1039 setMinFunctionAlignment(2); 1040 if (Subtarget.isDarwin()) 1041 setPrefFunctionAlignment(4); 1042 1043 switch (Subtarget.getDarwinDirective()) { 1044 default: break; 1045 case PPC::DIR_970: 1046 case PPC::DIR_A2: 1047 case PPC::DIR_E500mc: 1048 case PPC::DIR_E5500: 1049 case PPC::DIR_PWR4: 1050 case PPC::DIR_PWR5: 1051 case PPC::DIR_PWR5X: 1052 case PPC::DIR_PWR6: 1053 case PPC::DIR_PWR6X: 1054 case PPC::DIR_PWR7: 1055 case PPC::DIR_PWR8: 1056 case PPC::DIR_PWR9: 1057 setPrefFunctionAlignment(4); 1058 setPrefLoopAlignment(4); 1059 break; 1060 } 1061 1062 if (Subtarget.enableMachineScheduler()) 1063 setSchedulingPreference(Sched::Source); 1064 else 1065 setSchedulingPreference(Sched::Hybrid); 1066 1067 computeRegisterProperties(STI.getRegisterInfo()); 1068 1069 // The Freescale cores do better with aggressive inlining of memcpy and 1070 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1071 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1072 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1073 MaxStoresPerMemset = 32; 1074 MaxStoresPerMemsetOptSize = 16; 1075 MaxStoresPerMemcpy = 32; 1076 MaxStoresPerMemcpyOptSize = 8; 1077 MaxStoresPerMemmove = 32; 1078 MaxStoresPerMemmoveOptSize = 8; 1079 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1080 // The A2 also benefits from (very) aggressive inlining of memcpy and 1081 // friends. The overhead of a the function call, even when warm, can be 1082 // over one hundred cycles. 1083 MaxStoresPerMemset = 128; 1084 MaxStoresPerMemcpy = 128; 1085 MaxStoresPerMemmove = 128; 1086 MaxLoadsPerMemcmp = 128; 1087 } else { 1088 MaxLoadsPerMemcmp = 8; 1089 MaxLoadsPerMemcmpOptSize = 4; 1090 } 1091 } 1092 1093 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1094 /// the desired ByVal argument alignment. 1095 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1096 unsigned MaxMaxAlign) { 1097 if (MaxAlign == MaxMaxAlign) 1098 return; 1099 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1100 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1101 MaxAlign = 32; 1102 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1103 MaxAlign = 16; 1104 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1105 unsigned EltAlign = 0; 1106 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1107 if (EltAlign > MaxAlign) 1108 MaxAlign = EltAlign; 1109 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1110 for (auto *EltTy : STy->elements()) { 1111 unsigned EltAlign = 0; 1112 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1113 if (EltAlign > MaxAlign) 1114 MaxAlign = EltAlign; 1115 if (MaxAlign == MaxMaxAlign) 1116 break; 1117 } 1118 } 1119 } 1120 1121 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1122 /// function arguments in the caller parameter area. 1123 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1124 const DataLayout &DL) const { 1125 // Darwin passes everything on 4 byte boundary. 1126 if (Subtarget.isDarwin()) 1127 return 4; 1128 1129 // 16byte and wider vectors are passed on 16byte boundary. 1130 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1131 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1132 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1133 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1134 return Align; 1135 } 1136 1137 bool PPCTargetLowering::useSoftFloat() const { 1138 return Subtarget.useSoftFloat(); 1139 } 1140 1141 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1142 switch ((PPCISD::NodeType)Opcode) { 1143 case PPCISD::FIRST_NUMBER: break; 1144 case PPCISD::FSEL: return "PPCISD::FSEL"; 1145 case PPCISD::FCFID: return "PPCISD::FCFID"; 1146 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1147 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1148 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1149 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1150 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1151 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1152 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1153 case PPCISD::FRE: return "PPCISD::FRE"; 1154 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1155 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1156 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1157 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1158 case PPCISD::VPERM: return "PPCISD::VPERM"; 1159 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1160 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1161 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1162 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1163 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1164 case PPCISD::CMPB: return "PPCISD::CMPB"; 1165 case PPCISD::Hi: return "PPCISD::Hi"; 1166 case PPCISD::Lo: return "PPCISD::Lo"; 1167 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1168 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1169 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1170 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1171 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1172 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1173 case PPCISD::SRL: return "PPCISD::SRL"; 1174 case PPCISD::SRA: return "PPCISD::SRA"; 1175 case PPCISD::SHL: return "PPCISD::SHL"; 1176 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1177 case PPCISD::CALL: return "PPCISD::CALL"; 1178 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1179 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1180 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1181 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1182 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1183 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1184 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1185 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1186 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1187 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1188 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1189 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1190 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1191 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1192 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1193 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1194 case PPCISD::VCMP: return "PPCISD::VCMP"; 1195 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1196 case PPCISD::LBRX: return "PPCISD::LBRX"; 1197 case PPCISD::STBRX: return "PPCISD::STBRX"; 1198 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1199 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1200 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1201 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1202 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1203 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1204 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1205 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1206 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1207 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1208 case PPCISD::BDZ: return "PPCISD::BDZ"; 1209 case PPCISD::MFFS: return "PPCISD::MFFS"; 1210 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1211 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1212 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1213 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1214 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1215 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1216 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1217 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1218 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1219 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1220 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1221 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1222 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1223 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1224 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1225 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1226 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1227 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1228 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1229 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1230 case PPCISD::SC: return "PPCISD::SC"; 1231 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1232 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1233 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1234 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1235 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1236 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1237 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1238 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1239 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1240 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1241 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1242 } 1243 return nullptr; 1244 } 1245 1246 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1247 EVT VT) const { 1248 if (!VT.isVector()) 1249 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1250 1251 if (Subtarget.hasQPX()) 1252 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1253 1254 return VT.changeVectorElementTypeToInteger(); 1255 } 1256 1257 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1258 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1259 return true; 1260 } 1261 1262 //===----------------------------------------------------------------------===// 1263 // Node matching predicates, for use by the tblgen matching code. 1264 //===----------------------------------------------------------------------===// 1265 1266 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1267 static bool isFloatingPointZero(SDValue Op) { 1268 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1269 return CFP->getValueAPF().isZero(); 1270 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1271 // Maybe this has already been legalized into the constant pool? 1272 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1273 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1274 return CFP->getValueAPF().isZero(); 1275 } 1276 return false; 1277 } 1278 1279 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1280 /// true if Op is undef or if it matches the specified value. 1281 static bool isConstantOrUndef(int Op, int Val) { 1282 return Op < 0 || Op == Val; 1283 } 1284 1285 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1286 /// VPKUHUM instruction. 1287 /// The ShuffleKind distinguishes between big-endian operations with 1288 /// two different inputs (0), either-endian operations with two identical 1289 /// inputs (1), and little-endian operations with two different inputs (2). 1290 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1291 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1292 SelectionDAG &DAG) { 1293 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1294 if (ShuffleKind == 0) { 1295 if (IsLE) 1296 return false; 1297 for (unsigned i = 0; i != 16; ++i) 1298 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1299 return false; 1300 } else if (ShuffleKind == 2) { 1301 if (!IsLE) 1302 return false; 1303 for (unsigned i = 0; i != 16; ++i) 1304 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1305 return false; 1306 } else if (ShuffleKind == 1) { 1307 unsigned j = IsLE ? 0 : 1; 1308 for (unsigned i = 0; i != 8; ++i) 1309 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1310 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1311 return false; 1312 } 1313 return true; 1314 } 1315 1316 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1317 /// VPKUWUM instruction. 1318 /// The ShuffleKind distinguishes between big-endian operations with 1319 /// two different inputs (0), either-endian operations with two identical 1320 /// inputs (1), and little-endian operations with two different inputs (2). 1321 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1322 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1323 SelectionDAG &DAG) { 1324 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1325 if (ShuffleKind == 0) { 1326 if (IsLE) 1327 return false; 1328 for (unsigned i = 0; i != 16; i += 2) 1329 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1330 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1331 return false; 1332 } else if (ShuffleKind == 2) { 1333 if (!IsLE) 1334 return false; 1335 for (unsigned i = 0; i != 16; i += 2) 1336 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1337 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1338 return false; 1339 } else if (ShuffleKind == 1) { 1340 unsigned j = IsLE ? 0 : 2; 1341 for (unsigned i = 0; i != 8; i += 2) 1342 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1343 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1344 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1345 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1346 return false; 1347 } 1348 return true; 1349 } 1350 1351 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1352 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1353 /// current subtarget. 1354 /// 1355 /// The ShuffleKind distinguishes between big-endian operations with 1356 /// two different inputs (0), either-endian operations with two identical 1357 /// inputs (1), and little-endian operations with two different inputs (2). 1358 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1359 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1360 SelectionDAG &DAG) { 1361 const PPCSubtarget& Subtarget = 1362 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1363 if (!Subtarget.hasP8Vector()) 1364 return false; 1365 1366 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1367 if (ShuffleKind == 0) { 1368 if (IsLE) 1369 return false; 1370 for (unsigned i = 0; i != 16; i += 4) 1371 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1372 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1373 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1374 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1375 return false; 1376 } else if (ShuffleKind == 2) { 1377 if (!IsLE) 1378 return false; 1379 for (unsigned i = 0; i != 16; i += 4) 1380 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1381 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1382 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1383 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1384 return false; 1385 } else if (ShuffleKind == 1) { 1386 unsigned j = IsLE ? 0 : 4; 1387 for (unsigned i = 0; i != 8; i += 4) 1388 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1389 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1390 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1391 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1392 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1393 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1394 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1395 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1396 return false; 1397 } 1398 return true; 1399 } 1400 1401 /// isVMerge - Common function, used to match vmrg* shuffles. 1402 /// 1403 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1404 unsigned LHSStart, unsigned RHSStart) { 1405 if (N->getValueType(0) != MVT::v16i8) 1406 return false; 1407 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1408 "Unsupported merge size!"); 1409 1410 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1411 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1412 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1413 LHSStart+j+i*UnitSize) || 1414 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1415 RHSStart+j+i*UnitSize)) 1416 return false; 1417 } 1418 return true; 1419 } 1420 1421 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1422 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1423 /// The ShuffleKind distinguishes between big-endian merges with two 1424 /// different inputs (0), either-endian merges with two identical inputs (1), 1425 /// and little-endian merges with two different inputs (2). For the latter, 1426 /// the input operands are swapped (see PPCInstrAltivec.td). 1427 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1428 unsigned ShuffleKind, SelectionDAG &DAG) { 1429 if (DAG.getDataLayout().isLittleEndian()) { 1430 if (ShuffleKind == 1) // unary 1431 return isVMerge(N, UnitSize, 0, 0); 1432 else if (ShuffleKind == 2) // swapped 1433 return isVMerge(N, UnitSize, 0, 16); 1434 else 1435 return false; 1436 } else { 1437 if (ShuffleKind == 1) // unary 1438 return isVMerge(N, UnitSize, 8, 8); 1439 else if (ShuffleKind == 0) // normal 1440 return isVMerge(N, UnitSize, 8, 24); 1441 else 1442 return false; 1443 } 1444 } 1445 1446 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1447 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1448 /// The ShuffleKind distinguishes between big-endian merges with two 1449 /// different inputs (0), either-endian merges with two identical inputs (1), 1450 /// and little-endian merges with two different inputs (2). For the latter, 1451 /// the input operands are swapped (see PPCInstrAltivec.td). 1452 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1453 unsigned ShuffleKind, SelectionDAG &DAG) { 1454 if (DAG.getDataLayout().isLittleEndian()) { 1455 if (ShuffleKind == 1) // unary 1456 return isVMerge(N, UnitSize, 8, 8); 1457 else if (ShuffleKind == 2) // swapped 1458 return isVMerge(N, UnitSize, 8, 24); 1459 else 1460 return false; 1461 } else { 1462 if (ShuffleKind == 1) // unary 1463 return isVMerge(N, UnitSize, 0, 0); 1464 else if (ShuffleKind == 0) // normal 1465 return isVMerge(N, UnitSize, 0, 16); 1466 else 1467 return false; 1468 } 1469 } 1470 1471 /** 1472 * \brief Common function used to match vmrgew and vmrgow shuffles 1473 * 1474 * The indexOffset determines whether to look for even or odd words in 1475 * the shuffle mask. This is based on the of the endianness of the target 1476 * machine. 1477 * - Little Endian: 1478 * - Use offset of 0 to check for odd elements 1479 * - Use offset of 4 to check for even elements 1480 * - Big Endian: 1481 * - Use offset of 0 to check for even elements 1482 * - Use offset of 4 to check for odd elements 1483 * A detailed description of the vector element ordering for little endian and 1484 * big endian can be found at 1485 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1486 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1487 * compiler differences mean to you 1488 * 1489 * The mask to the shuffle vector instruction specifies the indices of the 1490 * elements from the two input vectors to place in the result. The elements are 1491 * numbered in array-access order, starting with the first vector. These vectors 1492 * are always of type v16i8, thus each vector will contain 16 elements of size 1493 * 8. More info on the shuffle vector can be found in the 1494 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1495 * Language Reference. 1496 * 1497 * The RHSStartValue indicates whether the same input vectors are used (unary) 1498 * or two different input vectors are used, based on the following: 1499 * - If the instruction uses the same vector for both inputs, the range of the 1500 * indices will be 0 to 15. In this case, the RHSStart value passed should 1501 * be 0. 1502 * - If the instruction has two different vectors then the range of the 1503 * indices will be 0 to 31. In this case, the RHSStart value passed should 1504 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1505 * to 31 specify elements in the second vector). 1506 * 1507 * \param[in] N The shuffle vector SD Node to analyze 1508 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1509 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1510 * vector to the shuffle_vector instruction 1511 * \return true iff this shuffle vector represents an even or odd word merge 1512 */ 1513 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1514 unsigned RHSStartValue) { 1515 if (N->getValueType(0) != MVT::v16i8) 1516 return false; 1517 1518 for (unsigned i = 0; i < 2; ++i) 1519 for (unsigned j = 0; j < 4; ++j) 1520 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1521 i*RHSStartValue+j+IndexOffset) || 1522 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1523 i*RHSStartValue+j+IndexOffset+8)) 1524 return false; 1525 return true; 1526 } 1527 1528 /** 1529 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1530 * vmrgow instructions. 1531 * 1532 * \param[in] N The shuffle vector SD Node to analyze 1533 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1534 * \param[in] ShuffleKind Identify the type of merge: 1535 * - 0 = big-endian merge with two different inputs; 1536 * - 1 = either-endian merge with two identical inputs; 1537 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1538 * little-endian merges). 1539 * \param[in] DAG The current SelectionDAG 1540 * \return true iff this shuffle mask 1541 */ 1542 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1543 unsigned ShuffleKind, SelectionDAG &DAG) { 1544 if (DAG.getDataLayout().isLittleEndian()) { 1545 unsigned indexOffset = CheckEven ? 4 : 0; 1546 if (ShuffleKind == 1) // Unary 1547 return isVMerge(N, indexOffset, 0); 1548 else if (ShuffleKind == 2) // swapped 1549 return isVMerge(N, indexOffset, 16); 1550 else 1551 return false; 1552 } 1553 else { 1554 unsigned indexOffset = CheckEven ? 0 : 4; 1555 if (ShuffleKind == 1) // Unary 1556 return isVMerge(N, indexOffset, 0); 1557 else if (ShuffleKind == 0) // Normal 1558 return isVMerge(N, indexOffset, 16); 1559 else 1560 return false; 1561 } 1562 return false; 1563 } 1564 1565 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1566 /// amount, otherwise return -1. 1567 /// The ShuffleKind distinguishes between big-endian operations with two 1568 /// different inputs (0), either-endian operations with two identical inputs 1569 /// (1), and little-endian operations with two different inputs (2). For the 1570 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1571 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1572 SelectionDAG &DAG) { 1573 if (N->getValueType(0) != MVT::v16i8) 1574 return -1; 1575 1576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1577 1578 // Find the first non-undef value in the shuffle mask. 1579 unsigned i; 1580 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1581 /*search*/; 1582 1583 if (i == 16) return -1; // all undef. 1584 1585 // Otherwise, check to see if the rest of the elements are consecutively 1586 // numbered from this value. 1587 unsigned ShiftAmt = SVOp->getMaskElt(i); 1588 if (ShiftAmt < i) return -1; 1589 1590 ShiftAmt -= i; 1591 bool isLE = DAG.getDataLayout().isLittleEndian(); 1592 1593 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1594 // Check the rest of the elements to see if they are consecutive. 1595 for (++i; i != 16; ++i) 1596 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1597 return -1; 1598 } else if (ShuffleKind == 1) { 1599 // Check the rest of the elements to see if they are consecutive. 1600 for (++i; i != 16; ++i) 1601 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1602 return -1; 1603 } else 1604 return -1; 1605 1606 if (isLE) 1607 ShiftAmt = 16 - ShiftAmt; 1608 1609 return ShiftAmt; 1610 } 1611 1612 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1613 /// specifies a splat of a single element that is suitable for input to 1614 /// VSPLTB/VSPLTH/VSPLTW. 1615 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1616 assert(N->getValueType(0) == MVT::v16i8 && 1617 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1618 1619 // The consecutive indices need to specify an element, not part of two 1620 // different elements. So abandon ship early if this isn't the case. 1621 if (N->getMaskElt(0) % EltSize != 0) 1622 return false; 1623 1624 // This is a splat operation if each element of the permute is the same, and 1625 // if the value doesn't reference the second vector. 1626 unsigned ElementBase = N->getMaskElt(0); 1627 1628 // FIXME: Handle UNDEF elements too! 1629 if (ElementBase >= 16) 1630 return false; 1631 1632 // Check that the indices are consecutive, in the case of a multi-byte element 1633 // splatted with a v16i8 mask. 1634 for (unsigned i = 1; i != EltSize; ++i) 1635 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1636 return false; 1637 1638 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1639 if (N->getMaskElt(i) < 0) continue; 1640 for (unsigned j = 0; j != EltSize; ++j) 1641 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1642 return false; 1643 } 1644 return true; 1645 } 1646 1647 /// Check that the mask is shuffling N byte elements. Within each N byte 1648 /// element of the mask, the indices could be either in increasing or 1649 /// decreasing order as long as they are consecutive. 1650 /// \param[in] N the shuffle vector SD Node to analyze 1651 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1652 /// Word/DoubleWord/QuadWord). 1653 /// \param[in] StepLen the delta indices number among the N byte element, if 1654 /// the mask is in increasing/decreasing order then it is 1/-1. 1655 /// \return true iff the mask is shuffling N byte elements. 1656 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1657 int StepLen) { 1658 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1659 "Unexpected element width."); 1660 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1661 1662 unsigned NumOfElem = 16 / Width; 1663 unsigned MaskVal[16]; // Width is never greater than 16 1664 for (unsigned i = 0; i < NumOfElem; ++i) { 1665 MaskVal[0] = N->getMaskElt(i * Width); 1666 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1667 return false; 1668 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1669 return false; 1670 } 1671 1672 for (unsigned int j = 1; j < Width; ++j) { 1673 MaskVal[j] = N->getMaskElt(i * Width + j); 1674 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1675 return false; 1676 } 1677 } 1678 } 1679 1680 return true; 1681 } 1682 1683 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1684 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1685 if (!isNByteElemShuffleMask(N, 4, 1)) 1686 return false; 1687 1688 // Now we look at mask elements 0,4,8,12 1689 unsigned M0 = N->getMaskElt(0) / 4; 1690 unsigned M1 = N->getMaskElt(4) / 4; 1691 unsigned M2 = N->getMaskElt(8) / 4; 1692 unsigned M3 = N->getMaskElt(12) / 4; 1693 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1694 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1695 1696 // Below, let H and L be arbitrary elements of the shuffle mask 1697 // where H is in the range [4,7] and L is in the range [0,3]. 1698 // H, 1, 2, 3 or L, 5, 6, 7 1699 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1700 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1701 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1702 InsertAtByte = IsLE ? 12 : 0; 1703 Swap = M0 < 4; 1704 return true; 1705 } 1706 // 0, H, 2, 3 or 4, L, 6, 7 1707 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1708 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1709 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1710 InsertAtByte = IsLE ? 8 : 4; 1711 Swap = M1 < 4; 1712 return true; 1713 } 1714 // 0, 1, H, 3 or 4, 5, L, 7 1715 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1716 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1717 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1718 InsertAtByte = IsLE ? 4 : 8; 1719 Swap = M2 < 4; 1720 return true; 1721 } 1722 // 0, 1, 2, H or 4, 5, 6, L 1723 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1724 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1725 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1726 InsertAtByte = IsLE ? 0 : 12; 1727 Swap = M3 < 4; 1728 return true; 1729 } 1730 1731 // If both vector operands for the shuffle are the same vector, the mask will 1732 // contain only elements from the first one and the second one will be undef. 1733 if (N->getOperand(1).isUndef()) { 1734 ShiftElts = 0; 1735 Swap = true; 1736 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1737 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1738 InsertAtByte = IsLE ? 12 : 0; 1739 return true; 1740 } 1741 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1742 InsertAtByte = IsLE ? 8 : 4; 1743 return true; 1744 } 1745 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1746 InsertAtByte = IsLE ? 4 : 8; 1747 return true; 1748 } 1749 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1750 InsertAtByte = IsLE ? 0 : 12; 1751 return true; 1752 } 1753 } 1754 1755 return false; 1756 } 1757 1758 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1759 bool &Swap, bool IsLE) { 1760 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1761 // Ensure each byte index of the word is consecutive. 1762 if (!isNByteElemShuffleMask(N, 4, 1)) 1763 return false; 1764 1765 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1766 unsigned M0 = N->getMaskElt(0) / 4; 1767 unsigned M1 = N->getMaskElt(4) / 4; 1768 unsigned M2 = N->getMaskElt(8) / 4; 1769 unsigned M3 = N->getMaskElt(12) / 4; 1770 1771 // If both vector operands for the shuffle are the same vector, the mask will 1772 // contain only elements from the first one and the second one will be undef. 1773 if (N->getOperand(1).isUndef()) { 1774 assert(M0 < 4 && "Indexing into an undef vector?"); 1775 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1776 return false; 1777 1778 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1779 Swap = false; 1780 return true; 1781 } 1782 1783 // Ensure each word index of the ShuffleVector Mask is consecutive. 1784 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1785 return false; 1786 1787 if (IsLE) { 1788 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1789 // Input vectors don't need to be swapped if the leading element 1790 // of the result is one of the 3 left elements of the second vector 1791 // (or if there is no shift to be done at all). 1792 Swap = false; 1793 ShiftElts = (8 - M0) % 8; 1794 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1795 // Input vectors need to be swapped if the leading element 1796 // of the result is one of the 3 left elements of the first vector 1797 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1798 Swap = true; 1799 ShiftElts = (4 - M0) % 4; 1800 } 1801 1802 return true; 1803 } else { // BE 1804 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1805 // Input vectors don't need to be swapped if the leading element 1806 // of the result is one of the 4 elements of the first vector. 1807 Swap = false; 1808 ShiftElts = M0; 1809 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1810 // Input vectors need to be swapped if the leading element 1811 // of the result is one of the 4 elements of the right vector. 1812 Swap = true; 1813 ShiftElts = M0 - 4; 1814 } 1815 1816 return true; 1817 } 1818 } 1819 1820 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1821 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1822 1823 if (!isNByteElemShuffleMask(N, Width, -1)) 1824 return false; 1825 1826 for (int i = 0; i < 16; i += Width) 1827 if (N->getMaskElt(i) != i + Width - 1) 1828 return false; 1829 1830 return true; 1831 } 1832 1833 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1834 return isXXBRShuffleMaskHelper(N, 2); 1835 } 1836 1837 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1838 return isXXBRShuffleMaskHelper(N, 4); 1839 } 1840 1841 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1842 return isXXBRShuffleMaskHelper(N, 8); 1843 } 1844 1845 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1846 return isXXBRShuffleMaskHelper(N, 16); 1847 } 1848 1849 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1850 /// if the inputs to the instruction should be swapped and set \p DM to the 1851 /// value for the immediate. 1852 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1853 /// AND element 0 of the result comes from the first input (LE) or second input 1854 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1855 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1856 /// mask. 1857 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1858 bool &Swap, bool IsLE) { 1859 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1860 1861 // Ensure each byte index of the double word is consecutive. 1862 if (!isNByteElemShuffleMask(N, 8, 1)) 1863 return false; 1864 1865 unsigned M0 = N->getMaskElt(0) / 8; 1866 unsigned M1 = N->getMaskElt(8) / 8; 1867 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1868 1869 // If both vector operands for the shuffle are the same vector, the mask will 1870 // contain only elements from the first one and the second one will be undef. 1871 if (N->getOperand(1).isUndef()) { 1872 if ((M0 | M1) < 2) { 1873 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1874 Swap = false; 1875 return true; 1876 } else 1877 return false; 1878 } 1879 1880 if (IsLE) { 1881 if (M0 > 1 && M1 < 2) { 1882 Swap = false; 1883 } else if (M0 < 2 && M1 > 1) { 1884 M0 = (M0 + 2) % 4; 1885 M1 = (M1 + 2) % 4; 1886 Swap = true; 1887 } else 1888 return false; 1889 1890 // Note: if control flow comes here that means Swap is already set above 1891 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1892 return true; 1893 } else { // BE 1894 if (M0 < 2 && M1 > 1) { 1895 Swap = false; 1896 } else if (M0 > 1 && M1 < 2) { 1897 M0 = (M0 + 2) % 4; 1898 M1 = (M1 + 2) % 4; 1899 Swap = true; 1900 } else 1901 return false; 1902 1903 // Note: if control flow comes here that means Swap is already set above 1904 DM = (M0 << 1) + (M1 & 1); 1905 return true; 1906 } 1907 } 1908 1909 1910 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1911 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1912 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1913 SelectionDAG &DAG) { 1914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1915 assert(isSplatShuffleMask(SVOp, EltSize)); 1916 if (DAG.getDataLayout().isLittleEndian()) 1917 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1918 else 1919 return SVOp->getMaskElt(0) / EltSize; 1920 } 1921 1922 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1923 /// by using a vspltis[bhw] instruction of the specified element size, return 1924 /// the constant being splatted. The ByteSize field indicates the number of 1925 /// bytes of each element [124] -> [bhw]. 1926 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1927 SDValue OpVal(nullptr, 0); 1928 1929 // If ByteSize of the splat is bigger than the element size of the 1930 // build_vector, then we have a case where we are checking for a splat where 1931 // multiple elements of the buildvector are folded together into a single 1932 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1933 unsigned EltSize = 16/N->getNumOperands(); 1934 if (EltSize < ByteSize) { 1935 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1936 SDValue UniquedVals[4]; 1937 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1938 1939 // See if all of the elements in the buildvector agree across. 1940 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1941 if (N->getOperand(i).isUndef()) continue; 1942 // If the element isn't a constant, bail fully out. 1943 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1944 1945 if (!UniquedVals[i&(Multiple-1)].getNode()) 1946 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1947 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1948 return SDValue(); // no match. 1949 } 1950 1951 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1952 // either constant or undef values that are identical for each chunk. See 1953 // if these chunks can form into a larger vspltis*. 1954 1955 // Check to see if all of the leading entries are either 0 or -1. If 1956 // neither, then this won't fit into the immediate field. 1957 bool LeadingZero = true; 1958 bool LeadingOnes = true; 1959 for (unsigned i = 0; i != Multiple-1; ++i) { 1960 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1961 1962 LeadingZero &= isNullConstant(UniquedVals[i]); 1963 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1964 } 1965 // Finally, check the least significant entry. 1966 if (LeadingZero) { 1967 if (!UniquedVals[Multiple-1].getNode()) 1968 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1969 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1970 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1971 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1972 } 1973 if (LeadingOnes) { 1974 if (!UniquedVals[Multiple-1].getNode()) 1975 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1976 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1977 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1978 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1979 } 1980 1981 return SDValue(); 1982 } 1983 1984 // Check to see if this buildvec has a single non-undef value in its elements. 1985 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1986 if (N->getOperand(i).isUndef()) continue; 1987 if (!OpVal.getNode()) 1988 OpVal = N->getOperand(i); 1989 else if (OpVal != N->getOperand(i)) 1990 return SDValue(); 1991 } 1992 1993 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1994 1995 unsigned ValSizeInBytes = EltSize; 1996 uint64_t Value = 0; 1997 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1998 Value = CN->getZExtValue(); 1999 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2000 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2001 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2002 } 2003 2004 // If the splat value is larger than the element value, then we can never do 2005 // this splat. The only case that we could fit the replicated bits into our 2006 // immediate field for would be zero, and we prefer to use vxor for it. 2007 if (ValSizeInBytes < ByteSize) return SDValue(); 2008 2009 // If the element value is larger than the splat value, check if it consists 2010 // of a repeated bit pattern of size ByteSize. 2011 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2012 return SDValue(); 2013 2014 // Properly sign extend the value. 2015 int MaskVal = SignExtend32(Value, ByteSize * 8); 2016 2017 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2018 if (MaskVal == 0) return SDValue(); 2019 2020 // Finally, if this value fits in a 5 bit sext field, return it 2021 if (SignExtend32<5>(MaskVal) == MaskVal) 2022 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2023 return SDValue(); 2024 } 2025 2026 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2027 /// amount, otherwise return -1. 2028 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2029 EVT VT = N->getValueType(0); 2030 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2031 return -1; 2032 2033 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2034 2035 // Find the first non-undef value in the shuffle mask. 2036 unsigned i; 2037 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2038 /*search*/; 2039 2040 if (i == 4) return -1; // all undef. 2041 2042 // Otherwise, check to see if the rest of the elements are consecutively 2043 // numbered from this value. 2044 unsigned ShiftAmt = SVOp->getMaskElt(i); 2045 if (ShiftAmt < i) return -1; 2046 ShiftAmt -= i; 2047 2048 // Check the rest of the elements to see if they are consecutive. 2049 for (++i; i != 4; ++i) 2050 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2051 return -1; 2052 2053 return ShiftAmt; 2054 } 2055 2056 //===----------------------------------------------------------------------===// 2057 // Addressing Mode Selection 2058 //===----------------------------------------------------------------------===// 2059 2060 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2061 /// or 64-bit immediate, and if the value can be accurately represented as a 2062 /// sign extension from a 16-bit value. If so, this returns true and the 2063 /// immediate. 2064 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2065 if (!isa<ConstantSDNode>(N)) 2066 return false; 2067 2068 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2069 if (N->getValueType(0) == MVT::i32) 2070 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2071 else 2072 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2073 } 2074 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2075 return isIntS16Immediate(Op.getNode(), Imm); 2076 } 2077 2078 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2079 /// can be represented as an indexed [r+r] operation. Returns false if it 2080 /// can be more efficiently represented with [r+imm]. 2081 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2082 SDValue &Index, 2083 SelectionDAG &DAG) const { 2084 int16_t imm = 0; 2085 if (N.getOpcode() == ISD::ADD) { 2086 if (isIntS16Immediate(N.getOperand(1), imm)) 2087 return false; // r+i 2088 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2089 return false; // r+i 2090 2091 Base = N.getOperand(0); 2092 Index = N.getOperand(1); 2093 return true; 2094 } else if (N.getOpcode() == ISD::OR) { 2095 if (isIntS16Immediate(N.getOperand(1), imm)) 2096 return false; // r+i can fold it if we can. 2097 2098 // If this is an or of disjoint bitfields, we can codegen this as an add 2099 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2100 // disjoint. 2101 KnownBits LHSKnown, RHSKnown; 2102 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2103 2104 if (LHSKnown.Zero.getBoolValue()) { 2105 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2106 // If all of the bits are known zero on the LHS or RHS, the add won't 2107 // carry. 2108 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2109 Base = N.getOperand(0); 2110 Index = N.getOperand(1); 2111 return true; 2112 } 2113 } 2114 } 2115 2116 return false; 2117 } 2118 2119 // If we happen to be doing an i64 load or store into a stack slot that has 2120 // less than a 4-byte alignment, then the frame-index elimination may need to 2121 // use an indexed load or store instruction (because the offset may not be a 2122 // multiple of 4). The extra register needed to hold the offset comes from the 2123 // register scavenger, and it is possible that the scavenger will need to use 2124 // an emergency spill slot. As a result, we need to make sure that a spill slot 2125 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2126 // stack slot. 2127 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2128 // FIXME: This does not handle the LWA case. 2129 if (VT != MVT::i64) 2130 return; 2131 2132 // NOTE: We'll exclude negative FIs here, which come from argument 2133 // lowering, because there are no known test cases triggering this problem 2134 // using packed structures (or similar). We can remove this exclusion if 2135 // we find such a test case. The reason why this is so test-case driven is 2136 // because this entire 'fixup' is only to prevent crashes (from the 2137 // register scavenger) on not-really-valid inputs. For example, if we have: 2138 // %a = alloca i1 2139 // %b = bitcast i1* %a to i64* 2140 // store i64* a, i64 b 2141 // then the store should really be marked as 'align 1', but is not. If it 2142 // were marked as 'align 1' then the indexed form would have been 2143 // instruction-selected initially, and the problem this 'fixup' is preventing 2144 // won't happen regardless. 2145 if (FrameIdx < 0) 2146 return; 2147 2148 MachineFunction &MF = DAG.getMachineFunction(); 2149 MachineFrameInfo &MFI = MF.getFrameInfo(); 2150 2151 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2152 if (Align >= 4) 2153 return; 2154 2155 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2156 FuncInfo->setHasNonRISpills(); 2157 } 2158 2159 /// Returns true if the address N can be represented by a base register plus 2160 /// a signed 16-bit displacement [r+imm], and if it is not better 2161 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2162 /// displacements that are multiples of that value. 2163 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2164 SDValue &Base, 2165 SelectionDAG &DAG, 2166 unsigned Alignment) const { 2167 // FIXME dl should come from parent load or store, not from address 2168 SDLoc dl(N); 2169 // If this can be more profitably realized as r+r, fail. 2170 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2171 return false; 2172 2173 if (N.getOpcode() == ISD::ADD) { 2174 int16_t imm = 0; 2175 if (isIntS16Immediate(N.getOperand(1), imm) && 2176 (!Alignment || (imm % Alignment) == 0)) { 2177 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2178 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2179 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2180 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2181 } else { 2182 Base = N.getOperand(0); 2183 } 2184 return true; // [r+i] 2185 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2186 // Match LOAD (ADD (X, Lo(G))). 2187 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2188 && "Cannot handle constant offsets yet!"); 2189 Disp = N.getOperand(1).getOperand(0); // The global address. 2190 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2191 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2192 Disp.getOpcode() == ISD::TargetConstantPool || 2193 Disp.getOpcode() == ISD::TargetJumpTable); 2194 Base = N.getOperand(0); 2195 return true; // [&g+r] 2196 } 2197 } else if (N.getOpcode() == ISD::OR) { 2198 int16_t imm = 0; 2199 if (isIntS16Immediate(N.getOperand(1), imm) && 2200 (!Alignment || (imm % Alignment) == 0)) { 2201 // If this is an or of disjoint bitfields, we can codegen this as an add 2202 // (for better address arithmetic) if the LHS and RHS of the OR are 2203 // provably disjoint. 2204 KnownBits LHSKnown; 2205 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2206 2207 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2208 // If all of the bits are known zero on the LHS or RHS, the add won't 2209 // carry. 2210 if (FrameIndexSDNode *FI = 2211 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2212 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2213 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2214 } else { 2215 Base = N.getOperand(0); 2216 } 2217 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2218 return true; 2219 } 2220 } 2221 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2222 // Loading from a constant address. 2223 2224 // If this address fits entirely in a 16-bit sext immediate field, codegen 2225 // this as "d, 0" 2226 int16_t Imm; 2227 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2228 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2229 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2230 CN->getValueType(0)); 2231 return true; 2232 } 2233 2234 // Handle 32-bit sext immediates with LIS + addr mode. 2235 if ((CN->getValueType(0) == MVT::i32 || 2236 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2237 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2238 int Addr = (int)CN->getZExtValue(); 2239 2240 // Otherwise, break this down into an LIS + disp. 2241 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2242 2243 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2244 MVT::i32); 2245 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2246 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2247 return true; 2248 } 2249 } 2250 2251 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2252 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2253 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2254 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2255 } else 2256 Base = N; 2257 return true; // [r+0] 2258 } 2259 2260 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2261 /// represented as an indexed [r+r] operation. 2262 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2263 SDValue &Index, 2264 SelectionDAG &DAG) const { 2265 // Check to see if we can easily represent this as an [r+r] address. This 2266 // will fail if it thinks that the address is more profitably represented as 2267 // reg+imm, e.g. where imm = 0. 2268 if (SelectAddressRegReg(N, Base, Index, DAG)) 2269 return true; 2270 2271 // If the address is the result of an add, we will utilize the fact that the 2272 // address calculation includes an implicit add. However, we can reduce 2273 // register pressure if we do not materialize a constant just for use as the 2274 // index register. We only get rid of the add if it is not an add of a 2275 // value and a 16-bit signed constant and both have a single use. 2276 int16_t imm = 0; 2277 if (N.getOpcode() == ISD::ADD && 2278 (!isIntS16Immediate(N.getOperand(1), imm) || 2279 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2280 Base = N.getOperand(0); 2281 Index = N.getOperand(1); 2282 return true; 2283 } 2284 2285 // Otherwise, do it the hard way, using R0 as the base register. 2286 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2287 N.getValueType()); 2288 Index = N; 2289 return true; 2290 } 2291 2292 /// getPreIndexedAddressParts - returns true by value, base pointer and 2293 /// offset pointer and addressing mode by reference if the node's address 2294 /// can be legally represented as pre-indexed load / store address. 2295 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2296 SDValue &Offset, 2297 ISD::MemIndexedMode &AM, 2298 SelectionDAG &DAG) const { 2299 if (DisablePPCPreinc) return false; 2300 2301 bool isLoad = true; 2302 SDValue Ptr; 2303 EVT VT; 2304 unsigned Alignment; 2305 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2306 Ptr = LD->getBasePtr(); 2307 VT = LD->getMemoryVT(); 2308 Alignment = LD->getAlignment(); 2309 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2310 Ptr = ST->getBasePtr(); 2311 VT = ST->getMemoryVT(); 2312 Alignment = ST->getAlignment(); 2313 isLoad = false; 2314 } else 2315 return false; 2316 2317 // PowerPC doesn't have preinc load/store instructions for vectors (except 2318 // for QPX, which does have preinc r+r forms). 2319 if (VT.isVector()) { 2320 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2321 return false; 2322 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2323 AM = ISD::PRE_INC; 2324 return true; 2325 } 2326 } 2327 2328 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2329 // Common code will reject creating a pre-inc form if the base pointer 2330 // is a frame index, or if N is a store and the base pointer is either 2331 // the same as or a predecessor of the value being stored. Check for 2332 // those situations here, and try with swapped Base/Offset instead. 2333 bool Swap = false; 2334 2335 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2336 Swap = true; 2337 else if (!isLoad) { 2338 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2339 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2340 Swap = true; 2341 } 2342 2343 if (Swap) 2344 std::swap(Base, Offset); 2345 2346 AM = ISD::PRE_INC; 2347 return true; 2348 } 2349 2350 // LDU/STU can only handle immediates that are a multiple of 4. 2351 if (VT != MVT::i64) { 2352 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2353 return false; 2354 } else { 2355 // LDU/STU need an address with at least 4-byte alignment. 2356 if (Alignment < 4) 2357 return false; 2358 2359 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2360 return false; 2361 } 2362 2363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2364 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2365 // sext i32 to i64 when addr mode is r+i. 2366 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2367 LD->getExtensionType() == ISD::SEXTLOAD && 2368 isa<ConstantSDNode>(Offset)) 2369 return false; 2370 } 2371 2372 AM = ISD::PRE_INC; 2373 return true; 2374 } 2375 2376 //===----------------------------------------------------------------------===// 2377 // LowerOperation implementation 2378 //===----------------------------------------------------------------------===// 2379 2380 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2381 /// and LoOpFlags to the target MO flags. 2382 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2383 unsigned &HiOpFlags, unsigned &LoOpFlags, 2384 const GlobalValue *GV = nullptr) { 2385 HiOpFlags = PPCII::MO_HA; 2386 LoOpFlags = PPCII::MO_LO; 2387 2388 // Don't use the pic base if not in PIC relocation model. 2389 if (IsPIC) { 2390 HiOpFlags |= PPCII::MO_PIC_FLAG; 2391 LoOpFlags |= PPCII::MO_PIC_FLAG; 2392 } 2393 2394 // If this is a reference to a global value that requires a non-lazy-ptr, make 2395 // sure that instruction lowering adds it. 2396 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2397 HiOpFlags |= PPCII::MO_NLP_FLAG; 2398 LoOpFlags |= PPCII::MO_NLP_FLAG; 2399 2400 if (GV->hasHiddenVisibility()) { 2401 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2402 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2403 } 2404 } 2405 } 2406 2407 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2408 SelectionDAG &DAG) { 2409 SDLoc DL(HiPart); 2410 EVT PtrVT = HiPart.getValueType(); 2411 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2412 2413 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2414 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2415 2416 // With PIC, the first instruction is actually "GR+hi(&G)". 2417 if (isPIC) 2418 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2419 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2420 2421 // Generate non-pic code that has direct accesses to the constant pool. 2422 // The address of the global is just (hi(&g)+lo(&g)). 2423 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2424 } 2425 2426 static void setUsesTOCBasePtr(MachineFunction &MF) { 2427 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2428 FuncInfo->setUsesTOCBasePtr(); 2429 } 2430 2431 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2432 setUsesTOCBasePtr(DAG.getMachineFunction()); 2433 } 2434 2435 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2436 SDValue GA) { 2437 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2438 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2439 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2440 2441 SDValue Ops[] = { GA, Reg }; 2442 return DAG.getMemIntrinsicNode( 2443 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2444 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2445 MachineMemOperand::MOLoad); 2446 } 2447 2448 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2449 SelectionDAG &DAG) const { 2450 EVT PtrVT = Op.getValueType(); 2451 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2452 const Constant *C = CP->getConstVal(); 2453 2454 // 64-bit SVR4 ABI code is always position-independent. 2455 // The actual address of the GlobalValue is stored in the TOC. 2456 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2457 setUsesTOCBasePtr(DAG); 2458 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2459 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2460 } 2461 2462 unsigned MOHiFlag, MOLoFlag; 2463 bool IsPIC = isPositionIndependent(); 2464 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2465 2466 if (IsPIC && Subtarget.isSVR4ABI()) { 2467 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2468 PPCII::MO_PIC_FLAG); 2469 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2470 } 2471 2472 SDValue CPIHi = 2473 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2474 SDValue CPILo = 2475 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2476 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2477 } 2478 2479 // For 64-bit PowerPC, prefer the more compact relative encodings. 2480 // This trades 32 bits per jump table entry for one or two instructions 2481 // on the jump site. 2482 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2483 if (isJumpTableRelative()) 2484 return MachineJumpTableInfo::EK_LabelDifference32; 2485 2486 return TargetLowering::getJumpTableEncoding(); 2487 } 2488 2489 bool PPCTargetLowering::isJumpTableRelative() const { 2490 if (Subtarget.isPPC64()) 2491 return true; 2492 return TargetLowering::isJumpTableRelative(); 2493 } 2494 2495 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2496 SelectionDAG &DAG) const { 2497 if (!Subtarget.isPPC64()) 2498 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2499 2500 switch (getTargetMachine().getCodeModel()) { 2501 case CodeModel::Small: 2502 case CodeModel::Medium: 2503 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2504 default: 2505 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2506 getPointerTy(DAG.getDataLayout())); 2507 } 2508 } 2509 2510 const MCExpr * 2511 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2512 unsigned JTI, 2513 MCContext &Ctx) const { 2514 if (!Subtarget.isPPC64()) 2515 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2516 2517 switch (getTargetMachine().getCodeModel()) { 2518 case CodeModel::Small: 2519 case CodeModel::Medium: 2520 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2521 default: 2522 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2523 } 2524 } 2525 2526 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2527 EVT PtrVT = Op.getValueType(); 2528 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2529 2530 // 64-bit SVR4 ABI code is always position-independent. 2531 // The actual address of the GlobalValue is stored in the TOC. 2532 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2533 setUsesTOCBasePtr(DAG); 2534 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2535 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2536 } 2537 2538 unsigned MOHiFlag, MOLoFlag; 2539 bool IsPIC = isPositionIndependent(); 2540 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2541 2542 if (IsPIC && Subtarget.isSVR4ABI()) { 2543 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2544 PPCII::MO_PIC_FLAG); 2545 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2546 } 2547 2548 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2549 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2550 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2551 } 2552 2553 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2554 SelectionDAG &DAG) const { 2555 EVT PtrVT = Op.getValueType(); 2556 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2557 const BlockAddress *BA = BASDN->getBlockAddress(); 2558 2559 // 64-bit SVR4 ABI code is always position-independent. 2560 // The actual BlockAddress is stored in the TOC. 2561 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2562 setUsesTOCBasePtr(DAG); 2563 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2564 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2565 } 2566 2567 unsigned MOHiFlag, MOLoFlag; 2568 bool IsPIC = isPositionIndependent(); 2569 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2570 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2571 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2572 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2573 } 2574 2575 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2576 SelectionDAG &DAG) const { 2577 // FIXME: TLS addresses currently use medium model code sequences, 2578 // which is the most useful form. Eventually support for small and 2579 // large models could be added if users need it, at the cost of 2580 // additional complexity. 2581 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2582 if (DAG.getTarget().useEmulatedTLS()) 2583 return LowerToTLSEmulatedModel(GA, DAG); 2584 2585 SDLoc dl(GA); 2586 const GlobalValue *GV = GA->getGlobal(); 2587 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2588 bool is64bit = Subtarget.isPPC64(); 2589 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2590 PICLevel::Level picLevel = M->getPICLevel(); 2591 2592 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2593 2594 if (Model == TLSModel::LocalExec) { 2595 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2596 PPCII::MO_TPREL_HA); 2597 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2598 PPCII::MO_TPREL_LO); 2599 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2600 : DAG.getRegister(PPC::R2, MVT::i32); 2601 2602 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2603 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2604 } 2605 2606 if (Model == TLSModel::InitialExec) { 2607 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2608 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2609 PPCII::MO_TLS); 2610 SDValue GOTPtr; 2611 if (is64bit) { 2612 setUsesTOCBasePtr(DAG); 2613 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2614 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2615 PtrVT, GOTReg, TGA); 2616 } else 2617 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2618 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2619 PtrVT, TGA, GOTPtr); 2620 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2621 } 2622 2623 if (Model == TLSModel::GeneralDynamic) { 2624 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2625 SDValue GOTPtr; 2626 if (is64bit) { 2627 setUsesTOCBasePtr(DAG); 2628 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2629 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2630 GOTReg, TGA); 2631 } else { 2632 if (picLevel == PICLevel::SmallPIC) 2633 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2634 else 2635 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2636 } 2637 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2638 GOTPtr, TGA, TGA); 2639 } 2640 2641 if (Model == TLSModel::LocalDynamic) { 2642 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2643 SDValue GOTPtr; 2644 if (is64bit) { 2645 setUsesTOCBasePtr(DAG); 2646 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2647 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2648 GOTReg, TGA); 2649 } else { 2650 if (picLevel == PICLevel::SmallPIC) 2651 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2652 else 2653 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2654 } 2655 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2656 PtrVT, GOTPtr, TGA, TGA); 2657 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2658 PtrVT, TLSAddr, TGA); 2659 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2660 } 2661 2662 llvm_unreachable("Unknown TLS model!"); 2663 } 2664 2665 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2666 SelectionDAG &DAG) const { 2667 EVT PtrVT = Op.getValueType(); 2668 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2669 SDLoc DL(GSDN); 2670 const GlobalValue *GV = GSDN->getGlobal(); 2671 2672 // 64-bit SVR4 ABI code is always position-independent. 2673 // The actual address of the GlobalValue is stored in the TOC. 2674 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2675 setUsesTOCBasePtr(DAG); 2676 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2677 return getTOCEntry(DAG, DL, true, GA); 2678 } 2679 2680 unsigned MOHiFlag, MOLoFlag; 2681 bool IsPIC = isPositionIndependent(); 2682 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2683 2684 if (IsPIC && Subtarget.isSVR4ABI()) { 2685 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2686 GSDN->getOffset(), 2687 PPCII::MO_PIC_FLAG); 2688 return getTOCEntry(DAG, DL, false, GA); 2689 } 2690 2691 SDValue GAHi = 2692 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2693 SDValue GALo = 2694 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2695 2696 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2697 2698 // If the global reference is actually to a non-lazy-pointer, we have to do an 2699 // extra load to get the address of the global. 2700 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2701 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2702 return Ptr; 2703 } 2704 2705 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2706 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2707 SDLoc dl(Op); 2708 2709 if (Op.getValueType() == MVT::v2i64) { 2710 // When the operands themselves are v2i64 values, we need to do something 2711 // special because VSX has no underlying comparison operations for these. 2712 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2713 // Equality can be handled by casting to the legal type for Altivec 2714 // comparisons, everything else needs to be expanded. 2715 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2716 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2717 DAG.getSetCC(dl, MVT::v4i32, 2718 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2719 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2720 CC)); 2721 } 2722 2723 return SDValue(); 2724 } 2725 2726 // We handle most of these in the usual way. 2727 return Op; 2728 } 2729 2730 // If we're comparing for equality to zero, expose the fact that this is 2731 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2732 // fold the new nodes. 2733 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2734 return V; 2735 2736 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2737 // Leave comparisons against 0 and -1 alone for now, since they're usually 2738 // optimized. FIXME: revisit this when we can custom lower all setcc 2739 // optimizations. 2740 if (C->isAllOnesValue() || C->isNullValue()) 2741 return SDValue(); 2742 } 2743 2744 // If we have an integer seteq/setne, turn it into a compare against zero 2745 // by xor'ing the rhs with the lhs, which is faster than setting a 2746 // condition register, reading it back out, and masking the correct bit. The 2747 // normal approach here uses sub to do this instead of xor. Using xor exposes 2748 // the result to other bit-twiddling opportunities. 2749 EVT LHSVT = Op.getOperand(0).getValueType(); 2750 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2751 EVT VT = Op.getValueType(); 2752 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2753 Op.getOperand(1)); 2754 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2755 } 2756 return SDValue(); 2757 } 2758 2759 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2760 SDNode *Node = Op.getNode(); 2761 EVT VT = Node->getValueType(0); 2762 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2763 SDValue InChain = Node->getOperand(0); 2764 SDValue VAListPtr = Node->getOperand(1); 2765 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2766 SDLoc dl(Node); 2767 2768 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2769 2770 // gpr_index 2771 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2772 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2773 InChain = GprIndex.getValue(1); 2774 2775 if (VT == MVT::i64) { 2776 // Check if GprIndex is even 2777 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2778 DAG.getConstant(1, dl, MVT::i32)); 2779 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2780 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2781 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2782 DAG.getConstant(1, dl, MVT::i32)); 2783 // Align GprIndex to be even if it isn't 2784 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2785 GprIndex); 2786 } 2787 2788 // fpr index is 1 byte after gpr 2789 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2790 DAG.getConstant(1, dl, MVT::i32)); 2791 2792 // fpr 2793 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2794 FprPtr, MachinePointerInfo(SV), MVT::i8); 2795 InChain = FprIndex.getValue(1); 2796 2797 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2798 DAG.getConstant(8, dl, MVT::i32)); 2799 2800 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2801 DAG.getConstant(4, dl, MVT::i32)); 2802 2803 // areas 2804 SDValue OverflowArea = 2805 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2806 InChain = OverflowArea.getValue(1); 2807 2808 SDValue RegSaveArea = 2809 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2810 InChain = RegSaveArea.getValue(1); 2811 2812 // select overflow_area if index > 8 2813 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2814 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2815 2816 // adjustment constant gpr_index * 4/8 2817 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2818 VT.isInteger() ? GprIndex : FprIndex, 2819 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2820 MVT::i32)); 2821 2822 // OurReg = RegSaveArea + RegConstant 2823 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2824 RegConstant); 2825 2826 // Floating types are 32 bytes into RegSaveArea 2827 if (VT.isFloatingPoint()) 2828 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2829 DAG.getConstant(32, dl, MVT::i32)); 2830 2831 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2832 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2833 VT.isInteger() ? GprIndex : FprIndex, 2834 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2835 MVT::i32)); 2836 2837 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2838 VT.isInteger() ? VAListPtr : FprPtr, 2839 MachinePointerInfo(SV), MVT::i8); 2840 2841 // determine if we should load from reg_save_area or overflow_area 2842 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2843 2844 // increase overflow_area by 4/8 if gpr/fpr > 8 2845 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2846 DAG.getConstant(VT.isInteger() ? 4 : 8, 2847 dl, MVT::i32)); 2848 2849 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2850 OverflowAreaPlusN); 2851 2852 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2853 MachinePointerInfo(), MVT::i32); 2854 2855 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2856 } 2857 2858 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2859 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2860 2861 // We have to copy the entire va_list struct: 2862 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2863 return DAG.getMemcpy(Op.getOperand(0), Op, 2864 Op.getOperand(1), Op.getOperand(2), 2865 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2866 false, MachinePointerInfo(), MachinePointerInfo()); 2867 } 2868 2869 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2870 SelectionDAG &DAG) const { 2871 return Op.getOperand(0); 2872 } 2873 2874 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2875 SelectionDAG &DAG) const { 2876 SDValue Chain = Op.getOperand(0); 2877 SDValue Trmp = Op.getOperand(1); // trampoline 2878 SDValue FPtr = Op.getOperand(2); // nested function 2879 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2880 SDLoc dl(Op); 2881 2882 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2883 bool isPPC64 = (PtrVT == MVT::i64); 2884 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2885 2886 TargetLowering::ArgListTy Args; 2887 TargetLowering::ArgListEntry Entry; 2888 2889 Entry.Ty = IntPtrTy; 2890 Entry.Node = Trmp; Args.push_back(Entry); 2891 2892 // TrampSize == (isPPC64 ? 48 : 40); 2893 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2894 isPPC64 ? MVT::i64 : MVT::i32); 2895 Args.push_back(Entry); 2896 2897 Entry.Node = FPtr; Args.push_back(Entry); 2898 Entry.Node = Nest; Args.push_back(Entry); 2899 2900 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2901 TargetLowering::CallLoweringInfo CLI(DAG); 2902 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2903 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2904 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2905 2906 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2907 return CallResult.second; 2908 } 2909 2910 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2911 MachineFunction &MF = DAG.getMachineFunction(); 2912 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2913 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2914 2915 SDLoc dl(Op); 2916 2917 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2918 // vastart just stores the address of the VarArgsFrameIndex slot into the 2919 // memory location argument. 2920 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2921 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2922 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2923 MachinePointerInfo(SV)); 2924 } 2925 2926 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2927 // We suppose the given va_list is already allocated. 2928 // 2929 // typedef struct { 2930 // char gpr; /* index into the array of 8 GPRs 2931 // * stored in the register save area 2932 // * gpr=0 corresponds to r3, 2933 // * gpr=1 to r4, etc. 2934 // */ 2935 // char fpr; /* index into the array of 8 FPRs 2936 // * stored in the register save area 2937 // * fpr=0 corresponds to f1, 2938 // * fpr=1 to f2, etc. 2939 // */ 2940 // char *overflow_arg_area; 2941 // /* location on stack that holds 2942 // * the next overflow argument 2943 // */ 2944 // char *reg_save_area; 2945 // /* where r3:r10 and f1:f8 (if saved) 2946 // * are stored 2947 // */ 2948 // } va_list[1]; 2949 2950 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2951 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2952 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2953 PtrVT); 2954 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2955 PtrVT); 2956 2957 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2958 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2959 2960 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2961 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2962 2963 uint64_t FPROffset = 1; 2964 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2965 2966 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2967 2968 // Store first byte : number of int regs 2969 SDValue firstStore = 2970 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2971 MachinePointerInfo(SV), MVT::i8); 2972 uint64_t nextOffset = FPROffset; 2973 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2974 ConstFPROffset); 2975 2976 // Store second byte : number of float regs 2977 SDValue secondStore = 2978 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2979 MachinePointerInfo(SV, nextOffset), MVT::i8); 2980 nextOffset += StackOffset; 2981 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2982 2983 // Store second word : arguments given on stack 2984 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2985 MachinePointerInfo(SV, nextOffset)); 2986 nextOffset += FrameOffset; 2987 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2988 2989 // Store third word : arguments given in registers 2990 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2991 MachinePointerInfo(SV, nextOffset)); 2992 } 2993 2994 #include "PPCGenCallingConv.inc" 2995 2996 // Function whose sole purpose is to kill compiler warnings 2997 // stemming from unused functions included from PPCGenCallingConv.inc. 2998 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2999 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 3000 } 3001 3002 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 3003 CCValAssign::LocInfo &LocInfo, 3004 ISD::ArgFlagsTy &ArgFlags, 3005 CCState &State) { 3006 return true; 3007 } 3008 3009 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3010 MVT &LocVT, 3011 CCValAssign::LocInfo &LocInfo, 3012 ISD::ArgFlagsTy &ArgFlags, 3013 CCState &State) { 3014 static const MCPhysReg ArgRegs[] = { 3015 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3016 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3017 }; 3018 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3019 3020 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3021 3022 // Skip one register if the first unallocated register has an even register 3023 // number and there are still argument registers available which have not been 3024 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3025 // need to skip a register if RegNum is odd. 3026 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3027 State.AllocateReg(ArgRegs[RegNum]); 3028 } 3029 3030 // Always return false here, as this function only makes sure that the first 3031 // unallocated register has an odd register number and does not actually 3032 // allocate a register for the current argument. 3033 return false; 3034 } 3035 3036 bool 3037 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3038 MVT &LocVT, 3039 CCValAssign::LocInfo &LocInfo, 3040 ISD::ArgFlagsTy &ArgFlags, 3041 CCState &State) { 3042 static const MCPhysReg ArgRegs[] = { 3043 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3044 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3045 }; 3046 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3047 3048 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3049 int RegsLeft = NumArgRegs - RegNum; 3050 3051 // Skip if there is not enough registers left for long double type (4 gpr regs 3052 // in soft float mode) and put long double argument on the stack. 3053 if (RegNum != NumArgRegs && RegsLeft < 4) { 3054 for (int i = 0; i < RegsLeft; i++) { 3055 State.AllocateReg(ArgRegs[RegNum + i]); 3056 } 3057 } 3058 3059 return false; 3060 } 3061 3062 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3063 MVT &LocVT, 3064 CCValAssign::LocInfo &LocInfo, 3065 ISD::ArgFlagsTy &ArgFlags, 3066 CCState &State) { 3067 static const MCPhysReg ArgRegs[] = { 3068 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3069 PPC::F8 3070 }; 3071 3072 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3073 3074 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3075 3076 // If there is only one Floating-point register left we need to put both f64 3077 // values of a split ppc_fp128 value on the stack. 3078 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3079 State.AllocateReg(ArgRegs[RegNum]); 3080 } 3081 3082 // Always return false here, as this function only makes sure that the two f64 3083 // values a ppc_fp128 value is split into are both passed in registers or both 3084 // passed on the stack and does not actually allocate a register for the 3085 // current argument. 3086 return false; 3087 } 3088 3089 /// FPR - The set of FP registers that should be allocated for arguments, 3090 /// on Darwin. 3091 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3092 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3093 PPC::F11, PPC::F12, PPC::F13}; 3094 3095 /// QFPR - The set of QPX registers that should be allocated for arguments. 3096 static const MCPhysReg QFPR[] = { 3097 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3098 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3099 3100 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3101 /// the stack. 3102 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3103 unsigned PtrByteSize) { 3104 unsigned ArgSize = ArgVT.getStoreSize(); 3105 if (Flags.isByVal()) 3106 ArgSize = Flags.getByValSize(); 3107 3108 // Round up to multiples of the pointer size, except for array members, 3109 // which are always packed. 3110 if (!Flags.isInConsecutiveRegs()) 3111 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3112 3113 return ArgSize; 3114 } 3115 3116 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3117 /// on the stack. 3118 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3119 ISD::ArgFlagsTy Flags, 3120 unsigned PtrByteSize) { 3121 unsigned Align = PtrByteSize; 3122 3123 // Altivec parameters are padded to a 16 byte boundary. 3124 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3125 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3126 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3127 ArgVT == MVT::v1i128) 3128 Align = 16; 3129 // QPX vector types stored in double-precision are padded to a 32 byte 3130 // boundary. 3131 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3132 Align = 32; 3133 3134 // ByVal parameters are aligned as requested. 3135 if (Flags.isByVal()) { 3136 unsigned BVAlign = Flags.getByValAlign(); 3137 if (BVAlign > PtrByteSize) { 3138 if (BVAlign % PtrByteSize != 0) 3139 llvm_unreachable( 3140 "ByVal alignment is not a multiple of the pointer size"); 3141 3142 Align = BVAlign; 3143 } 3144 } 3145 3146 // Array members are always packed to their original alignment. 3147 if (Flags.isInConsecutiveRegs()) { 3148 // If the array member was split into multiple registers, the first 3149 // needs to be aligned to the size of the full type. (Except for 3150 // ppcf128, which is only aligned as its f64 components.) 3151 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3152 Align = OrigVT.getStoreSize(); 3153 else 3154 Align = ArgVT.getStoreSize(); 3155 } 3156 3157 return Align; 3158 } 3159 3160 /// CalculateStackSlotUsed - Return whether this argument will use its 3161 /// stack slot (instead of being passed in registers). ArgOffset, 3162 /// AvailableFPRs, and AvailableVRs must hold the current argument 3163 /// position, and will be updated to account for this argument. 3164 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3165 ISD::ArgFlagsTy Flags, 3166 unsigned PtrByteSize, 3167 unsigned LinkageSize, 3168 unsigned ParamAreaSize, 3169 unsigned &ArgOffset, 3170 unsigned &AvailableFPRs, 3171 unsigned &AvailableVRs, bool HasQPX) { 3172 bool UseMemory = false; 3173 3174 // Respect alignment of argument on the stack. 3175 unsigned Align = 3176 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3177 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3178 // If there's no space left in the argument save area, we must 3179 // use memory (this check also catches zero-sized arguments). 3180 if (ArgOffset >= LinkageSize + ParamAreaSize) 3181 UseMemory = true; 3182 3183 // Allocate argument on the stack. 3184 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3185 if (Flags.isInConsecutiveRegsLast()) 3186 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3187 // If we overran the argument save area, we must use memory 3188 // (this check catches arguments passed partially in memory) 3189 if (ArgOffset > LinkageSize + ParamAreaSize) 3190 UseMemory = true; 3191 3192 // However, if the argument is actually passed in an FPR or a VR, 3193 // we don't use memory after all. 3194 if (!Flags.isByVal()) { 3195 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3196 // QPX registers overlap with the scalar FP registers. 3197 (HasQPX && (ArgVT == MVT::v4f32 || 3198 ArgVT == MVT::v4f64 || 3199 ArgVT == MVT::v4i1))) 3200 if (AvailableFPRs > 0) { 3201 --AvailableFPRs; 3202 return false; 3203 } 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) 3208 if (AvailableVRs > 0) { 3209 --AvailableVRs; 3210 return false; 3211 } 3212 } 3213 3214 return UseMemory; 3215 } 3216 3217 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3218 /// ensure minimum alignment required for target. 3219 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3220 unsigned NumBytes) { 3221 unsigned TargetAlign = Lowering->getStackAlignment(); 3222 unsigned AlignMask = TargetAlign - 1; 3223 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3224 return NumBytes; 3225 } 3226 3227 SDValue PPCTargetLowering::LowerFormalArguments( 3228 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3229 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3230 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3231 if (Subtarget.isSVR4ABI()) { 3232 if (Subtarget.isPPC64()) 3233 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3234 dl, DAG, InVals); 3235 else 3236 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3237 dl, DAG, InVals); 3238 } else { 3239 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3240 dl, DAG, InVals); 3241 } 3242 } 3243 3244 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3245 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3246 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3247 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3248 3249 // 32-bit SVR4 ABI Stack Frame Layout: 3250 // +-----------------------------------+ 3251 // +--> | Back chain | 3252 // | +-----------------------------------+ 3253 // | | Floating-point register save area | 3254 // | +-----------------------------------+ 3255 // | | General register save area | 3256 // | +-----------------------------------+ 3257 // | | CR save word | 3258 // | +-----------------------------------+ 3259 // | | VRSAVE save word | 3260 // | +-----------------------------------+ 3261 // | | Alignment padding | 3262 // | +-----------------------------------+ 3263 // | | Vector register save area | 3264 // | +-----------------------------------+ 3265 // | | Local variable space | 3266 // | +-----------------------------------+ 3267 // | | Parameter list area | 3268 // | +-----------------------------------+ 3269 // | | LR save word | 3270 // | +-----------------------------------+ 3271 // SP--> +--- | Back chain | 3272 // +-----------------------------------+ 3273 // 3274 // Specifications: 3275 // System V Application Binary Interface PowerPC Processor Supplement 3276 // AltiVec Technology Programming Interface Manual 3277 3278 MachineFunction &MF = DAG.getMachineFunction(); 3279 MachineFrameInfo &MFI = MF.getFrameInfo(); 3280 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3281 3282 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3283 // Potential tail calls could cause overwriting of argument stack slots. 3284 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3285 (CallConv == CallingConv::Fast)); 3286 unsigned PtrByteSize = 4; 3287 3288 // Assign locations to all of the incoming arguments. 3289 SmallVector<CCValAssign, 16> ArgLocs; 3290 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3291 *DAG.getContext()); 3292 3293 // Reserve space for the linkage area on the stack. 3294 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3295 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3296 if (useSoftFloat()) 3297 CCInfo.PreAnalyzeFormalArguments(Ins); 3298 3299 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3300 CCInfo.clearWasPPCF128(); 3301 3302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3303 CCValAssign &VA = ArgLocs[i]; 3304 3305 // Arguments stored in registers. 3306 if (VA.isRegLoc()) { 3307 const TargetRegisterClass *RC; 3308 EVT ValVT = VA.getValVT(); 3309 3310 switch (ValVT.getSimpleVT().SimpleTy) { 3311 default: 3312 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3313 case MVT::i1: 3314 case MVT::i32: 3315 RC = &PPC::GPRCRegClass; 3316 break; 3317 case MVT::f32: 3318 if (Subtarget.hasP8Vector()) 3319 RC = &PPC::VSSRCRegClass; 3320 else 3321 RC = &PPC::F4RCRegClass; 3322 break; 3323 case MVT::f64: 3324 if (Subtarget.hasVSX()) 3325 RC = &PPC::VSFRCRegClass; 3326 else 3327 RC = &PPC::F8RCRegClass; 3328 break; 3329 case MVT::v16i8: 3330 case MVT::v8i16: 3331 case MVT::v4i32: 3332 RC = &PPC::VRRCRegClass; 3333 break; 3334 case MVT::v4f32: 3335 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3336 break; 3337 case MVT::v2f64: 3338 case MVT::v2i64: 3339 RC = &PPC::VRRCRegClass; 3340 break; 3341 case MVT::v4f64: 3342 RC = &PPC::QFRCRegClass; 3343 break; 3344 case MVT::v4i1: 3345 RC = &PPC::QBRCRegClass; 3346 break; 3347 } 3348 3349 // Transform the arguments stored in physical registers into virtual ones. 3350 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3351 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3352 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3353 3354 if (ValVT == MVT::i1) 3355 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3356 3357 InVals.push_back(ArgValue); 3358 } else { 3359 // Argument stored in memory. 3360 assert(VA.isMemLoc()); 3361 3362 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3363 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3364 isImmutable); 3365 3366 // Create load nodes to retrieve arguments from the stack. 3367 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3368 InVals.push_back( 3369 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3370 } 3371 } 3372 3373 // Assign locations to all of the incoming aggregate by value arguments. 3374 // Aggregates passed by value are stored in the local variable space of the 3375 // caller's stack frame, right above the parameter list area. 3376 SmallVector<CCValAssign, 16> ByValArgLocs; 3377 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3378 ByValArgLocs, *DAG.getContext()); 3379 3380 // Reserve stack space for the allocations in CCInfo. 3381 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3382 3383 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3384 3385 // Area that is at least reserved in the caller of this function. 3386 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3387 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3388 3389 // Set the size that is at least reserved in caller of this function. Tail 3390 // call optimized function's reserved stack space needs to be aligned so that 3391 // taking the difference between two stack areas will result in an aligned 3392 // stack. 3393 MinReservedArea = 3394 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3395 FuncInfo->setMinReservedArea(MinReservedArea); 3396 3397 SmallVector<SDValue, 8> MemOps; 3398 3399 // If the function takes variable number of arguments, make a frame index for 3400 // the start of the first vararg value... for expansion of llvm.va_start. 3401 if (isVarArg) { 3402 static const MCPhysReg GPArgRegs[] = { 3403 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3404 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3405 }; 3406 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3407 3408 static const MCPhysReg FPArgRegs[] = { 3409 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3410 PPC::F8 3411 }; 3412 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3413 3414 if (useSoftFloat()) 3415 NumFPArgRegs = 0; 3416 3417 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3418 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3419 3420 // Make room for NumGPArgRegs and NumFPArgRegs. 3421 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3422 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3423 3424 FuncInfo->setVarArgsStackOffset( 3425 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3426 CCInfo.getNextStackOffset(), true)); 3427 3428 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3429 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3430 3431 // The fixed integer arguments of a variadic function are stored to the 3432 // VarArgsFrameIndex on the stack so that they may be loaded by 3433 // dereferencing the result of va_next. 3434 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3435 // Get an existing live-in vreg, or add a new one. 3436 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3437 if (!VReg) 3438 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3439 3440 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3441 SDValue Store = 3442 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3443 MemOps.push_back(Store); 3444 // Increment the address by four for the next argument to store 3445 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3446 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3447 } 3448 3449 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3450 // is set. 3451 // The double arguments are stored to the VarArgsFrameIndex 3452 // on the stack. 3453 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3454 // Get an existing live-in vreg, or add a new one. 3455 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3456 if (!VReg) 3457 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3458 3459 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3460 SDValue Store = 3461 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3462 MemOps.push_back(Store); 3463 // Increment the address by eight for the next argument to store 3464 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3465 PtrVT); 3466 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3467 } 3468 } 3469 3470 if (!MemOps.empty()) 3471 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3472 3473 return Chain; 3474 } 3475 3476 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3477 // value to MVT::i64 and then truncate to the correct register size. 3478 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3479 EVT ObjectVT, SelectionDAG &DAG, 3480 SDValue ArgVal, 3481 const SDLoc &dl) const { 3482 if (Flags.isSExt()) 3483 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3484 DAG.getValueType(ObjectVT)); 3485 else if (Flags.isZExt()) 3486 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3487 DAG.getValueType(ObjectVT)); 3488 3489 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3490 } 3491 3492 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3493 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3494 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3495 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3496 // TODO: add description of PPC stack frame format, or at least some docs. 3497 // 3498 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3499 bool isLittleEndian = Subtarget.isLittleEndian(); 3500 MachineFunction &MF = DAG.getMachineFunction(); 3501 MachineFrameInfo &MFI = MF.getFrameInfo(); 3502 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3503 3504 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3505 "fastcc not supported on varargs functions"); 3506 3507 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3508 // Potential tail calls could cause overwriting of argument stack slots. 3509 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3510 (CallConv == CallingConv::Fast)); 3511 unsigned PtrByteSize = 8; 3512 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3513 3514 static const MCPhysReg GPR[] = { 3515 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3516 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3517 }; 3518 static const MCPhysReg VR[] = { 3519 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3520 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3521 }; 3522 3523 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3524 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3525 const unsigned Num_VR_Regs = array_lengthof(VR); 3526 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3527 3528 // Do a first pass over the arguments to determine whether the ABI 3529 // guarantees that our caller has allocated the parameter save area 3530 // on its stack frame. In the ELFv1 ABI, this is always the case; 3531 // in the ELFv2 ABI, it is true if this is a vararg function or if 3532 // any parameter is located in a stack slot. 3533 3534 bool HasParameterArea = !isELFv2ABI || isVarArg; 3535 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3536 unsigned NumBytes = LinkageSize; 3537 unsigned AvailableFPRs = Num_FPR_Regs; 3538 unsigned AvailableVRs = Num_VR_Regs; 3539 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3540 if (Ins[i].Flags.isNest()) 3541 continue; 3542 3543 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3544 PtrByteSize, LinkageSize, ParamAreaSize, 3545 NumBytes, AvailableFPRs, AvailableVRs, 3546 Subtarget.hasQPX())) 3547 HasParameterArea = true; 3548 } 3549 3550 // Add DAG nodes to load the arguments or copy them out of registers. On 3551 // entry to a function on PPC, the arguments start after the linkage area, 3552 // although the first ones are often in registers. 3553 3554 unsigned ArgOffset = LinkageSize; 3555 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3556 unsigned &QFPR_idx = FPR_idx; 3557 SmallVector<SDValue, 8> MemOps; 3558 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3559 unsigned CurArgIdx = 0; 3560 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3561 SDValue ArgVal; 3562 bool needsLoad = false; 3563 EVT ObjectVT = Ins[ArgNo].VT; 3564 EVT OrigVT = Ins[ArgNo].ArgVT; 3565 unsigned ObjSize = ObjectVT.getStoreSize(); 3566 unsigned ArgSize = ObjSize; 3567 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3568 if (Ins[ArgNo].isOrigArg()) { 3569 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3570 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3571 } 3572 // We re-align the argument offset for each argument, except when using the 3573 // fast calling convention, when we need to make sure we do that only when 3574 // we'll actually use a stack slot. 3575 unsigned CurArgOffset, Align; 3576 auto ComputeArgOffset = [&]() { 3577 /* Respect alignment of argument on the stack. */ 3578 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3579 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3580 CurArgOffset = ArgOffset; 3581 }; 3582 3583 if (CallConv != CallingConv::Fast) { 3584 ComputeArgOffset(); 3585 3586 /* Compute GPR index associated with argument offset. */ 3587 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3588 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3589 } 3590 3591 // FIXME the codegen can be much improved in some cases. 3592 // We do not have to keep everything in memory. 3593 if (Flags.isByVal()) { 3594 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3595 3596 if (CallConv == CallingConv::Fast) 3597 ComputeArgOffset(); 3598 3599 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3600 ObjSize = Flags.getByValSize(); 3601 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3602 // Empty aggregate parameters do not take up registers. Examples: 3603 // struct { } a; 3604 // union { } b; 3605 // int c[0]; 3606 // etc. However, we have to provide a place-holder in InVals, so 3607 // pretend we have an 8-byte item at the current address for that 3608 // purpose. 3609 if (!ObjSize) { 3610 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3611 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3612 InVals.push_back(FIN); 3613 continue; 3614 } 3615 3616 // Create a stack object covering all stack doublewords occupied 3617 // by the argument. If the argument is (fully or partially) on 3618 // the stack, or if the argument is fully in registers but the 3619 // caller has allocated the parameter save anyway, we can refer 3620 // directly to the caller's stack frame. Otherwise, create a 3621 // local copy in our own frame. 3622 int FI; 3623 if (HasParameterArea || 3624 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3625 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3626 else 3627 FI = MFI.CreateStackObject(ArgSize, Align, false); 3628 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3629 3630 // Handle aggregates smaller than 8 bytes. 3631 if (ObjSize < PtrByteSize) { 3632 // The value of the object is its address, which differs from the 3633 // address of the enclosing doubleword on big-endian systems. 3634 SDValue Arg = FIN; 3635 if (!isLittleEndian) { 3636 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3637 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3638 } 3639 InVals.push_back(Arg); 3640 3641 if (GPR_idx != Num_GPR_Regs) { 3642 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3643 FuncInfo->addLiveInAttr(VReg, Flags); 3644 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3645 SDValue Store; 3646 3647 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3648 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3649 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3650 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3651 MachinePointerInfo(&*FuncArg), ObjType); 3652 } else { 3653 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3654 // store the whole register as-is to the parameter save area 3655 // slot. 3656 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3657 MachinePointerInfo(&*FuncArg)); 3658 } 3659 3660 MemOps.push_back(Store); 3661 } 3662 // Whether we copied from a register or not, advance the offset 3663 // into the parameter save area by a full doubleword. 3664 ArgOffset += PtrByteSize; 3665 continue; 3666 } 3667 3668 // The value of the object is its address, which is the address of 3669 // its first stack doubleword. 3670 InVals.push_back(FIN); 3671 3672 // Store whatever pieces of the object are in registers to memory. 3673 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3674 if (GPR_idx == Num_GPR_Regs) 3675 break; 3676 3677 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3678 FuncInfo->addLiveInAttr(VReg, Flags); 3679 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3680 SDValue Addr = FIN; 3681 if (j) { 3682 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3683 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3684 } 3685 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3686 MachinePointerInfo(&*FuncArg, j)); 3687 MemOps.push_back(Store); 3688 ++GPR_idx; 3689 } 3690 ArgOffset += ArgSize; 3691 continue; 3692 } 3693 3694 switch (ObjectVT.getSimpleVT().SimpleTy) { 3695 default: llvm_unreachable("Unhandled argument type!"); 3696 case MVT::i1: 3697 case MVT::i32: 3698 case MVT::i64: 3699 if (Flags.isNest()) { 3700 // The 'nest' parameter, if any, is passed in R11. 3701 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3702 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3703 3704 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3705 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3706 3707 break; 3708 } 3709 3710 // These can be scalar arguments or elements of an integer array type 3711 // passed directly. Clang may use those instead of "byval" aggregate 3712 // types to avoid forcing arguments to memory unnecessarily. 3713 if (GPR_idx != Num_GPR_Regs) { 3714 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3715 FuncInfo->addLiveInAttr(VReg, Flags); 3716 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3717 3718 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3719 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3720 // value to MVT::i64 and then truncate to the correct register size. 3721 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3722 } else { 3723 if (CallConv == CallingConv::Fast) 3724 ComputeArgOffset(); 3725 3726 needsLoad = true; 3727 ArgSize = PtrByteSize; 3728 } 3729 if (CallConv != CallingConv::Fast || needsLoad) 3730 ArgOffset += 8; 3731 break; 3732 3733 case MVT::f32: 3734 case MVT::f64: 3735 // These can be scalar arguments or elements of a float array type 3736 // passed directly. The latter are used to implement ELFv2 homogenous 3737 // float aggregates. 3738 if (FPR_idx != Num_FPR_Regs) { 3739 unsigned VReg; 3740 3741 if (ObjectVT == MVT::f32) 3742 VReg = MF.addLiveIn(FPR[FPR_idx], 3743 Subtarget.hasP8Vector() 3744 ? &PPC::VSSRCRegClass 3745 : &PPC::F4RCRegClass); 3746 else 3747 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3748 ? &PPC::VSFRCRegClass 3749 : &PPC::F8RCRegClass); 3750 3751 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3752 ++FPR_idx; 3753 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3754 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3755 // once we support fp <-> gpr moves. 3756 3757 // This can only ever happen in the presence of f32 array types, 3758 // since otherwise we never run out of FPRs before running out 3759 // of GPRs. 3760 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3761 FuncInfo->addLiveInAttr(VReg, Flags); 3762 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3763 3764 if (ObjectVT == MVT::f32) { 3765 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3766 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3767 DAG.getConstant(32, dl, MVT::i32)); 3768 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3769 } 3770 3771 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3772 } else { 3773 if (CallConv == CallingConv::Fast) 3774 ComputeArgOffset(); 3775 3776 needsLoad = true; 3777 } 3778 3779 // When passing an array of floats, the array occupies consecutive 3780 // space in the argument area; only round up to the next doubleword 3781 // at the end of the array. Otherwise, each float takes 8 bytes. 3782 if (CallConv != CallingConv::Fast || needsLoad) { 3783 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3784 ArgOffset += ArgSize; 3785 if (Flags.isInConsecutiveRegsLast()) 3786 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3787 } 3788 break; 3789 case MVT::v4f32: 3790 case MVT::v4i32: 3791 case MVT::v8i16: 3792 case MVT::v16i8: 3793 case MVT::v2f64: 3794 case MVT::v2i64: 3795 case MVT::v1i128: 3796 if (!Subtarget.hasQPX()) { 3797 // These can be scalar arguments or elements of a vector array type 3798 // passed directly. The latter are used to implement ELFv2 homogenous 3799 // vector aggregates. 3800 if (VR_idx != Num_VR_Regs) { 3801 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3802 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3803 ++VR_idx; 3804 } else { 3805 if (CallConv == CallingConv::Fast) 3806 ComputeArgOffset(); 3807 needsLoad = true; 3808 } 3809 if (CallConv != CallingConv::Fast || needsLoad) 3810 ArgOffset += 16; 3811 break; 3812 } // not QPX 3813 3814 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3815 "Invalid QPX parameter type"); 3816 /* fall through */ 3817 3818 case MVT::v4f64: 3819 case MVT::v4i1: 3820 // QPX vectors are treated like their scalar floating-point subregisters 3821 // (except that they're larger). 3822 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3823 if (QFPR_idx != Num_QFPR_Regs) { 3824 const TargetRegisterClass *RC; 3825 switch (ObjectVT.getSimpleVT().SimpleTy) { 3826 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3827 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3828 default: RC = &PPC::QBRCRegClass; break; 3829 } 3830 3831 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3832 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3833 ++QFPR_idx; 3834 } else { 3835 if (CallConv == CallingConv::Fast) 3836 ComputeArgOffset(); 3837 needsLoad = true; 3838 } 3839 if (CallConv != CallingConv::Fast || needsLoad) 3840 ArgOffset += Sz; 3841 break; 3842 } 3843 3844 // We need to load the argument to a virtual register if we determined 3845 // above that we ran out of physical registers of the appropriate type. 3846 if (needsLoad) { 3847 if (ObjSize < ArgSize && !isLittleEndian) 3848 CurArgOffset += ArgSize - ObjSize; 3849 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3850 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3851 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3852 } 3853 3854 InVals.push_back(ArgVal); 3855 } 3856 3857 // Area that is at least reserved in the caller of this function. 3858 unsigned MinReservedArea; 3859 if (HasParameterArea) 3860 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3861 else 3862 MinReservedArea = LinkageSize; 3863 3864 // Set the size that is at least reserved in caller of this function. Tail 3865 // call optimized functions' reserved stack space needs to be aligned so that 3866 // taking the difference between two stack areas will result in an aligned 3867 // stack. 3868 MinReservedArea = 3869 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3870 FuncInfo->setMinReservedArea(MinReservedArea); 3871 3872 // If the function takes variable number of arguments, make a frame index for 3873 // the start of the first vararg value... for expansion of llvm.va_start. 3874 if (isVarArg) { 3875 int Depth = ArgOffset; 3876 3877 FuncInfo->setVarArgsFrameIndex( 3878 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3879 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3880 3881 // If this function is vararg, store any remaining integer argument regs 3882 // to their spots on the stack so that they may be loaded by dereferencing 3883 // the result of va_next. 3884 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3885 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3886 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3887 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3888 SDValue Store = 3889 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3890 MemOps.push_back(Store); 3891 // Increment the address by four for the next argument to store 3892 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3893 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3894 } 3895 } 3896 3897 if (!MemOps.empty()) 3898 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3899 3900 return Chain; 3901 } 3902 3903 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3904 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3905 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3906 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3907 // TODO: add description of PPC stack frame format, or at least some docs. 3908 // 3909 MachineFunction &MF = DAG.getMachineFunction(); 3910 MachineFrameInfo &MFI = MF.getFrameInfo(); 3911 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3912 3913 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3914 bool isPPC64 = PtrVT == MVT::i64; 3915 // Potential tail calls could cause overwriting of argument stack slots. 3916 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3917 (CallConv == CallingConv::Fast)); 3918 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3919 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3920 unsigned ArgOffset = LinkageSize; 3921 // Area that is at least reserved in caller of this function. 3922 unsigned MinReservedArea = ArgOffset; 3923 3924 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3925 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3926 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3927 }; 3928 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3929 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3930 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3931 }; 3932 static const MCPhysReg VR[] = { 3933 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3934 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3935 }; 3936 3937 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3938 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3939 const unsigned Num_VR_Regs = array_lengthof( VR); 3940 3941 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3942 3943 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3944 3945 // In 32-bit non-varargs functions, the stack space for vectors is after the 3946 // stack space for non-vectors. We do not use this space unless we have 3947 // too many vectors to fit in registers, something that only occurs in 3948 // constructed examples:), but we have to walk the arglist to figure 3949 // that out...for the pathological case, compute VecArgOffset as the 3950 // start of the vector parameter area. Computing VecArgOffset is the 3951 // entire point of the following loop. 3952 unsigned VecArgOffset = ArgOffset; 3953 if (!isVarArg && !isPPC64) { 3954 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3955 ++ArgNo) { 3956 EVT ObjectVT = Ins[ArgNo].VT; 3957 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3958 3959 if (Flags.isByVal()) { 3960 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3961 unsigned ObjSize = Flags.getByValSize(); 3962 unsigned ArgSize = 3963 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3964 VecArgOffset += ArgSize; 3965 continue; 3966 } 3967 3968 switch(ObjectVT.getSimpleVT().SimpleTy) { 3969 default: llvm_unreachable("Unhandled argument type!"); 3970 case MVT::i1: 3971 case MVT::i32: 3972 case MVT::f32: 3973 VecArgOffset += 4; 3974 break; 3975 case MVT::i64: // PPC64 3976 case MVT::f64: 3977 // FIXME: We are guaranteed to be !isPPC64 at this point. 3978 // Does MVT::i64 apply? 3979 VecArgOffset += 8; 3980 break; 3981 case MVT::v4f32: 3982 case MVT::v4i32: 3983 case MVT::v8i16: 3984 case MVT::v16i8: 3985 // Nothing to do, we're only looking at Nonvector args here. 3986 break; 3987 } 3988 } 3989 } 3990 // We've found where the vector parameter area in memory is. Skip the 3991 // first 12 parameters; these don't use that memory. 3992 VecArgOffset = ((VecArgOffset+15)/16)*16; 3993 VecArgOffset += 12*16; 3994 3995 // Add DAG nodes to load the arguments or copy them out of registers. On 3996 // entry to a function on PPC, the arguments start after the linkage area, 3997 // although the first ones are often in registers. 3998 3999 SmallVector<SDValue, 8> MemOps; 4000 unsigned nAltivecParamsAtEnd = 0; 4001 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4002 unsigned CurArgIdx = 0; 4003 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4004 SDValue ArgVal; 4005 bool needsLoad = false; 4006 EVT ObjectVT = Ins[ArgNo].VT; 4007 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4008 unsigned ArgSize = ObjSize; 4009 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4010 if (Ins[ArgNo].isOrigArg()) { 4011 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4012 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4013 } 4014 unsigned CurArgOffset = ArgOffset; 4015 4016 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4017 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4018 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4019 if (isVarArg || isPPC64) { 4020 MinReservedArea = ((MinReservedArea+15)/16)*16; 4021 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4022 Flags, 4023 PtrByteSize); 4024 } else nAltivecParamsAtEnd++; 4025 } else 4026 // Calculate min reserved area. 4027 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4028 Flags, 4029 PtrByteSize); 4030 4031 // FIXME the codegen can be much improved in some cases. 4032 // We do not have to keep everything in memory. 4033 if (Flags.isByVal()) { 4034 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4035 4036 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4037 ObjSize = Flags.getByValSize(); 4038 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4039 // Objects of size 1 and 2 are right justified, everything else is 4040 // left justified. This means the memory address is adjusted forwards. 4041 if (ObjSize==1 || ObjSize==2) { 4042 CurArgOffset = CurArgOffset + (4 - ObjSize); 4043 } 4044 // The value of the object is its address. 4045 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4046 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4047 InVals.push_back(FIN); 4048 if (ObjSize==1 || ObjSize==2) { 4049 if (GPR_idx != Num_GPR_Regs) { 4050 unsigned VReg; 4051 if (isPPC64) 4052 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4053 else 4054 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4055 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4056 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4057 SDValue Store = 4058 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4059 MachinePointerInfo(&*FuncArg), ObjType); 4060 MemOps.push_back(Store); 4061 ++GPR_idx; 4062 } 4063 4064 ArgOffset += PtrByteSize; 4065 4066 continue; 4067 } 4068 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4069 // Store whatever pieces of the object are in registers 4070 // to memory. ArgOffset will be the address of the beginning 4071 // of the object. 4072 if (GPR_idx != Num_GPR_Regs) { 4073 unsigned VReg; 4074 if (isPPC64) 4075 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4076 else 4077 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4078 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4079 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4080 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4081 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4082 MachinePointerInfo(&*FuncArg, j)); 4083 MemOps.push_back(Store); 4084 ++GPR_idx; 4085 ArgOffset += PtrByteSize; 4086 } else { 4087 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4088 break; 4089 } 4090 } 4091 continue; 4092 } 4093 4094 switch (ObjectVT.getSimpleVT().SimpleTy) { 4095 default: llvm_unreachable("Unhandled argument type!"); 4096 case MVT::i1: 4097 case MVT::i32: 4098 if (!isPPC64) { 4099 if (GPR_idx != Num_GPR_Regs) { 4100 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4101 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4102 4103 if (ObjectVT == MVT::i1) 4104 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4105 4106 ++GPR_idx; 4107 } else { 4108 needsLoad = true; 4109 ArgSize = PtrByteSize; 4110 } 4111 // All int arguments reserve stack space in the Darwin ABI. 4112 ArgOffset += PtrByteSize; 4113 break; 4114 } 4115 LLVM_FALLTHROUGH; 4116 case MVT::i64: // PPC64 4117 if (GPR_idx != Num_GPR_Regs) { 4118 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4119 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4120 4121 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4122 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4123 // value to MVT::i64 and then truncate to the correct register size. 4124 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4125 4126 ++GPR_idx; 4127 } else { 4128 needsLoad = true; 4129 ArgSize = PtrByteSize; 4130 } 4131 // All int arguments reserve stack space in the Darwin ABI. 4132 ArgOffset += 8; 4133 break; 4134 4135 case MVT::f32: 4136 case MVT::f64: 4137 // Every 4 bytes of argument space consumes one of the GPRs available for 4138 // argument passing. 4139 if (GPR_idx != Num_GPR_Regs) { 4140 ++GPR_idx; 4141 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4142 ++GPR_idx; 4143 } 4144 if (FPR_idx != Num_FPR_Regs) { 4145 unsigned VReg; 4146 4147 if (ObjectVT == MVT::f32) 4148 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4149 else 4150 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4151 4152 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4153 ++FPR_idx; 4154 } else { 4155 needsLoad = true; 4156 } 4157 4158 // All FP arguments reserve stack space in the Darwin ABI. 4159 ArgOffset += isPPC64 ? 8 : ObjSize; 4160 break; 4161 case MVT::v4f32: 4162 case MVT::v4i32: 4163 case MVT::v8i16: 4164 case MVT::v16i8: 4165 // Note that vector arguments in registers don't reserve stack space, 4166 // except in varargs functions. 4167 if (VR_idx != Num_VR_Regs) { 4168 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4169 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4170 if (isVarArg) { 4171 while ((ArgOffset % 16) != 0) { 4172 ArgOffset += PtrByteSize; 4173 if (GPR_idx != Num_GPR_Regs) 4174 GPR_idx++; 4175 } 4176 ArgOffset += 16; 4177 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4178 } 4179 ++VR_idx; 4180 } else { 4181 if (!isVarArg && !isPPC64) { 4182 // Vectors go after all the nonvectors. 4183 CurArgOffset = VecArgOffset; 4184 VecArgOffset += 16; 4185 } else { 4186 // Vectors are aligned. 4187 ArgOffset = ((ArgOffset+15)/16)*16; 4188 CurArgOffset = ArgOffset; 4189 ArgOffset += 16; 4190 } 4191 needsLoad = true; 4192 } 4193 break; 4194 } 4195 4196 // We need to load the argument to a virtual register if we determined above 4197 // that we ran out of physical registers of the appropriate type. 4198 if (needsLoad) { 4199 int FI = MFI.CreateFixedObject(ObjSize, 4200 CurArgOffset + (ArgSize - ObjSize), 4201 isImmutable); 4202 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4203 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4204 } 4205 4206 InVals.push_back(ArgVal); 4207 } 4208 4209 // Allow for Altivec parameters at the end, if needed. 4210 if (nAltivecParamsAtEnd) { 4211 MinReservedArea = ((MinReservedArea+15)/16)*16; 4212 MinReservedArea += 16*nAltivecParamsAtEnd; 4213 } 4214 4215 // Area that is at least reserved in the caller of this function. 4216 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4217 4218 // Set the size that is at least reserved in caller of this function. Tail 4219 // call optimized functions' reserved stack space needs to be aligned so that 4220 // taking the difference between two stack areas will result in an aligned 4221 // stack. 4222 MinReservedArea = 4223 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4224 FuncInfo->setMinReservedArea(MinReservedArea); 4225 4226 // If the function takes variable number of arguments, make a frame index for 4227 // the start of the first vararg value... for expansion of llvm.va_start. 4228 if (isVarArg) { 4229 int Depth = ArgOffset; 4230 4231 FuncInfo->setVarArgsFrameIndex( 4232 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4233 Depth, true)); 4234 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4235 4236 // If this function is vararg, store any remaining integer argument regs 4237 // to their spots on the stack so that they may be loaded by dereferencing 4238 // the result of va_next. 4239 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4240 unsigned VReg; 4241 4242 if (isPPC64) 4243 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4244 else 4245 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4246 4247 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4248 SDValue Store = 4249 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4250 MemOps.push_back(Store); 4251 // Increment the address by four for the next argument to store 4252 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4253 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4254 } 4255 } 4256 4257 if (!MemOps.empty()) 4258 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4259 4260 return Chain; 4261 } 4262 4263 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4264 /// adjusted to accommodate the arguments for the tailcall. 4265 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4266 unsigned ParamSize) { 4267 4268 if (!isTailCall) return 0; 4269 4270 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4271 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4272 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4273 // Remember only if the new adjustement is bigger. 4274 if (SPDiff < FI->getTailCallSPDelta()) 4275 FI->setTailCallSPDelta(SPDiff); 4276 4277 return SPDiff; 4278 } 4279 4280 static bool isFunctionGlobalAddress(SDValue Callee); 4281 4282 static bool 4283 callsShareTOCBase(const Function *Caller, SDValue Callee, 4284 const TargetMachine &TM) { 4285 // If !G, Callee can be an external symbol. 4286 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4287 if (!G) 4288 return false; 4289 4290 // The medium and large code models are expected to provide a sufficiently 4291 // large TOC to provide all data addressing needs of a module with a 4292 // single TOC. Since each module will be addressed with a single TOC then we 4293 // only need to check that caller and callee don't cross dso boundaries. 4294 if (CodeModel::Medium == TM.getCodeModel() || 4295 CodeModel::Large == TM.getCodeModel()) 4296 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4297 4298 // Otherwise we need to ensure callee and caller are in the same section, 4299 // since the linker may allocate multiple TOCs, and we don't know which 4300 // sections will belong to the same TOC base. 4301 4302 const GlobalValue *GV = G->getGlobal(); 4303 if (!GV->isStrongDefinitionForLinker()) 4304 return false; 4305 4306 // Any explicitly-specified sections and section prefixes must also match. 4307 // Also, if we're using -ffunction-sections, then each function is always in 4308 // a different section (the same is true for COMDAT functions). 4309 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4310 GV->getSection() != Caller->getSection()) 4311 return false; 4312 if (const auto *F = dyn_cast<Function>(GV)) { 4313 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4314 return false; 4315 } 4316 4317 // If the callee might be interposed, then we can't assume the ultimate call 4318 // target will be in the same section. Even in cases where we can assume that 4319 // interposition won't happen, in any case where the linker might insert a 4320 // stub to allow for interposition, we must generate code as though 4321 // interposition might occur. To understand why this matters, consider a 4322 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4323 // in the same section, but a is in a different module (i.e. has a different 4324 // TOC base pointer). If the linker allows for interposition between b and c, 4325 // then it will generate a stub for the call edge between b and c which will 4326 // save the TOC pointer into the designated stack slot allocated by b. If we 4327 // return true here, and therefore allow a tail call between b and c, that 4328 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4329 // pointer into the stack slot allocated by a (where the a -> b stub saved 4330 // a's TOC base pointer). If we're not considering a tail call, but rather, 4331 // whether a nop is needed after the call instruction in b, because the linker 4332 // will insert a stub, it might complain about a missing nop if we omit it 4333 // (although many don't complain in this case). 4334 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4335 return false; 4336 4337 return true; 4338 } 4339 4340 static bool 4341 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4342 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4343 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4344 4345 const unsigned PtrByteSize = 8; 4346 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4347 4348 static const MCPhysReg GPR[] = { 4349 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4350 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4351 }; 4352 static const MCPhysReg VR[] = { 4353 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4354 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4355 }; 4356 4357 const unsigned NumGPRs = array_lengthof(GPR); 4358 const unsigned NumFPRs = 13; 4359 const unsigned NumVRs = array_lengthof(VR); 4360 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4361 4362 unsigned NumBytes = LinkageSize; 4363 unsigned AvailableFPRs = NumFPRs; 4364 unsigned AvailableVRs = NumVRs; 4365 4366 for (const ISD::OutputArg& Param : Outs) { 4367 if (Param.Flags.isNest()) continue; 4368 4369 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4370 PtrByteSize, LinkageSize, ParamAreaSize, 4371 NumBytes, AvailableFPRs, AvailableVRs, 4372 Subtarget.hasQPX())) 4373 return true; 4374 } 4375 return false; 4376 } 4377 4378 static bool 4379 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4380 if (CS.arg_size() != CallerFn->arg_size()) 4381 return false; 4382 4383 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4384 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4385 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4386 4387 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4388 const Value* CalleeArg = *CalleeArgIter; 4389 const Value* CallerArg = &(*CallerArgIter); 4390 if (CalleeArg == CallerArg) 4391 continue; 4392 4393 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4394 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4395 // } 4396 // 1st argument of callee is undef and has the same type as caller. 4397 if (CalleeArg->getType() == CallerArg->getType() && 4398 isa<UndefValue>(CalleeArg)) 4399 continue; 4400 4401 return false; 4402 } 4403 4404 return true; 4405 } 4406 4407 // Returns true if TCO is possible between the callers and callees 4408 // calling conventions. 4409 static bool 4410 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4411 CallingConv::ID CalleeCC) { 4412 // Tail calls are possible with fastcc and ccc. 4413 auto isTailCallableCC = [] (CallingConv::ID CC){ 4414 return CC == CallingConv::C || CC == CallingConv::Fast; 4415 }; 4416 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4417 return false; 4418 4419 // We can safely tail call both fastcc and ccc callees from a c calling 4420 // convention caller. If the caller is fastcc, we may have less stack space 4421 // than a non-fastcc caller with the same signature so disable tail-calls in 4422 // that case. 4423 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4424 } 4425 4426 bool 4427 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4428 SDValue Callee, 4429 CallingConv::ID CalleeCC, 4430 ImmutableCallSite CS, 4431 bool isVarArg, 4432 const SmallVectorImpl<ISD::OutputArg> &Outs, 4433 const SmallVectorImpl<ISD::InputArg> &Ins, 4434 SelectionDAG& DAG) const { 4435 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4436 4437 if (DisableSCO && !TailCallOpt) return false; 4438 4439 // Variadic argument functions are not supported. 4440 if (isVarArg) return false; 4441 4442 auto &Caller = DAG.getMachineFunction().getFunction(); 4443 // Check that the calling conventions are compatible for tco. 4444 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4445 return false; 4446 4447 // Caller contains any byval parameter is not supported. 4448 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4449 return false; 4450 4451 // Callee contains any byval parameter is not supported, too. 4452 // Note: This is a quick work around, because in some cases, e.g. 4453 // caller's stack size > callee's stack size, we are still able to apply 4454 // sibling call optimization. For example, gcc is able to do SCO for caller1 4455 // in the following example, but not for caller2. 4456 // struct test { 4457 // long int a; 4458 // char ary[56]; 4459 // } gTest; 4460 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4461 // b->a = v.a; 4462 // return 0; 4463 // } 4464 // void caller1(struct test a, struct test c, struct test *b) { 4465 // callee(gTest, b); } 4466 // void caller2(struct test *b) { callee(gTest, b); } 4467 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4468 return false; 4469 4470 // If callee and caller use different calling conventions, we cannot pass 4471 // parameters on stack since offsets for the parameter area may be different. 4472 if (Caller.getCallingConv() != CalleeCC && 4473 needStackSlotPassParameters(Subtarget, Outs)) 4474 return false; 4475 4476 // No TCO/SCO on indirect call because Caller have to restore its TOC 4477 if (!isFunctionGlobalAddress(Callee) && 4478 !isa<ExternalSymbolSDNode>(Callee)) 4479 return false; 4480 4481 // If the caller and callee potentially have different TOC bases then we 4482 // cannot tail call since we need to restore the TOC pointer after the call. 4483 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4484 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4485 return false; 4486 4487 // TCO allows altering callee ABI, so we don't have to check further. 4488 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4489 return true; 4490 4491 if (DisableSCO) return false; 4492 4493 // If callee use the same argument list that caller is using, then we can 4494 // apply SCO on this case. If it is not, then we need to check if callee needs 4495 // stack for passing arguments. 4496 if (!hasSameArgumentList(&Caller, CS) && 4497 needStackSlotPassParameters(Subtarget, Outs)) { 4498 return false; 4499 } 4500 4501 return true; 4502 } 4503 4504 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4505 /// for tail call optimization. Targets which want to do tail call 4506 /// optimization should implement this function. 4507 bool 4508 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4509 CallingConv::ID CalleeCC, 4510 bool isVarArg, 4511 const SmallVectorImpl<ISD::InputArg> &Ins, 4512 SelectionDAG& DAG) const { 4513 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4514 return false; 4515 4516 // Variable argument functions are not supported. 4517 if (isVarArg) 4518 return false; 4519 4520 MachineFunction &MF = DAG.getMachineFunction(); 4521 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4522 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4523 // Functions containing by val parameters are not supported. 4524 for (unsigned i = 0; i != Ins.size(); i++) { 4525 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4526 if (Flags.isByVal()) return false; 4527 } 4528 4529 // Non-PIC/GOT tail calls are supported. 4530 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4531 return true; 4532 4533 // At the moment we can only do local tail calls (in same module, hidden 4534 // or protected) if we are generating PIC. 4535 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4536 return G->getGlobal()->hasHiddenVisibility() 4537 || G->getGlobal()->hasProtectedVisibility(); 4538 } 4539 4540 return false; 4541 } 4542 4543 /// isCallCompatibleAddress - Return the immediate to use if the specified 4544 /// 32-bit value is representable in the immediate field of a BxA instruction. 4545 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4546 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4547 if (!C) return nullptr; 4548 4549 int Addr = C->getZExtValue(); 4550 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4551 SignExtend32<26>(Addr) != Addr) 4552 return nullptr; // Top 6 bits have to be sext of immediate. 4553 4554 return DAG 4555 .getConstant( 4556 (int)C->getZExtValue() >> 2, SDLoc(Op), 4557 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4558 .getNode(); 4559 } 4560 4561 namespace { 4562 4563 struct TailCallArgumentInfo { 4564 SDValue Arg; 4565 SDValue FrameIdxOp; 4566 int FrameIdx = 0; 4567 4568 TailCallArgumentInfo() = default; 4569 }; 4570 4571 } // end anonymous namespace 4572 4573 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4574 static void StoreTailCallArgumentsToStackSlot( 4575 SelectionDAG &DAG, SDValue Chain, 4576 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4577 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4578 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4579 SDValue Arg = TailCallArgs[i].Arg; 4580 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4581 int FI = TailCallArgs[i].FrameIdx; 4582 // Store relative to framepointer. 4583 MemOpChains.push_back(DAG.getStore( 4584 Chain, dl, Arg, FIN, 4585 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4586 } 4587 } 4588 4589 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4590 /// the appropriate stack slot for the tail call optimized function call. 4591 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4592 SDValue OldRetAddr, SDValue OldFP, 4593 int SPDiff, const SDLoc &dl) { 4594 if (SPDiff) { 4595 // Calculate the new stack slot for the return address. 4596 MachineFunction &MF = DAG.getMachineFunction(); 4597 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4598 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4599 bool isPPC64 = Subtarget.isPPC64(); 4600 int SlotSize = isPPC64 ? 8 : 4; 4601 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4602 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4603 NewRetAddrLoc, true); 4604 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4605 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4606 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4607 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4608 4609 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4610 // slot as the FP is never overwritten. 4611 if (Subtarget.isDarwinABI()) { 4612 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4613 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4614 true); 4615 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4616 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4617 MachinePointerInfo::getFixedStack( 4618 DAG.getMachineFunction(), NewFPIdx)); 4619 } 4620 } 4621 return Chain; 4622 } 4623 4624 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4625 /// the position of the argument. 4626 static void 4627 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4628 SDValue Arg, int SPDiff, unsigned ArgOffset, 4629 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4630 int Offset = ArgOffset + SPDiff; 4631 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4632 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4633 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4634 SDValue FIN = DAG.getFrameIndex(FI, VT); 4635 TailCallArgumentInfo Info; 4636 Info.Arg = Arg; 4637 Info.FrameIdxOp = FIN; 4638 Info.FrameIdx = FI; 4639 TailCallArguments.push_back(Info); 4640 } 4641 4642 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4643 /// stack slot. Returns the chain as result and the loaded frame pointers in 4644 /// LROpOut/FPOpout. Used when tail calling. 4645 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4646 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4647 SDValue &FPOpOut, const SDLoc &dl) const { 4648 if (SPDiff) { 4649 // Load the LR and FP stack slot for later adjusting. 4650 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4651 LROpOut = getReturnAddrFrameIndex(DAG); 4652 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4653 Chain = SDValue(LROpOut.getNode(), 1); 4654 4655 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4656 // slot as the FP is never overwritten. 4657 if (Subtarget.isDarwinABI()) { 4658 FPOpOut = getFramePointerFrameIndex(DAG); 4659 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4660 Chain = SDValue(FPOpOut.getNode(), 1); 4661 } 4662 } 4663 return Chain; 4664 } 4665 4666 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4667 /// by "Src" to address "Dst" of size "Size". Alignment information is 4668 /// specified by the specific parameter attribute. The copy will be passed as 4669 /// a byval function parameter. 4670 /// Sometimes what we are copying is the end of a larger object, the part that 4671 /// does not fit in registers. 4672 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4673 SDValue Chain, ISD::ArgFlagsTy Flags, 4674 SelectionDAG &DAG, const SDLoc &dl) { 4675 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4676 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4677 false, false, false, MachinePointerInfo(), 4678 MachinePointerInfo()); 4679 } 4680 4681 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4682 /// tail calls. 4683 static void LowerMemOpCallTo( 4684 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4685 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4686 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4687 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4688 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4689 if (!isTailCall) { 4690 if (isVector) { 4691 SDValue StackPtr; 4692 if (isPPC64) 4693 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4694 else 4695 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4696 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4697 DAG.getConstant(ArgOffset, dl, PtrVT)); 4698 } 4699 MemOpChains.push_back( 4700 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4701 // Calculate and remember argument location. 4702 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4703 TailCallArguments); 4704 } 4705 4706 static void 4707 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4708 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4709 SDValue FPOp, 4710 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4711 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4712 // might overwrite each other in case of tail call optimization. 4713 SmallVector<SDValue, 8> MemOpChains2; 4714 // Do not flag preceding copytoreg stuff together with the following stuff. 4715 InFlag = SDValue(); 4716 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4717 MemOpChains2, dl); 4718 if (!MemOpChains2.empty()) 4719 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4720 4721 // Store the return address to the appropriate stack slot. 4722 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4723 4724 // Emit callseq_end just before tailcall node. 4725 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4726 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4727 InFlag = Chain.getValue(1); 4728 } 4729 4730 // Is this global address that of a function that can be called by name? (as 4731 // opposed to something that must hold a descriptor for an indirect call). 4732 static bool isFunctionGlobalAddress(SDValue Callee) { 4733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4734 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4735 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4736 return false; 4737 4738 return G->getGlobal()->getValueType()->isFunctionTy(); 4739 } 4740 4741 return false; 4742 } 4743 4744 static unsigned 4745 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4746 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4747 bool isPatchPoint, bool hasNest, 4748 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4749 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4750 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4751 bool isPPC64 = Subtarget.isPPC64(); 4752 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4753 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4754 4755 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4756 NodeTys.push_back(MVT::Other); // Returns a chain 4757 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4758 4759 unsigned CallOpc = PPCISD::CALL; 4760 4761 bool needIndirectCall = true; 4762 if (!isSVR4ABI || !isPPC64) 4763 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4764 // If this is an absolute destination address, use the munged value. 4765 Callee = SDValue(Dest, 0); 4766 needIndirectCall = false; 4767 } 4768 4769 // PC-relative references to external symbols should go through $stub, unless 4770 // we're building with the leopard linker or later, which automatically 4771 // synthesizes these stubs. 4772 const TargetMachine &TM = DAG.getTarget(); 4773 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4774 const GlobalValue *GV = nullptr; 4775 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4776 GV = G->getGlobal(); 4777 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4778 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4779 4780 if (isFunctionGlobalAddress(Callee)) { 4781 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4782 // A call to a TLS address is actually an indirect call to a 4783 // thread-specific pointer. 4784 unsigned OpFlags = 0; 4785 if (UsePlt) 4786 OpFlags = PPCII::MO_PLT; 4787 4788 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4789 // every direct call is) turn it into a TargetGlobalAddress / 4790 // TargetExternalSymbol node so that legalize doesn't hack it. 4791 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4792 Callee.getValueType(), 0, OpFlags); 4793 needIndirectCall = false; 4794 } 4795 4796 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4797 unsigned char OpFlags = 0; 4798 4799 if (UsePlt) 4800 OpFlags = PPCII::MO_PLT; 4801 4802 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4803 OpFlags); 4804 needIndirectCall = false; 4805 } 4806 4807 if (isPatchPoint) { 4808 // We'll form an invalid direct call when lowering a patchpoint; the full 4809 // sequence for an indirect call is complicated, and many of the 4810 // instructions introduced might have side effects (and, thus, can't be 4811 // removed later). The call itself will be removed as soon as the 4812 // argument/return lowering is complete, so the fact that it has the wrong 4813 // kind of operands should not really matter. 4814 needIndirectCall = false; 4815 } 4816 4817 if (needIndirectCall) { 4818 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4819 // to do the call, we can't use PPCISD::CALL. 4820 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4821 4822 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4823 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4824 // entry point, but to the function descriptor (the function entry point 4825 // address is part of the function descriptor though). 4826 // The function descriptor is a three doubleword structure with the 4827 // following fields: function entry point, TOC base address and 4828 // environment pointer. 4829 // Thus for a call through a function pointer, the following actions need 4830 // to be performed: 4831 // 1. Save the TOC of the caller in the TOC save area of its stack 4832 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4833 // 2. Load the address of the function entry point from the function 4834 // descriptor. 4835 // 3. Load the TOC of the callee from the function descriptor into r2. 4836 // 4. Load the environment pointer from the function descriptor into 4837 // r11. 4838 // 5. Branch to the function entry point address. 4839 // 6. On return of the callee, the TOC of the caller needs to be 4840 // restored (this is done in FinishCall()). 4841 // 4842 // The loads are scheduled at the beginning of the call sequence, and the 4843 // register copies are flagged together to ensure that no other 4844 // operations can be scheduled in between. E.g. without flagging the 4845 // copies together, a TOC access in the caller could be scheduled between 4846 // the assignment of the callee TOC and the branch to the callee, which 4847 // results in the TOC access going through the TOC of the callee instead 4848 // of going through the TOC of the caller, which leads to incorrect code. 4849 4850 // Load the address of the function entry point from the function 4851 // descriptor. 4852 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4853 if (LDChain.getValueType() == MVT::Glue) 4854 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4855 4856 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4857 ? (MachineMemOperand::MODereferenceable | 4858 MachineMemOperand::MOInvariant) 4859 : MachineMemOperand::MONone; 4860 4861 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4862 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4863 /* Alignment = */ 8, MMOFlags); 4864 4865 // Load environment pointer into r11. 4866 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4867 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4868 SDValue LoadEnvPtr = 4869 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4870 /* Alignment = */ 8, MMOFlags); 4871 4872 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4873 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4874 SDValue TOCPtr = 4875 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4876 /* Alignment = */ 8, MMOFlags); 4877 4878 setUsesTOCBasePtr(DAG); 4879 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4880 InFlag); 4881 Chain = TOCVal.getValue(0); 4882 InFlag = TOCVal.getValue(1); 4883 4884 // If the function call has an explicit 'nest' parameter, it takes the 4885 // place of the environment pointer. 4886 if (!hasNest) { 4887 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4888 InFlag); 4889 4890 Chain = EnvVal.getValue(0); 4891 InFlag = EnvVal.getValue(1); 4892 } 4893 4894 MTCTROps[0] = Chain; 4895 MTCTROps[1] = LoadFuncPtr; 4896 MTCTROps[2] = InFlag; 4897 } 4898 4899 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4900 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4901 InFlag = Chain.getValue(1); 4902 4903 NodeTys.clear(); 4904 NodeTys.push_back(MVT::Other); 4905 NodeTys.push_back(MVT::Glue); 4906 Ops.push_back(Chain); 4907 CallOpc = PPCISD::BCTRL; 4908 Callee.setNode(nullptr); 4909 // Add use of X11 (holding environment pointer) 4910 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4911 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4912 // Add CTR register as callee so a bctr can be emitted later. 4913 if (isTailCall) 4914 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4915 } 4916 4917 // If this is a direct call, pass the chain and the callee. 4918 if (Callee.getNode()) { 4919 Ops.push_back(Chain); 4920 Ops.push_back(Callee); 4921 } 4922 // If this is a tail call add stack pointer delta. 4923 if (isTailCall) 4924 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4925 4926 // Add argument registers to the end of the list so that they are known live 4927 // into the call. 4928 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4929 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4930 RegsToPass[i].second.getValueType())); 4931 4932 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4933 // into the call. 4934 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4935 setUsesTOCBasePtr(DAG); 4936 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4937 } 4938 4939 return CallOpc; 4940 } 4941 4942 SDValue PPCTargetLowering::LowerCallResult( 4943 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4944 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4945 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4946 SmallVector<CCValAssign, 16> RVLocs; 4947 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4948 *DAG.getContext()); 4949 4950 CCRetInfo.AnalyzeCallResult( 4951 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4952 ? RetCC_PPC_Cold 4953 : RetCC_PPC); 4954 4955 // Copy all of the result registers out of their specified physreg. 4956 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4957 CCValAssign &VA = RVLocs[i]; 4958 assert(VA.isRegLoc() && "Can only return in registers!"); 4959 4960 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4961 VA.getLocReg(), VA.getLocVT(), InFlag); 4962 Chain = Val.getValue(1); 4963 InFlag = Val.getValue(2); 4964 4965 switch (VA.getLocInfo()) { 4966 default: llvm_unreachable("Unknown loc info!"); 4967 case CCValAssign::Full: break; 4968 case CCValAssign::AExt: 4969 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4970 break; 4971 case CCValAssign::ZExt: 4972 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4973 DAG.getValueType(VA.getValVT())); 4974 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4975 break; 4976 case CCValAssign::SExt: 4977 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4978 DAG.getValueType(VA.getValVT())); 4979 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4980 break; 4981 } 4982 4983 InVals.push_back(Val); 4984 } 4985 4986 return Chain; 4987 } 4988 4989 SDValue PPCTargetLowering::FinishCall( 4990 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4991 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4992 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4993 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4994 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4995 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 4996 std::vector<EVT> NodeTys; 4997 SmallVector<SDValue, 8> Ops; 4998 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4999 SPDiff, isTailCall, isPatchPoint, hasNest, 5000 RegsToPass, Ops, NodeTys, CS, Subtarget); 5001 5002 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5003 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5004 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5005 5006 // When performing tail call optimization the callee pops its arguments off 5007 // the stack. Account for this here so these bytes can be pushed back on in 5008 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5009 int BytesCalleePops = 5010 (CallConv == CallingConv::Fast && 5011 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5012 5013 // Add a register mask operand representing the call-preserved registers. 5014 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5015 const uint32_t *Mask = 5016 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5017 assert(Mask && "Missing call preserved mask for calling convention"); 5018 Ops.push_back(DAG.getRegisterMask(Mask)); 5019 5020 if (InFlag.getNode()) 5021 Ops.push_back(InFlag); 5022 5023 // Emit tail call. 5024 if (isTailCall) { 5025 assert(((Callee.getOpcode() == ISD::Register && 5026 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5027 Callee.getOpcode() == ISD::TargetExternalSymbol || 5028 Callee.getOpcode() == ISD::TargetGlobalAddress || 5029 isa<ConstantSDNode>(Callee)) && 5030 "Expecting an global address, external symbol, absolute value or register"); 5031 5032 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5033 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5034 } 5035 5036 // Add a NOP immediately after the branch instruction when using the 64-bit 5037 // SVR4 ABI. At link time, if caller and callee are in a different module and 5038 // thus have a different TOC, the call will be replaced with a call to a stub 5039 // function which saves the current TOC, loads the TOC of the callee and 5040 // branches to the callee. The NOP will be replaced with a load instruction 5041 // which restores the TOC of the caller from the TOC save slot of the current 5042 // stack frame. If caller and callee belong to the same module (and have the 5043 // same TOC), the NOP will remain unchanged. 5044 5045 MachineFunction &MF = DAG.getMachineFunction(); 5046 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5047 !isPatchPoint) { 5048 if (CallOpc == PPCISD::BCTRL) { 5049 // This is a call through a function pointer. 5050 // Restore the caller TOC from the save area into R2. 5051 // See PrepareCall() for more information about calls through function 5052 // pointers in the 64-bit SVR4 ABI. 5053 // We are using a target-specific load with r2 hard coded, because the 5054 // result of a target-independent load would never go directly into r2, 5055 // since r2 is a reserved register (which prevents the register allocator 5056 // from allocating it), resulting in an additional register being 5057 // allocated and an unnecessary move instruction being generated. 5058 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5059 5060 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5061 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5062 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5063 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5064 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5065 5066 // The address needs to go after the chain input but before the flag (or 5067 // any other variadic arguments). 5068 Ops.insert(std::next(Ops.begin()), AddTOC); 5069 } else if (CallOpc == PPCISD::CALL && 5070 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5071 // Otherwise insert NOP for non-local calls. 5072 CallOpc = PPCISD::CALL_NOP; 5073 } 5074 } 5075 5076 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5077 InFlag = Chain.getValue(1); 5078 5079 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5080 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5081 InFlag, dl); 5082 if (!Ins.empty()) 5083 InFlag = Chain.getValue(1); 5084 5085 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5086 Ins, dl, DAG, InVals); 5087 } 5088 5089 SDValue 5090 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5091 SmallVectorImpl<SDValue> &InVals) const { 5092 SelectionDAG &DAG = CLI.DAG; 5093 SDLoc &dl = CLI.DL; 5094 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5095 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5096 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5097 SDValue Chain = CLI.Chain; 5098 SDValue Callee = CLI.Callee; 5099 bool &isTailCall = CLI.IsTailCall; 5100 CallingConv::ID CallConv = CLI.CallConv; 5101 bool isVarArg = CLI.IsVarArg; 5102 bool isPatchPoint = CLI.IsPatchPoint; 5103 ImmutableCallSite CS = CLI.CS; 5104 5105 if (isTailCall) { 5106 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5107 isTailCall = false; 5108 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5109 isTailCall = 5110 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5111 isVarArg, Outs, Ins, DAG); 5112 else 5113 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5114 Ins, DAG); 5115 if (isTailCall) { 5116 ++NumTailCalls; 5117 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5118 ++NumSiblingCalls; 5119 5120 assert(isa<GlobalAddressSDNode>(Callee) && 5121 "Callee should be an llvm::Function object."); 5122 DEBUG( 5123 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5124 const unsigned Width = 80 - strlen("TCO caller: ") 5125 - strlen(", callee linkage: 0, 0"); 5126 dbgs() << "TCO caller: " 5127 << left_justify(DAG.getMachineFunction().getName(), Width) 5128 << ", callee linkage: " 5129 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5130 ); 5131 } 5132 } 5133 5134 if (!isTailCall && CS && CS.isMustTailCall()) 5135 report_fatal_error("failed to perform tail call elimination on a call " 5136 "site marked musttail"); 5137 5138 // When long calls (i.e. indirect calls) are always used, calls are always 5139 // made via function pointer. If we have a function name, first translate it 5140 // into a pointer. 5141 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5142 !isTailCall) 5143 Callee = LowerGlobalAddress(Callee, DAG); 5144 5145 if (Subtarget.isSVR4ABI()) { 5146 if (Subtarget.isPPC64()) 5147 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5148 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5149 dl, DAG, InVals, CS); 5150 else 5151 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5152 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5153 dl, DAG, InVals, CS); 5154 } 5155 5156 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5157 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5158 dl, DAG, InVals, CS); 5159 } 5160 5161 SDValue PPCTargetLowering::LowerCall_32SVR4( 5162 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5163 bool isTailCall, bool isPatchPoint, 5164 const SmallVectorImpl<ISD::OutputArg> &Outs, 5165 const SmallVectorImpl<SDValue> &OutVals, 5166 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5167 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5168 ImmutableCallSite CS) const { 5169 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5170 // of the 32-bit SVR4 ABI stack frame layout. 5171 5172 assert((CallConv == CallingConv::C || 5173 CallConv == CallingConv::Cold || 5174 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5175 5176 unsigned PtrByteSize = 4; 5177 5178 MachineFunction &MF = DAG.getMachineFunction(); 5179 5180 // Mark this function as potentially containing a function that contains a 5181 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5182 // and restoring the callers stack pointer in this functions epilog. This is 5183 // done because by tail calling the called function might overwrite the value 5184 // in this function's (MF) stack pointer stack slot 0(SP). 5185 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5186 CallConv == CallingConv::Fast) 5187 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5188 5189 // Count how many bytes are to be pushed on the stack, including the linkage 5190 // area, parameter list area and the part of the local variable space which 5191 // contains copies of aggregates which are passed by value. 5192 5193 // Assign locations to all of the outgoing arguments. 5194 SmallVector<CCValAssign, 16> ArgLocs; 5195 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5196 5197 // Reserve space for the linkage area on the stack. 5198 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5199 PtrByteSize); 5200 if (useSoftFloat()) 5201 CCInfo.PreAnalyzeCallOperands(Outs); 5202 5203 if (isVarArg) { 5204 // Handle fixed and variable vector arguments differently. 5205 // Fixed vector arguments go into registers as long as registers are 5206 // available. Variable vector arguments always go into memory. 5207 unsigned NumArgs = Outs.size(); 5208 5209 for (unsigned i = 0; i != NumArgs; ++i) { 5210 MVT ArgVT = Outs[i].VT; 5211 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5212 bool Result; 5213 5214 if (Outs[i].IsFixed) { 5215 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5216 CCInfo); 5217 } else { 5218 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5219 ArgFlags, CCInfo); 5220 } 5221 5222 if (Result) { 5223 #ifndef NDEBUG 5224 errs() << "Call operand #" << i << " has unhandled type " 5225 << EVT(ArgVT).getEVTString() << "\n"; 5226 #endif 5227 llvm_unreachable(nullptr); 5228 } 5229 } 5230 } else { 5231 // All arguments are treated the same. 5232 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5233 } 5234 CCInfo.clearWasPPCF128(); 5235 5236 // Assign locations to all of the outgoing aggregate by value arguments. 5237 SmallVector<CCValAssign, 16> ByValArgLocs; 5238 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5239 5240 // Reserve stack space for the allocations in CCInfo. 5241 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5242 5243 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5244 5245 // Size of the linkage area, parameter list area and the part of the local 5246 // space variable where copies of aggregates which are passed by value are 5247 // stored. 5248 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5249 5250 // Calculate by how many bytes the stack has to be adjusted in case of tail 5251 // call optimization. 5252 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5253 5254 // Adjust the stack pointer for the new arguments... 5255 // These operations are automatically eliminated by the prolog/epilog pass 5256 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5257 SDValue CallSeqStart = Chain; 5258 5259 // Load the return address and frame pointer so it can be moved somewhere else 5260 // later. 5261 SDValue LROp, FPOp; 5262 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5263 5264 // Set up a copy of the stack pointer for use loading and storing any 5265 // arguments that may not fit in the registers available for argument 5266 // passing. 5267 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5268 5269 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5270 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5271 SmallVector<SDValue, 8> MemOpChains; 5272 5273 bool seenFloatArg = false; 5274 // Walk the register/memloc assignments, inserting copies/loads. 5275 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5276 i != e; 5277 ++i) { 5278 CCValAssign &VA = ArgLocs[i]; 5279 SDValue Arg = OutVals[i]; 5280 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5281 5282 if (Flags.isByVal()) { 5283 // Argument is an aggregate which is passed by value, thus we need to 5284 // create a copy of it in the local variable space of the current stack 5285 // frame (which is the stack frame of the caller) and pass the address of 5286 // this copy to the callee. 5287 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5288 CCValAssign &ByValVA = ByValArgLocs[j++]; 5289 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5290 5291 // Memory reserved in the local variable space of the callers stack frame. 5292 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5293 5294 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5295 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5296 StackPtr, PtrOff); 5297 5298 // Create a copy of the argument in the local area of the current 5299 // stack frame. 5300 SDValue MemcpyCall = 5301 CreateCopyOfByValArgument(Arg, PtrOff, 5302 CallSeqStart.getNode()->getOperand(0), 5303 Flags, DAG, dl); 5304 5305 // This must go outside the CALLSEQ_START..END. 5306 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5307 SDLoc(MemcpyCall)); 5308 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5309 NewCallSeqStart.getNode()); 5310 Chain = CallSeqStart = NewCallSeqStart; 5311 5312 // Pass the address of the aggregate copy on the stack either in a 5313 // physical register or in the parameter list area of the current stack 5314 // frame to the callee. 5315 Arg = PtrOff; 5316 } 5317 5318 if (VA.isRegLoc()) { 5319 if (Arg.getValueType() == MVT::i1) 5320 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5321 5322 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5323 // Put argument in a physical register. 5324 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5325 } else { 5326 // Put argument in the parameter list area of the current stack frame. 5327 assert(VA.isMemLoc()); 5328 unsigned LocMemOffset = VA.getLocMemOffset(); 5329 5330 if (!isTailCall) { 5331 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5332 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5333 StackPtr, PtrOff); 5334 5335 MemOpChains.push_back( 5336 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5337 } else { 5338 // Calculate and remember argument location. 5339 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5340 TailCallArguments); 5341 } 5342 } 5343 } 5344 5345 if (!MemOpChains.empty()) 5346 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5347 5348 // Build a sequence of copy-to-reg nodes chained together with token chain 5349 // and flag operands which copy the outgoing args into the appropriate regs. 5350 SDValue InFlag; 5351 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5352 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5353 RegsToPass[i].second, InFlag); 5354 InFlag = Chain.getValue(1); 5355 } 5356 5357 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5358 // registers. 5359 if (isVarArg) { 5360 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5361 SDValue Ops[] = { Chain, InFlag }; 5362 5363 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5364 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5365 5366 InFlag = Chain.getValue(1); 5367 } 5368 5369 if (isTailCall) 5370 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5371 TailCallArguments); 5372 5373 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5374 /* unused except on PPC64 ELFv1 */ false, DAG, 5375 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5376 NumBytes, Ins, InVals, CS); 5377 } 5378 5379 // Copy an argument into memory, being careful to do this outside the 5380 // call sequence for the call to which the argument belongs. 5381 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5382 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5383 SelectionDAG &DAG, const SDLoc &dl) const { 5384 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5385 CallSeqStart.getNode()->getOperand(0), 5386 Flags, DAG, dl); 5387 // The MEMCPY must go outside the CALLSEQ_START..END. 5388 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5389 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5390 SDLoc(MemcpyCall)); 5391 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5392 NewCallSeqStart.getNode()); 5393 return NewCallSeqStart; 5394 } 5395 5396 SDValue PPCTargetLowering::LowerCall_64SVR4( 5397 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5398 bool isTailCall, bool isPatchPoint, 5399 const SmallVectorImpl<ISD::OutputArg> &Outs, 5400 const SmallVectorImpl<SDValue> &OutVals, 5401 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5402 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5403 ImmutableCallSite CS) const { 5404 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5405 bool isLittleEndian = Subtarget.isLittleEndian(); 5406 unsigned NumOps = Outs.size(); 5407 bool hasNest = false; 5408 bool IsSibCall = false; 5409 5410 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5411 unsigned PtrByteSize = 8; 5412 5413 MachineFunction &MF = DAG.getMachineFunction(); 5414 5415 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5416 IsSibCall = true; 5417 5418 // Mark this function as potentially containing a function that contains a 5419 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5420 // and restoring the callers stack pointer in this functions epilog. This is 5421 // done because by tail calling the called function might overwrite the value 5422 // in this function's (MF) stack pointer stack slot 0(SP). 5423 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5424 CallConv == CallingConv::Fast) 5425 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5426 5427 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5428 "fastcc not supported on varargs functions"); 5429 5430 // Count how many bytes are to be pushed on the stack, including the linkage 5431 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5432 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5433 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5434 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5435 unsigned NumBytes = LinkageSize; 5436 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5437 unsigned &QFPR_idx = FPR_idx; 5438 5439 static const MCPhysReg GPR[] = { 5440 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5441 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5442 }; 5443 static const MCPhysReg VR[] = { 5444 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5445 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5446 }; 5447 5448 const unsigned NumGPRs = array_lengthof(GPR); 5449 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5450 const unsigned NumVRs = array_lengthof(VR); 5451 const unsigned NumQFPRs = NumFPRs; 5452 5453 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5454 // can be passed to the callee in registers. 5455 // For the fast calling convention, there is another check below. 5456 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5457 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5458 if (!HasParameterArea) { 5459 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5460 unsigned AvailableFPRs = NumFPRs; 5461 unsigned AvailableVRs = NumVRs; 5462 unsigned NumBytesTmp = NumBytes; 5463 for (unsigned i = 0; i != NumOps; ++i) { 5464 if (Outs[i].Flags.isNest()) continue; 5465 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5466 PtrByteSize, LinkageSize, ParamAreaSize, 5467 NumBytesTmp, AvailableFPRs, AvailableVRs, 5468 Subtarget.hasQPX())) 5469 HasParameterArea = true; 5470 } 5471 } 5472 5473 // When using the fast calling convention, we don't provide backing for 5474 // arguments that will be in registers. 5475 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5476 5477 // Avoid allocating parameter area for fastcc functions if all the arguments 5478 // can be passed in the registers. 5479 if (CallConv == CallingConv::Fast) 5480 HasParameterArea = false; 5481 5482 // Add up all the space actually used. 5483 for (unsigned i = 0; i != NumOps; ++i) { 5484 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5485 EVT ArgVT = Outs[i].VT; 5486 EVT OrigVT = Outs[i].ArgVT; 5487 5488 if (Flags.isNest()) 5489 continue; 5490 5491 if (CallConv == CallingConv::Fast) { 5492 if (Flags.isByVal()) { 5493 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5494 if (NumGPRsUsed > NumGPRs) 5495 HasParameterArea = true; 5496 } else { 5497 switch (ArgVT.getSimpleVT().SimpleTy) { 5498 default: llvm_unreachable("Unexpected ValueType for argument!"); 5499 case MVT::i1: 5500 case MVT::i32: 5501 case MVT::i64: 5502 if (++NumGPRsUsed <= NumGPRs) 5503 continue; 5504 break; 5505 case MVT::v4i32: 5506 case MVT::v8i16: 5507 case MVT::v16i8: 5508 case MVT::v2f64: 5509 case MVT::v2i64: 5510 case MVT::v1i128: 5511 if (++NumVRsUsed <= NumVRs) 5512 continue; 5513 break; 5514 case MVT::v4f32: 5515 // When using QPX, this is handled like a FP register, otherwise, it 5516 // is an Altivec register. 5517 if (Subtarget.hasQPX()) { 5518 if (++NumFPRsUsed <= NumFPRs) 5519 continue; 5520 } else { 5521 if (++NumVRsUsed <= NumVRs) 5522 continue; 5523 } 5524 break; 5525 case MVT::f32: 5526 case MVT::f64: 5527 case MVT::v4f64: // QPX 5528 case MVT::v4i1: // QPX 5529 if (++NumFPRsUsed <= NumFPRs) 5530 continue; 5531 break; 5532 } 5533 HasParameterArea = true; 5534 } 5535 } 5536 5537 /* Respect alignment of argument on the stack. */ 5538 unsigned Align = 5539 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5540 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5541 5542 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5543 if (Flags.isInConsecutiveRegsLast()) 5544 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5545 } 5546 5547 unsigned NumBytesActuallyUsed = NumBytes; 5548 5549 // In the old ELFv1 ABI, 5550 // the prolog code of the callee may store up to 8 GPR argument registers to 5551 // the stack, allowing va_start to index over them in memory if its varargs. 5552 // Because we cannot tell if this is needed on the caller side, we have to 5553 // conservatively assume that it is needed. As such, make sure we have at 5554 // least enough stack space for the caller to store the 8 GPRs. 5555 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5556 // really requires memory operands, e.g. a vararg function. 5557 if (HasParameterArea) 5558 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5559 else 5560 NumBytes = LinkageSize; 5561 5562 // Tail call needs the stack to be aligned. 5563 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5564 CallConv == CallingConv::Fast) 5565 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5566 5567 int SPDiff = 0; 5568 5569 // Calculate by how many bytes the stack has to be adjusted in case of tail 5570 // call optimization. 5571 if (!IsSibCall) 5572 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5573 5574 // To protect arguments on the stack from being clobbered in a tail call, 5575 // force all the loads to happen before doing any other lowering. 5576 if (isTailCall) 5577 Chain = DAG.getStackArgumentTokenFactor(Chain); 5578 5579 // Adjust the stack pointer for the new arguments... 5580 // These operations are automatically eliminated by the prolog/epilog pass 5581 if (!IsSibCall) 5582 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5583 SDValue CallSeqStart = Chain; 5584 5585 // Load the return address and frame pointer so it can be move somewhere else 5586 // later. 5587 SDValue LROp, FPOp; 5588 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5589 5590 // Set up a copy of the stack pointer for use loading and storing any 5591 // arguments that may not fit in the registers available for argument 5592 // passing. 5593 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5594 5595 // Figure out which arguments are going to go in registers, and which in 5596 // memory. Also, if this is a vararg function, floating point operations 5597 // must be stored to our stack, and loaded into integer regs as well, if 5598 // any integer regs are available for argument passing. 5599 unsigned ArgOffset = LinkageSize; 5600 5601 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5602 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5603 5604 SmallVector<SDValue, 8> MemOpChains; 5605 for (unsigned i = 0; i != NumOps; ++i) { 5606 SDValue Arg = OutVals[i]; 5607 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5608 EVT ArgVT = Outs[i].VT; 5609 EVT OrigVT = Outs[i].ArgVT; 5610 5611 // PtrOff will be used to store the current argument to the stack if a 5612 // register cannot be found for it. 5613 SDValue PtrOff; 5614 5615 // We re-align the argument offset for each argument, except when using the 5616 // fast calling convention, when we need to make sure we do that only when 5617 // we'll actually use a stack slot. 5618 auto ComputePtrOff = [&]() { 5619 /* Respect alignment of argument on the stack. */ 5620 unsigned Align = 5621 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5622 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5623 5624 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5625 5626 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5627 }; 5628 5629 if (CallConv != CallingConv::Fast) { 5630 ComputePtrOff(); 5631 5632 /* Compute GPR index associated with argument offset. */ 5633 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5634 GPR_idx = std::min(GPR_idx, NumGPRs); 5635 } 5636 5637 // Promote integers to 64-bit values. 5638 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5639 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5640 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5641 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5642 } 5643 5644 // FIXME memcpy is used way more than necessary. Correctness first. 5645 // Note: "by value" is code for passing a structure by value, not 5646 // basic types. 5647 if (Flags.isByVal()) { 5648 // Note: Size includes alignment padding, so 5649 // struct x { short a; char b; } 5650 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5651 // These are the proper values we need for right-justifying the 5652 // aggregate in a parameter register. 5653 unsigned Size = Flags.getByValSize(); 5654 5655 // An empty aggregate parameter takes up no storage and no 5656 // registers. 5657 if (Size == 0) 5658 continue; 5659 5660 if (CallConv == CallingConv::Fast) 5661 ComputePtrOff(); 5662 5663 // All aggregates smaller than 8 bytes must be passed right-justified. 5664 if (Size==1 || Size==2 || Size==4) { 5665 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5666 if (GPR_idx != NumGPRs) { 5667 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5668 MachinePointerInfo(), VT); 5669 MemOpChains.push_back(Load.getValue(1)); 5670 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5671 5672 ArgOffset += PtrByteSize; 5673 continue; 5674 } 5675 } 5676 5677 if (GPR_idx == NumGPRs && Size < 8) { 5678 SDValue AddPtr = PtrOff; 5679 if (!isLittleEndian) { 5680 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5681 PtrOff.getValueType()); 5682 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5683 } 5684 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5685 CallSeqStart, 5686 Flags, DAG, dl); 5687 ArgOffset += PtrByteSize; 5688 continue; 5689 } 5690 // Copy entire object into memory. There are cases where gcc-generated 5691 // code assumes it is there, even if it could be put entirely into 5692 // registers. (This is not what the doc says.) 5693 5694 // FIXME: The above statement is likely due to a misunderstanding of the 5695 // documents. All arguments must be copied into the parameter area BY 5696 // THE CALLEE in the event that the callee takes the address of any 5697 // formal argument. That has not yet been implemented. However, it is 5698 // reasonable to use the stack area as a staging area for the register 5699 // load. 5700 5701 // Skip this for small aggregates, as we will use the same slot for a 5702 // right-justified copy, below. 5703 if (Size >= 8) 5704 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5705 CallSeqStart, 5706 Flags, DAG, dl); 5707 5708 // When a register is available, pass a small aggregate right-justified. 5709 if (Size < 8 && GPR_idx != NumGPRs) { 5710 // The easiest way to get this right-justified in a register 5711 // is to copy the structure into the rightmost portion of a 5712 // local variable slot, then load the whole slot into the 5713 // register. 5714 // FIXME: The memcpy seems to produce pretty awful code for 5715 // small aggregates, particularly for packed ones. 5716 // FIXME: It would be preferable to use the slot in the 5717 // parameter save area instead of a new local variable. 5718 SDValue AddPtr = PtrOff; 5719 if (!isLittleEndian) { 5720 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5721 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5722 } 5723 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5724 CallSeqStart, 5725 Flags, DAG, dl); 5726 5727 // Load the slot into the register. 5728 SDValue Load = 5729 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5730 MemOpChains.push_back(Load.getValue(1)); 5731 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5732 5733 // Done with this argument. 5734 ArgOffset += PtrByteSize; 5735 continue; 5736 } 5737 5738 // For aggregates larger than PtrByteSize, copy the pieces of the 5739 // object that fit into registers from the parameter save area. 5740 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5741 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5742 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5743 if (GPR_idx != NumGPRs) { 5744 SDValue Load = 5745 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5746 MemOpChains.push_back(Load.getValue(1)); 5747 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5748 ArgOffset += PtrByteSize; 5749 } else { 5750 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5751 break; 5752 } 5753 } 5754 continue; 5755 } 5756 5757 switch (Arg.getSimpleValueType().SimpleTy) { 5758 default: llvm_unreachable("Unexpected ValueType for argument!"); 5759 case MVT::i1: 5760 case MVT::i32: 5761 case MVT::i64: 5762 if (Flags.isNest()) { 5763 // The 'nest' parameter, if any, is passed in R11. 5764 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5765 hasNest = true; 5766 break; 5767 } 5768 5769 // These can be scalar arguments or elements of an integer array type 5770 // passed directly. Clang may use those instead of "byval" aggregate 5771 // types to avoid forcing arguments to memory unnecessarily. 5772 if (GPR_idx != NumGPRs) { 5773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5774 } else { 5775 if (CallConv == CallingConv::Fast) 5776 ComputePtrOff(); 5777 5778 assert(HasParameterArea && 5779 "Parameter area must exist to pass an argument in memory."); 5780 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5781 true, isTailCall, false, MemOpChains, 5782 TailCallArguments, dl); 5783 if (CallConv == CallingConv::Fast) 5784 ArgOffset += PtrByteSize; 5785 } 5786 if (CallConv != CallingConv::Fast) 5787 ArgOffset += PtrByteSize; 5788 break; 5789 case MVT::f32: 5790 case MVT::f64: { 5791 // These can be scalar arguments or elements of a float array type 5792 // passed directly. The latter are used to implement ELFv2 homogenous 5793 // float aggregates. 5794 5795 // Named arguments go into FPRs first, and once they overflow, the 5796 // remaining arguments go into GPRs and then the parameter save area. 5797 // Unnamed arguments for vararg functions always go to GPRs and 5798 // then the parameter save area. For now, put all arguments to vararg 5799 // routines always in both locations (FPR *and* GPR or stack slot). 5800 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5801 bool NeededLoad = false; 5802 5803 // First load the argument into the next available FPR. 5804 if (FPR_idx != NumFPRs) 5805 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5806 5807 // Next, load the argument into GPR or stack slot if needed. 5808 if (!NeedGPROrStack) 5809 ; 5810 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5811 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5812 // once we support fp <-> gpr moves. 5813 5814 // In the non-vararg case, this can only ever happen in the 5815 // presence of f32 array types, since otherwise we never run 5816 // out of FPRs before running out of GPRs. 5817 SDValue ArgVal; 5818 5819 // Double values are always passed in a single GPR. 5820 if (Arg.getValueType() != MVT::f32) { 5821 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5822 5823 // Non-array float values are extended and passed in a GPR. 5824 } else if (!Flags.isInConsecutiveRegs()) { 5825 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5826 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5827 5828 // If we have an array of floats, we collect every odd element 5829 // together with its predecessor into one GPR. 5830 } else if (ArgOffset % PtrByteSize != 0) { 5831 SDValue Lo, Hi; 5832 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5833 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5834 if (!isLittleEndian) 5835 std::swap(Lo, Hi); 5836 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5837 5838 // The final element, if even, goes into the first half of a GPR. 5839 } else if (Flags.isInConsecutiveRegsLast()) { 5840 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5841 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5842 if (!isLittleEndian) 5843 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5844 DAG.getConstant(32, dl, MVT::i32)); 5845 5846 // Non-final even elements are skipped; they will be handled 5847 // together the with subsequent argument on the next go-around. 5848 } else 5849 ArgVal = SDValue(); 5850 5851 if (ArgVal.getNode()) 5852 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5853 } else { 5854 if (CallConv == CallingConv::Fast) 5855 ComputePtrOff(); 5856 5857 // Single-precision floating-point values are mapped to the 5858 // second (rightmost) word of the stack doubleword. 5859 if (Arg.getValueType() == MVT::f32 && 5860 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5861 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5862 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5863 } 5864 5865 assert(HasParameterArea && 5866 "Parameter area must exist to pass an argument in memory."); 5867 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5868 true, isTailCall, false, MemOpChains, 5869 TailCallArguments, dl); 5870 5871 NeededLoad = true; 5872 } 5873 // When passing an array of floats, the array occupies consecutive 5874 // space in the argument area; only round up to the next doubleword 5875 // at the end of the array. Otherwise, each float takes 8 bytes. 5876 if (CallConv != CallingConv::Fast || NeededLoad) { 5877 ArgOffset += (Arg.getValueType() == MVT::f32 && 5878 Flags.isInConsecutiveRegs()) ? 4 : 8; 5879 if (Flags.isInConsecutiveRegsLast()) 5880 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5881 } 5882 break; 5883 } 5884 case MVT::v4f32: 5885 case MVT::v4i32: 5886 case MVT::v8i16: 5887 case MVT::v16i8: 5888 case MVT::v2f64: 5889 case MVT::v2i64: 5890 case MVT::v1i128: 5891 if (!Subtarget.hasQPX()) { 5892 // These can be scalar arguments or elements of a vector array type 5893 // passed directly. The latter are used to implement ELFv2 homogenous 5894 // vector aggregates. 5895 5896 // For a varargs call, named arguments go into VRs or on the stack as 5897 // usual; unnamed arguments always go to the stack or the corresponding 5898 // GPRs when within range. For now, we always put the value in both 5899 // locations (or even all three). 5900 if (isVarArg) { 5901 assert(HasParameterArea && 5902 "Parameter area must exist if we have a varargs call."); 5903 // We could elide this store in the case where the object fits 5904 // entirely in R registers. Maybe later. 5905 SDValue Store = 5906 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5907 MemOpChains.push_back(Store); 5908 if (VR_idx != NumVRs) { 5909 SDValue Load = 5910 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5911 MemOpChains.push_back(Load.getValue(1)); 5912 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5913 } 5914 ArgOffset += 16; 5915 for (unsigned i=0; i<16; i+=PtrByteSize) { 5916 if (GPR_idx == NumGPRs) 5917 break; 5918 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5919 DAG.getConstant(i, dl, PtrVT)); 5920 SDValue Load = 5921 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5922 MemOpChains.push_back(Load.getValue(1)); 5923 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5924 } 5925 break; 5926 } 5927 5928 // Non-varargs Altivec params go into VRs or on the stack. 5929 if (VR_idx != NumVRs) { 5930 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5931 } else { 5932 if (CallConv == CallingConv::Fast) 5933 ComputePtrOff(); 5934 5935 assert(HasParameterArea && 5936 "Parameter area must exist to pass an argument in memory."); 5937 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5938 true, isTailCall, true, MemOpChains, 5939 TailCallArguments, dl); 5940 if (CallConv == CallingConv::Fast) 5941 ArgOffset += 16; 5942 } 5943 5944 if (CallConv != CallingConv::Fast) 5945 ArgOffset += 16; 5946 break; 5947 } // not QPX 5948 5949 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5950 "Invalid QPX parameter type"); 5951 5952 /* fall through */ 5953 case MVT::v4f64: 5954 case MVT::v4i1: { 5955 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5956 if (isVarArg) { 5957 assert(HasParameterArea && 5958 "Parameter area must exist if we have a varargs call."); 5959 // We could elide this store in the case where the object fits 5960 // entirely in R registers. Maybe later. 5961 SDValue Store = 5962 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5963 MemOpChains.push_back(Store); 5964 if (QFPR_idx != NumQFPRs) { 5965 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5966 PtrOff, MachinePointerInfo()); 5967 MemOpChains.push_back(Load.getValue(1)); 5968 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5969 } 5970 ArgOffset += (IsF32 ? 16 : 32); 5971 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5972 if (GPR_idx == NumGPRs) 5973 break; 5974 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5975 DAG.getConstant(i, dl, PtrVT)); 5976 SDValue Load = 5977 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5978 MemOpChains.push_back(Load.getValue(1)); 5979 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5980 } 5981 break; 5982 } 5983 5984 // Non-varargs QPX params go into registers or on the stack. 5985 if (QFPR_idx != NumQFPRs) { 5986 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5987 } else { 5988 if (CallConv == CallingConv::Fast) 5989 ComputePtrOff(); 5990 5991 assert(HasParameterArea && 5992 "Parameter area must exist to pass an argument in memory."); 5993 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5994 true, isTailCall, true, MemOpChains, 5995 TailCallArguments, dl); 5996 if (CallConv == CallingConv::Fast) 5997 ArgOffset += (IsF32 ? 16 : 32); 5998 } 5999 6000 if (CallConv != CallingConv::Fast) 6001 ArgOffset += (IsF32 ? 16 : 32); 6002 break; 6003 } 6004 } 6005 } 6006 6007 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6008 "mismatch in size of parameter area"); 6009 (void)NumBytesActuallyUsed; 6010 6011 if (!MemOpChains.empty()) 6012 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6013 6014 // Check if this is an indirect call (MTCTR/BCTRL). 6015 // See PrepareCall() for more information about calls through function 6016 // pointers in the 64-bit SVR4 ABI. 6017 if (!isTailCall && !isPatchPoint && 6018 !isFunctionGlobalAddress(Callee) && 6019 !isa<ExternalSymbolSDNode>(Callee)) { 6020 // Load r2 into a virtual register and store it to the TOC save area. 6021 setUsesTOCBasePtr(DAG); 6022 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6023 // TOC save area offset. 6024 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6025 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6026 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6027 Chain = DAG.getStore( 6028 Val.getValue(1), dl, Val, AddPtr, 6029 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6030 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6031 // This does not mean the MTCTR instruction must use R12; it's easier 6032 // to model this as an extra parameter, so do that. 6033 if (isELFv2ABI && !isPatchPoint) 6034 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6035 } 6036 6037 // Build a sequence of copy-to-reg nodes chained together with token chain 6038 // and flag operands which copy the outgoing args into the appropriate regs. 6039 SDValue InFlag; 6040 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6041 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6042 RegsToPass[i].second, InFlag); 6043 InFlag = Chain.getValue(1); 6044 } 6045 6046 if (isTailCall && !IsSibCall) 6047 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6048 TailCallArguments); 6049 6050 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6051 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6052 SPDiff, NumBytes, Ins, InVals, CS); 6053 } 6054 6055 SDValue PPCTargetLowering::LowerCall_Darwin( 6056 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6057 bool isTailCall, bool isPatchPoint, 6058 const SmallVectorImpl<ISD::OutputArg> &Outs, 6059 const SmallVectorImpl<SDValue> &OutVals, 6060 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6061 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6062 ImmutableCallSite CS) const { 6063 unsigned NumOps = Outs.size(); 6064 6065 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6066 bool isPPC64 = PtrVT == MVT::i64; 6067 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6068 6069 MachineFunction &MF = DAG.getMachineFunction(); 6070 6071 // Mark this function as potentially containing a function that contains a 6072 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6073 // and restoring the callers stack pointer in this functions epilog. This is 6074 // done because by tail calling the called function might overwrite the value 6075 // in this function's (MF) stack pointer stack slot 0(SP). 6076 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6077 CallConv == CallingConv::Fast) 6078 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6079 6080 // Count how many bytes are to be pushed on the stack, including the linkage 6081 // area, and parameter passing area. We start with 24/48 bytes, which is 6082 // prereserved space for [SP][CR][LR][3 x unused]. 6083 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6084 unsigned NumBytes = LinkageSize; 6085 6086 // Add up all the space actually used. 6087 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6088 // they all go in registers, but we must reserve stack space for them for 6089 // possible use by the caller. In varargs or 64-bit calls, parameters are 6090 // assigned stack space in order, with padding so Altivec parameters are 6091 // 16-byte aligned. 6092 unsigned nAltivecParamsAtEnd = 0; 6093 for (unsigned i = 0; i != NumOps; ++i) { 6094 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6095 EVT ArgVT = Outs[i].VT; 6096 // Varargs Altivec parameters are padded to a 16 byte boundary. 6097 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6098 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6099 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6100 if (!isVarArg && !isPPC64) { 6101 // Non-varargs Altivec parameters go after all the non-Altivec 6102 // parameters; handle those later so we know how much padding we need. 6103 nAltivecParamsAtEnd++; 6104 continue; 6105 } 6106 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6107 NumBytes = ((NumBytes+15)/16)*16; 6108 } 6109 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6110 } 6111 6112 // Allow for Altivec parameters at the end, if needed. 6113 if (nAltivecParamsAtEnd) { 6114 NumBytes = ((NumBytes+15)/16)*16; 6115 NumBytes += 16*nAltivecParamsAtEnd; 6116 } 6117 6118 // The prolog code of the callee may store up to 8 GPR argument registers to 6119 // the stack, allowing va_start to index over them in memory if its varargs. 6120 // Because we cannot tell if this is needed on the caller side, we have to 6121 // conservatively assume that it is needed. As such, make sure we have at 6122 // least enough stack space for the caller to store the 8 GPRs. 6123 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6124 6125 // Tail call needs the stack to be aligned. 6126 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6127 CallConv == CallingConv::Fast) 6128 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6129 6130 // Calculate by how many bytes the stack has to be adjusted in case of tail 6131 // call optimization. 6132 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6133 6134 // To protect arguments on the stack from being clobbered in a tail call, 6135 // force all the loads to happen before doing any other lowering. 6136 if (isTailCall) 6137 Chain = DAG.getStackArgumentTokenFactor(Chain); 6138 6139 // Adjust the stack pointer for the new arguments... 6140 // These operations are automatically eliminated by the prolog/epilog pass 6141 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6142 SDValue CallSeqStart = Chain; 6143 6144 // Load the return address and frame pointer so it can be move somewhere else 6145 // later. 6146 SDValue LROp, FPOp; 6147 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6148 6149 // Set up a copy of the stack pointer for use loading and storing any 6150 // arguments that may not fit in the registers available for argument 6151 // passing. 6152 SDValue StackPtr; 6153 if (isPPC64) 6154 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6155 else 6156 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6157 6158 // Figure out which arguments are going to go in registers, and which in 6159 // memory. Also, if this is a vararg function, floating point operations 6160 // must be stored to our stack, and loaded into integer regs as well, if 6161 // any integer regs are available for argument passing. 6162 unsigned ArgOffset = LinkageSize; 6163 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6164 6165 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6166 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6167 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6168 }; 6169 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6170 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6171 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6172 }; 6173 static const MCPhysReg VR[] = { 6174 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6175 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6176 }; 6177 const unsigned NumGPRs = array_lengthof(GPR_32); 6178 const unsigned NumFPRs = 13; 6179 const unsigned NumVRs = array_lengthof(VR); 6180 6181 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6182 6183 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6184 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6185 6186 SmallVector<SDValue, 8> MemOpChains; 6187 for (unsigned i = 0; i != NumOps; ++i) { 6188 SDValue Arg = OutVals[i]; 6189 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6190 6191 // PtrOff will be used to store the current argument to the stack if a 6192 // register cannot be found for it. 6193 SDValue PtrOff; 6194 6195 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6196 6197 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6198 6199 // On PPC64, promote integers to 64-bit values. 6200 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6201 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6202 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6203 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6204 } 6205 6206 // FIXME memcpy is used way more than necessary. Correctness first. 6207 // Note: "by value" is code for passing a structure by value, not 6208 // basic types. 6209 if (Flags.isByVal()) { 6210 unsigned Size = Flags.getByValSize(); 6211 // Very small objects are passed right-justified. Everything else is 6212 // passed left-justified. 6213 if (Size==1 || Size==2) { 6214 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6215 if (GPR_idx != NumGPRs) { 6216 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6217 MachinePointerInfo(), VT); 6218 MemOpChains.push_back(Load.getValue(1)); 6219 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6220 6221 ArgOffset += PtrByteSize; 6222 } else { 6223 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6224 PtrOff.getValueType()); 6225 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6226 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6227 CallSeqStart, 6228 Flags, DAG, dl); 6229 ArgOffset += PtrByteSize; 6230 } 6231 continue; 6232 } 6233 // Copy entire object into memory. There are cases where gcc-generated 6234 // code assumes it is there, even if it could be put entirely into 6235 // registers. (This is not what the doc says.) 6236 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6237 CallSeqStart, 6238 Flags, DAG, dl); 6239 6240 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6241 // copy the pieces of the object that fit into registers from the 6242 // parameter save area. 6243 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6244 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6245 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6246 if (GPR_idx != NumGPRs) { 6247 SDValue Load = 6248 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6249 MemOpChains.push_back(Load.getValue(1)); 6250 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6251 ArgOffset += PtrByteSize; 6252 } else { 6253 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6254 break; 6255 } 6256 } 6257 continue; 6258 } 6259 6260 switch (Arg.getSimpleValueType().SimpleTy) { 6261 default: llvm_unreachable("Unexpected ValueType for argument!"); 6262 case MVT::i1: 6263 case MVT::i32: 6264 case MVT::i64: 6265 if (GPR_idx != NumGPRs) { 6266 if (Arg.getValueType() == MVT::i1) 6267 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6268 6269 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6270 } else { 6271 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6272 isPPC64, isTailCall, false, MemOpChains, 6273 TailCallArguments, dl); 6274 } 6275 ArgOffset += PtrByteSize; 6276 break; 6277 case MVT::f32: 6278 case MVT::f64: 6279 if (FPR_idx != NumFPRs) { 6280 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6281 6282 if (isVarArg) { 6283 SDValue Store = 6284 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6285 MemOpChains.push_back(Store); 6286 6287 // Float varargs are always shadowed in available integer registers 6288 if (GPR_idx != NumGPRs) { 6289 SDValue Load = 6290 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6291 MemOpChains.push_back(Load.getValue(1)); 6292 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6293 } 6294 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6295 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6296 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6297 SDValue Load = 6298 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6299 MemOpChains.push_back(Load.getValue(1)); 6300 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6301 } 6302 } else { 6303 // If we have any FPRs remaining, we may also have GPRs remaining. 6304 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6305 // GPRs. 6306 if (GPR_idx != NumGPRs) 6307 ++GPR_idx; 6308 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6309 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6310 ++GPR_idx; 6311 } 6312 } else 6313 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6314 isPPC64, isTailCall, false, MemOpChains, 6315 TailCallArguments, dl); 6316 if (isPPC64) 6317 ArgOffset += 8; 6318 else 6319 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6320 break; 6321 case MVT::v4f32: 6322 case MVT::v4i32: 6323 case MVT::v8i16: 6324 case MVT::v16i8: 6325 if (isVarArg) { 6326 // These go aligned on the stack, or in the corresponding R registers 6327 // when within range. The Darwin PPC ABI doc claims they also go in 6328 // V registers; in fact gcc does this only for arguments that are 6329 // prototyped, not for those that match the ... We do it for all 6330 // arguments, seems to work. 6331 while (ArgOffset % 16 !=0) { 6332 ArgOffset += PtrByteSize; 6333 if (GPR_idx != NumGPRs) 6334 GPR_idx++; 6335 } 6336 // We could elide this store in the case where the object fits 6337 // entirely in R registers. Maybe later. 6338 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6339 DAG.getConstant(ArgOffset, dl, PtrVT)); 6340 SDValue Store = 6341 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6342 MemOpChains.push_back(Store); 6343 if (VR_idx != NumVRs) { 6344 SDValue Load = 6345 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6346 MemOpChains.push_back(Load.getValue(1)); 6347 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6348 } 6349 ArgOffset += 16; 6350 for (unsigned i=0; i<16; i+=PtrByteSize) { 6351 if (GPR_idx == NumGPRs) 6352 break; 6353 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6354 DAG.getConstant(i, dl, PtrVT)); 6355 SDValue Load = 6356 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6357 MemOpChains.push_back(Load.getValue(1)); 6358 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6359 } 6360 break; 6361 } 6362 6363 // Non-varargs Altivec params generally go in registers, but have 6364 // stack space allocated at the end. 6365 if (VR_idx != NumVRs) { 6366 // Doesn't have GPR space allocated. 6367 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6368 } else if (nAltivecParamsAtEnd==0) { 6369 // We are emitting Altivec params in order. 6370 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6371 isPPC64, isTailCall, true, MemOpChains, 6372 TailCallArguments, dl); 6373 ArgOffset += 16; 6374 } 6375 break; 6376 } 6377 } 6378 // If all Altivec parameters fit in registers, as they usually do, 6379 // they get stack space following the non-Altivec parameters. We 6380 // don't track this here because nobody below needs it. 6381 // If there are more Altivec parameters than fit in registers emit 6382 // the stores here. 6383 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6384 unsigned j = 0; 6385 // Offset is aligned; skip 1st 12 params which go in V registers. 6386 ArgOffset = ((ArgOffset+15)/16)*16; 6387 ArgOffset += 12*16; 6388 for (unsigned i = 0; i != NumOps; ++i) { 6389 SDValue Arg = OutVals[i]; 6390 EVT ArgType = Outs[i].VT; 6391 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6392 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6393 if (++j > NumVRs) { 6394 SDValue PtrOff; 6395 // We are emitting Altivec params in order. 6396 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6397 isPPC64, isTailCall, true, MemOpChains, 6398 TailCallArguments, dl); 6399 ArgOffset += 16; 6400 } 6401 } 6402 } 6403 } 6404 6405 if (!MemOpChains.empty()) 6406 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6407 6408 // On Darwin, R12 must contain the address of an indirect callee. This does 6409 // not mean the MTCTR instruction must use R12; it's easier to model this as 6410 // an extra parameter, so do that. 6411 if (!isTailCall && 6412 !isFunctionGlobalAddress(Callee) && 6413 !isa<ExternalSymbolSDNode>(Callee) && 6414 !isBLACompatibleAddress(Callee, DAG)) 6415 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6416 PPC::R12), Callee)); 6417 6418 // Build a sequence of copy-to-reg nodes chained together with token chain 6419 // and flag operands which copy the outgoing args into the appropriate regs. 6420 SDValue InFlag; 6421 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6422 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6423 RegsToPass[i].second, InFlag); 6424 InFlag = Chain.getValue(1); 6425 } 6426 6427 if (isTailCall) 6428 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6429 TailCallArguments); 6430 6431 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6432 /* unused except on PPC64 ELFv1 */ false, DAG, 6433 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6434 NumBytes, Ins, InVals, CS); 6435 } 6436 6437 bool 6438 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6439 MachineFunction &MF, bool isVarArg, 6440 const SmallVectorImpl<ISD::OutputArg> &Outs, 6441 LLVMContext &Context) const { 6442 SmallVector<CCValAssign, 16> RVLocs; 6443 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6444 return CCInfo.CheckReturn( 6445 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6446 ? RetCC_PPC_Cold 6447 : RetCC_PPC); 6448 } 6449 6450 SDValue 6451 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6452 bool isVarArg, 6453 const SmallVectorImpl<ISD::OutputArg> &Outs, 6454 const SmallVectorImpl<SDValue> &OutVals, 6455 const SDLoc &dl, SelectionDAG &DAG) const { 6456 SmallVector<CCValAssign, 16> RVLocs; 6457 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6458 *DAG.getContext()); 6459 CCInfo.AnalyzeReturn(Outs, 6460 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6461 ? RetCC_PPC_Cold 6462 : RetCC_PPC); 6463 6464 SDValue Flag; 6465 SmallVector<SDValue, 4> RetOps(1, Chain); 6466 6467 // Copy the result values into the output registers. 6468 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6469 CCValAssign &VA = RVLocs[i]; 6470 assert(VA.isRegLoc() && "Can only return in registers!"); 6471 6472 SDValue Arg = OutVals[i]; 6473 6474 switch (VA.getLocInfo()) { 6475 default: llvm_unreachable("Unknown loc info!"); 6476 case CCValAssign::Full: break; 6477 case CCValAssign::AExt: 6478 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6479 break; 6480 case CCValAssign::ZExt: 6481 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6482 break; 6483 case CCValAssign::SExt: 6484 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6485 break; 6486 } 6487 6488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6489 Flag = Chain.getValue(1); 6490 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6491 } 6492 6493 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6494 const MCPhysReg *I = 6495 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6496 if (I) { 6497 for (; *I; ++I) { 6498 6499 if (PPC::G8RCRegClass.contains(*I)) 6500 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6501 else if (PPC::F8RCRegClass.contains(*I)) 6502 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6503 else if (PPC::CRRCRegClass.contains(*I)) 6504 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6505 else if (PPC::VRRCRegClass.contains(*I)) 6506 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6507 else 6508 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6509 } 6510 } 6511 6512 RetOps[0] = Chain; // Update chain. 6513 6514 // Add the flag if we have it. 6515 if (Flag.getNode()) 6516 RetOps.push_back(Flag); 6517 6518 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6519 } 6520 6521 SDValue 6522 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6523 SelectionDAG &DAG) const { 6524 SDLoc dl(Op); 6525 6526 // Get the correct type for integers. 6527 EVT IntVT = Op.getValueType(); 6528 6529 // Get the inputs. 6530 SDValue Chain = Op.getOperand(0); 6531 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6532 // Build a DYNAREAOFFSET node. 6533 SDValue Ops[2] = {Chain, FPSIdx}; 6534 SDVTList VTs = DAG.getVTList(IntVT); 6535 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6536 } 6537 6538 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6539 SelectionDAG &DAG) const { 6540 // When we pop the dynamic allocation we need to restore the SP link. 6541 SDLoc dl(Op); 6542 6543 // Get the correct type for pointers. 6544 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6545 6546 // Construct the stack pointer operand. 6547 bool isPPC64 = Subtarget.isPPC64(); 6548 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6549 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6550 6551 // Get the operands for the STACKRESTORE. 6552 SDValue Chain = Op.getOperand(0); 6553 SDValue SaveSP = Op.getOperand(1); 6554 6555 // Load the old link SP. 6556 SDValue LoadLinkSP = 6557 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6558 6559 // Restore the stack pointer. 6560 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6561 6562 // Store the old link SP. 6563 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6564 } 6565 6566 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6567 MachineFunction &MF = DAG.getMachineFunction(); 6568 bool isPPC64 = Subtarget.isPPC64(); 6569 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6570 6571 // Get current frame pointer save index. The users of this index will be 6572 // primarily DYNALLOC instructions. 6573 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6574 int RASI = FI->getReturnAddrSaveIndex(); 6575 6576 // If the frame pointer save index hasn't been defined yet. 6577 if (!RASI) { 6578 // Find out what the fix offset of the frame pointer save area. 6579 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6580 // Allocate the frame index for frame pointer save area. 6581 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6582 // Save the result. 6583 FI->setReturnAddrSaveIndex(RASI); 6584 } 6585 return DAG.getFrameIndex(RASI, PtrVT); 6586 } 6587 6588 SDValue 6589 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6590 MachineFunction &MF = DAG.getMachineFunction(); 6591 bool isPPC64 = Subtarget.isPPC64(); 6592 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6593 6594 // Get current frame pointer save index. The users of this index will be 6595 // primarily DYNALLOC instructions. 6596 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6597 int FPSI = FI->getFramePointerSaveIndex(); 6598 6599 // If the frame pointer save index hasn't been defined yet. 6600 if (!FPSI) { 6601 // Find out what the fix offset of the frame pointer save area. 6602 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6603 // Allocate the frame index for frame pointer save area. 6604 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6605 // Save the result. 6606 FI->setFramePointerSaveIndex(FPSI); 6607 } 6608 return DAG.getFrameIndex(FPSI, PtrVT); 6609 } 6610 6611 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6612 SelectionDAG &DAG) const { 6613 // Get the inputs. 6614 SDValue Chain = Op.getOperand(0); 6615 SDValue Size = Op.getOperand(1); 6616 SDLoc dl(Op); 6617 6618 // Get the correct type for pointers. 6619 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6620 // Negate the size. 6621 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6622 DAG.getConstant(0, dl, PtrVT), Size); 6623 // Construct a node for the frame pointer save index. 6624 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6625 // Build a DYNALLOC node. 6626 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6627 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6628 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6629 } 6630 6631 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6632 SelectionDAG &DAG) const { 6633 MachineFunction &MF = DAG.getMachineFunction(); 6634 6635 bool isPPC64 = Subtarget.isPPC64(); 6636 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6637 6638 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6639 return DAG.getFrameIndex(FI, PtrVT); 6640 } 6641 6642 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6643 SelectionDAG &DAG) const { 6644 SDLoc DL(Op); 6645 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6646 DAG.getVTList(MVT::i32, MVT::Other), 6647 Op.getOperand(0), Op.getOperand(1)); 6648 } 6649 6650 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6651 SelectionDAG &DAG) const { 6652 SDLoc DL(Op); 6653 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6654 Op.getOperand(0), Op.getOperand(1)); 6655 } 6656 6657 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6658 if (Op.getValueType().isVector()) 6659 return LowerVectorLoad(Op, DAG); 6660 6661 assert(Op.getValueType() == MVT::i1 && 6662 "Custom lowering only for i1 loads"); 6663 6664 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6665 6666 SDLoc dl(Op); 6667 LoadSDNode *LD = cast<LoadSDNode>(Op); 6668 6669 SDValue Chain = LD->getChain(); 6670 SDValue BasePtr = LD->getBasePtr(); 6671 MachineMemOperand *MMO = LD->getMemOperand(); 6672 6673 SDValue NewLD = 6674 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6675 BasePtr, MVT::i8, MMO); 6676 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6677 6678 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6679 return DAG.getMergeValues(Ops, dl); 6680 } 6681 6682 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6683 if (Op.getOperand(1).getValueType().isVector()) 6684 return LowerVectorStore(Op, DAG); 6685 6686 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6687 "Custom lowering only for i1 stores"); 6688 6689 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6690 6691 SDLoc dl(Op); 6692 StoreSDNode *ST = cast<StoreSDNode>(Op); 6693 6694 SDValue Chain = ST->getChain(); 6695 SDValue BasePtr = ST->getBasePtr(); 6696 SDValue Value = ST->getValue(); 6697 MachineMemOperand *MMO = ST->getMemOperand(); 6698 6699 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6700 Value); 6701 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6702 } 6703 6704 // FIXME: Remove this once the ANDI glue bug is fixed: 6705 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6706 assert(Op.getValueType() == MVT::i1 && 6707 "Custom lowering only for i1 results"); 6708 6709 SDLoc DL(Op); 6710 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6711 Op.getOperand(0)); 6712 } 6713 6714 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6715 /// possible. 6716 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6717 // Not FP? Not a fsel. 6718 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6719 !Op.getOperand(2).getValueType().isFloatingPoint()) 6720 return Op; 6721 6722 // We might be able to do better than this under some circumstances, but in 6723 // general, fsel-based lowering of select is a finite-math-only optimization. 6724 // For more information, see section F.3 of the 2.06 ISA specification. 6725 if (!DAG.getTarget().Options.NoInfsFPMath || 6726 !DAG.getTarget().Options.NoNaNsFPMath) 6727 return Op; 6728 // TODO: Propagate flags from the select rather than global settings. 6729 SDNodeFlags Flags; 6730 Flags.setNoInfs(true); 6731 Flags.setNoNaNs(true); 6732 6733 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6734 6735 EVT ResVT = Op.getValueType(); 6736 EVT CmpVT = Op.getOperand(0).getValueType(); 6737 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6738 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6739 SDLoc dl(Op); 6740 6741 // If the RHS of the comparison is a 0.0, we don't need to do the 6742 // subtraction at all. 6743 SDValue Sel1; 6744 if (isFloatingPointZero(RHS)) 6745 switch (CC) { 6746 default: break; // SETUO etc aren't handled by fsel. 6747 case ISD::SETNE: 6748 std::swap(TV, FV); 6749 LLVM_FALLTHROUGH; 6750 case ISD::SETEQ: 6751 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6752 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6753 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6754 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6755 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6756 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6757 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6758 case ISD::SETULT: 6759 case ISD::SETLT: 6760 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6761 LLVM_FALLTHROUGH; 6762 case ISD::SETOGE: 6763 case ISD::SETGE: 6764 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6765 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6766 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6767 case ISD::SETUGT: 6768 case ISD::SETGT: 6769 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6770 LLVM_FALLTHROUGH; 6771 case ISD::SETOLE: 6772 case ISD::SETLE: 6773 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6774 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6775 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6776 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6777 } 6778 6779 SDValue Cmp; 6780 switch (CC) { 6781 default: break; // SETUO etc aren't handled by fsel. 6782 case ISD::SETNE: 6783 std::swap(TV, FV); 6784 LLVM_FALLTHROUGH; 6785 case ISD::SETEQ: 6786 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6787 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6788 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6789 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6790 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6791 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6792 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6793 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6794 case ISD::SETULT: 6795 case ISD::SETLT: 6796 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6797 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6798 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6799 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6800 case ISD::SETOGE: 6801 case ISD::SETGE: 6802 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6803 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6804 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6805 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6806 case ISD::SETUGT: 6807 case ISD::SETGT: 6808 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6809 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6810 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6811 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6812 case ISD::SETOLE: 6813 case ISD::SETLE: 6814 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6815 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6816 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6817 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6818 } 6819 return Op; 6820 } 6821 6822 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6823 SelectionDAG &DAG, 6824 const SDLoc &dl) const { 6825 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6826 SDValue Src = Op.getOperand(0); 6827 if (Src.getValueType() == MVT::f32) 6828 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6829 6830 SDValue Tmp; 6831 switch (Op.getSimpleValueType().SimpleTy) { 6832 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6833 case MVT::i32: 6834 Tmp = DAG.getNode( 6835 Op.getOpcode() == ISD::FP_TO_SINT 6836 ? PPCISD::FCTIWZ 6837 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6838 dl, MVT::f64, Src); 6839 break; 6840 case MVT::i64: 6841 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6842 "i64 FP_TO_UINT is supported only with FPCVT"); 6843 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6844 PPCISD::FCTIDUZ, 6845 dl, MVT::f64, Src); 6846 break; 6847 } 6848 6849 // Convert the FP value to an int value through memory. 6850 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6851 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6852 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6853 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6854 MachinePointerInfo MPI = 6855 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6856 6857 // Emit a store to the stack slot. 6858 SDValue Chain; 6859 if (i32Stack) { 6860 MachineFunction &MF = DAG.getMachineFunction(); 6861 MachineMemOperand *MMO = 6862 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6863 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6864 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6865 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6866 } else 6867 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6868 6869 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6870 // add in a bias on big endian. 6871 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6872 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6873 DAG.getConstant(4, dl, FIPtr.getValueType())); 6874 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6875 } 6876 6877 RLI.Chain = Chain; 6878 RLI.Ptr = FIPtr; 6879 RLI.MPI = MPI; 6880 } 6881 6882 /// \brief Custom lowers floating point to integer conversions to use 6883 /// the direct move instructions available in ISA 2.07 to avoid the 6884 /// need for load/store combinations. 6885 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6886 SelectionDAG &DAG, 6887 const SDLoc &dl) const { 6888 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6889 SDValue Src = Op.getOperand(0); 6890 6891 if (Src.getValueType() == MVT::f32) 6892 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6893 6894 SDValue Tmp; 6895 switch (Op.getSimpleValueType().SimpleTy) { 6896 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6897 case MVT::i32: 6898 Tmp = DAG.getNode( 6899 Op.getOpcode() == ISD::FP_TO_SINT 6900 ? PPCISD::FCTIWZ 6901 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6902 dl, MVT::f64, Src); 6903 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6904 break; 6905 case MVT::i64: 6906 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6907 "i64 FP_TO_UINT is supported only with FPCVT"); 6908 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6909 PPCISD::FCTIDUZ, 6910 dl, MVT::f64, Src); 6911 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6912 break; 6913 } 6914 return Tmp; 6915 } 6916 6917 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6918 const SDLoc &dl) const { 6919 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 6920 // PPC (the libcall is not available). 6921 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 6922 if (Op.getValueType() == MVT::i32) { 6923 if (Op.getOpcode() == ISD::FP_TO_SINT) { 6924 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6925 MVT::f64, Op.getOperand(0), 6926 DAG.getIntPtrConstant(0, dl)); 6927 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6928 MVT::f64, Op.getOperand(0), 6929 DAG.getIntPtrConstant(1, dl)); 6930 6931 // Add the two halves of the long double in round-to-zero mode. 6932 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 6933 6934 // Now use a smaller FP_TO_SINT. 6935 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 6936 } 6937 if (Op.getOpcode() == ISD::FP_TO_UINT) { 6938 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 6939 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 6940 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 6941 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 6942 // FIXME: generated code sucks. 6943 // TODO: Are there fast-math-flags to propagate to this FSUB? 6944 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 6945 Op.getOperand(0), Tmp); 6946 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 6947 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 6948 DAG.getConstant(0x80000000, dl, MVT::i32)); 6949 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 6950 Op.getOperand(0)); 6951 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 6952 ISD::SETGE); 6953 } 6954 } 6955 6956 return SDValue(); 6957 } 6958 6959 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6960 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6961 6962 ReuseLoadInfo RLI; 6963 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6964 6965 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6966 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6967 } 6968 6969 // We're trying to insert a regular store, S, and then a load, L. If the 6970 // incoming value, O, is a load, we might just be able to have our load use the 6971 // address used by O. However, we don't know if anything else will store to 6972 // that address before we can load from it. To prevent this situation, we need 6973 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6974 // the same chain operand as O, we create a token factor from the chain results 6975 // of O and L, and we replace all uses of O's chain result with that token 6976 // factor (see spliceIntoChain below for this last part). 6977 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6978 ReuseLoadInfo &RLI, 6979 SelectionDAG &DAG, 6980 ISD::LoadExtType ET) const { 6981 SDLoc dl(Op); 6982 if (ET == ISD::NON_EXTLOAD && 6983 (Op.getOpcode() == ISD::FP_TO_UINT || 6984 Op.getOpcode() == ISD::FP_TO_SINT) && 6985 isOperationLegalOrCustom(Op.getOpcode(), 6986 Op.getOperand(0).getValueType())) { 6987 6988 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6989 return true; 6990 } 6991 6992 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6993 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6994 LD->isNonTemporal()) 6995 return false; 6996 if (LD->getMemoryVT() != MemVT) 6997 return false; 6998 6999 RLI.Ptr = LD->getBasePtr(); 7000 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7001 assert(LD->getAddressingMode() == ISD::PRE_INC && 7002 "Non-pre-inc AM on PPC?"); 7003 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7004 LD->getOffset()); 7005 } 7006 7007 RLI.Chain = LD->getChain(); 7008 RLI.MPI = LD->getPointerInfo(); 7009 RLI.IsDereferenceable = LD->isDereferenceable(); 7010 RLI.IsInvariant = LD->isInvariant(); 7011 RLI.Alignment = LD->getAlignment(); 7012 RLI.AAInfo = LD->getAAInfo(); 7013 RLI.Ranges = LD->getRanges(); 7014 7015 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7016 return true; 7017 } 7018 7019 // Given the head of the old chain, ResChain, insert a token factor containing 7020 // it and NewResChain, and make users of ResChain now be users of that token 7021 // factor. 7022 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7023 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7024 SDValue NewResChain, 7025 SelectionDAG &DAG) const { 7026 if (!ResChain) 7027 return; 7028 7029 SDLoc dl(NewResChain); 7030 7031 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7032 NewResChain, DAG.getUNDEF(MVT::Other)); 7033 assert(TF.getNode() != NewResChain.getNode() && 7034 "A new TF really is required here"); 7035 7036 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7037 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7038 } 7039 7040 /// \brief Analyze profitability of direct move 7041 /// prefer float load to int load plus direct move 7042 /// when there is no integer use of int load 7043 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7044 SDNode *Origin = Op.getOperand(0).getNode(); 7045 if (Origin->getOpcode() != ISD::LOAD) 7046 return true; 7047 7048 // If there is no LXSIBZX/LXSIHZX, like Power8, 7049 // prefer direct move if the memory size is 1 or 2 bytes. 7050 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7051 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7052 return true; 7053 7054 for (SDNode::use_iterator UI = Origin->use_begin(), 7055 UE = Origin->use_end(); 7056 UI != UE; ++UI) { 7057 7058 // Only look at the users of the loaded value. 7059 if (UI.getUse().get().getResNo() != 0) 7060 continue; 7061 7062 if (UI->getOpcode() != ISD::SINT_TO_FP && 7063 UI->getOpcode() != ISD::UINT_TO_FP) 7064 return true; 7065 } 7066 7067 return false; 7068 } 7069 7070 /// \brief Custom lowers integer to floating point conversions to use 7071 /// the direct move instructions available in ISA 2.07 to avoid the 7072 /// need for load/store combinations. 7073 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7074 SelectionDAG &DAG, 7075 const SDLoc &dl) const { 7076 assert((Op.getValueType() == MVT::f32 || 7077 Op.getValueType() == MVT::f64) && 7078 "Invalid floating point type as target of conversion"); 7079 assert(Subtarget.hasFPCVT() && 7080 "Int to FP conversions with direct moves require FPCVT"); 7081 SDValue FP; 7082 SDValue Src = Op.getOperand(0); 7083 bool SinglePrec = Op.getValueType() == MVT::f32; 7084 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7085 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7086 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7087 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7088 7089 if (WordInt) { 7090 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7091 dl, MVT::f64, Src); 7092 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7093 } 7094 else { 7095 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7096 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7097 } 7098 7099 return FP; 7100 } 7101 7102 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7103 SelectionDAG &DAG) const { 7104 SDLoc dl(Op); 7105 7106 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7107 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7108 return SDValue(); 7109 7110 SDValue Value = Op.getOperand(0); 7111 // The values are now known to be -1 (false) or 1 (true). To convert this 7112 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7113 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7114 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7115 7116 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7117 7118 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7119 7120 if (Op.getValueType() != MVT::v4f64) 7121 Value = DAG.getNode(ISD::FP_ROUND, dl, 7122 Op.getValueType(), Value, 7123 DAG.getIntPtrConstant(1, dl)); 7124 return Value; 7125 } 7126 7127 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7128 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7129 return SDValue(); 7130 7131 if (Op.getOperand(0).getValueType() == MVT::i1) 7132 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7133 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7134 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7135 7136 // If we have direct moves, we can do all the conversion, skip the store/load 7137 // however, without FPCVT we can't do most conversions. 7138 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7139 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7140 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7141 7142 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7143 "UINT_TO_FP is supported only with FPCVT"); 7144 7145 // If we have FCFIDS, then use it when converting to single-precision. 7146 // Otherwise, convert to double-precision and then round. 7147 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7148 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7149 : PPCISD::FCFIDS) 7150 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7151 : PPCISD::FCFID); 7152 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7153 ? MVT::f32 7154 : MVT::f64; 7155 7156 if (Op.getOperand(0).getValueType() == MVT::i64) { 7157 SDValue SINT = Op.getOperand(0); 7158 // When converting to single-precision, we actually need to convert 7159 // to double-precision first and then round to single-precision. 7160 // To avoid double-rounding effects during that operation, we have 7161 // to prepare the input operand. Bits that might be truncated when 7162 // converting to double-precision are replaced by a bit that won't 7163 // be lost at this stage, but is below the single-precision rounding 7164 // position. 7165 // 7166 // However, if -enable-unsafe-fp-math is in effect, accept double 7167 // rounding to avoid the extra overhead. 7168 if (Op.getValueType() == MVT::f32 && 7169 !Subtarget.hasFPCVT() && 7170 !DAG.getTarget().Options.UnsafeFPMath) { 7171 7172 // Twiddle input to make sure the low 11 bits are zero. (If this 7173 // is the case, we are guaranteed the value will fit into the 53 bit 7174 // mantissa of an IEEE double-precision value without rounding.) 7175 // If any of those low 11 bits were not zero originally, make sure 7176 // bit 12 (value 2048) is set instead, so that the final rounding 7177 // to single-precision gets the correct result. 7178 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7179 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7180 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7181 Round, DAG.getConstant(2047, dl, MVT::i64)); 7182 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7183 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7184 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7185 7186 // However, we cannot use that value unconditionally: if the magnitude 7187 // of the input value is small, the bit-twiddling we did above might 7188 // end up visibly changing the output. Fortunately, in that case, we 7189 // don't need to twiddle bits since the original input will convert 7190 // exactly to double-precision floating-point already. Therefore, 7191 // construct a conditional to use the original value if the top 11 7192 // bits are all sign-bit copies, and use the rounded value computed 7193 // above otherwise. 7194 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7195 SINT, DAG.getConstant(53, dl, MVT::i32)); 7196 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7197 Cond, DAG.getConstant(1, dl, MVT::i64)); 7198 Cond = DAG.getSetCC(dl, MVT::i32, 7199 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7200 7201 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7202 } 7203 7204 ReuseLoadInfo RLI; 7205 SDValue Bits; 7206 7207 MachineFunction &MF = DAG.getMachineFunction(); 7208 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7209 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7210 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7211 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7212 } else if (Subtarget.hasLFIWAX() && 7213 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7214 MachineMemOperand *MMO = 7215 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7216 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7217 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7218 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7219 DAG.getVTList(MVT::f64, MVT::Other), 7220 Ops, MVT::i32, MMO); 7221 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7222 } else if (Subtarget.hasFPCVT() && 7223 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7224 MachineMemOperand *MMO = 7225 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7226 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7227 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7228 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7229 DAG.getVTList(MVT::f64, MVT::Other), 7230 Ops, MVT::i32, MMO); 7231 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7232 } else if (((Subtarget.hasLFIWAX() && 7233 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7234 (Subtarget.hasFPCVT() && 7235 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7236 SINT.getOperand(0).getValueType() == MVT::i32) { 7237 MachineFrameInfo &MFI = MF.getFrameInfo(); 7238 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7239 7240 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7241 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7242 7243 SDValue Store = 7244 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7245 MachinePointerInfo::getFixedStack( 7246 DAG.getMachineFunction(), FrameIdx)); 7247 7248 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7249 "Expected an i32 store"); 7250 7251 RLI.Ptr = FIdx; 7252 RLI.Chain = Store; 7253 RLI.MPI = 7254 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7255 RLI.Alignment = 4; 7256 7257 MachineMemOperand *MMO = 7258 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7259 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7260 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7261 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7262 PPCISD::LFIWZX : PPCISD::LFIWAX, 7263 dl, DAG.getVTList(MVT::f64, MVT::Other), 7264 Ops, MVT::i32, MMO); 7265 } else 7266 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7267 7268 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7269 7270 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7271 FP = DAG.getNode(ISD::FP_ROUND, dl, 7272 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7273 return FP; 7274 } 7275 7276 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7277 "Unhandled INT_TO_FP type in custom expander!"); 7278 // Since we only generate this in 64-bit mode, we can take advantage of 7279 // 64-bit registers. In particular, sign extend the input value into the 7280 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7281 // then lfd it and fcfid it. 7282 MachineFunction &MF = DAG.getMachineFunction(); 7283 MachineFrameInfo &MFI = MF.getFrameInfo(); 7284 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7285 7286 SDValue Ld; 7287 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7288 ReuseLoadInfo RLI; 7289 bool ReusingLoad; 7290 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7291 DAG))) { 7292 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7293 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7294 7295 SDValue Store = 7296 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7297 MachinePointerInfo::getFixedStack( 7298 DAG.getMachineFunction(), FrameIdx)); 7299 7300 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7301 "Expected an i32 store"); 7302 7303 RLI.Ptr = FIdx; 7304 RLI.Chain = Store; 7305 RLI.MPI = 7306 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7307 RLI.Alignment = 4; 7308 } 7309 7310 MachineMemOperand *MMO = 7311 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7312 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7313 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7314 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7315 PPCISD::LFIWZX : PPCISD::LFIWAX, 7316 dl, DAG.getVTList(MVT::f64, MVT::Other), 7317 Ops, MVT::i32, MMO); 7318 if (ReusingLoad) 7319 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7320 } else { 7321 assert(Subtarget.isPPC64() && 7322 "i32->FP without LFIWAX supported only on PPC64"); 7323 7324 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7325 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7326 7327 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7328 Op.getOperand(0)); 7329 7330 // STD the extended value into the stack slot. 7331 SDValue Store = DAG.getStore( 7332 DAG.getEntryNode(), dl, Ext64, FIdx, 7333 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7334 7335 // Load the value as a double. 7336 Ld = DAG.getLoad( 7337 MVT::f64, dl, Store, FIdx, 7338 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7339 } 7340 7341 // FCFID it and return it. 7342 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7343 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7344 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7345 DAG.getIntPtrConstant(0, dl)); 7346 return FP; 7347 } 7348 7349 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7350 SelectionDAG &DAG) const { 7351 SDLoc dl(Op); 7352 /* 7353 The rounding mode is in bits 30:31 of FPSR, and has the following 7354 settings: 7355 00 Round to nearest 7356 01 Round to 0 7357 10 Round to +inf 7358 11 Round to -inf 7359 7360 FLT_ROUNDS, on the other hand, expects the following: 7361 -1 Undefined 7362 0 Round to 0 7363 1 Round to nearest 7364 2 Round to +inf 7365 3 Round to -inf 7366 7367 To perform the conversion, we do: 7368 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7369 */ 7370 7371 MachineFunction &MF = DAG.getMachineFunction(); 7372 EVT VT = Op.getValueType(); 7373 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7374 7375 // Save FP Control Word to register 7376 EVT NodeTys[] = { 7377 MVT::f64, // return register 7378 MVT::Glue // unused in this context 7379 }; 7380 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7381 7382 // Save FP register to stack slot 7383 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7384 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7385 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7386 MachinePointerInfo()); 7387 7388 // Load FP Control Word from low 32 bits of stack slot. 7389 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7390 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7391 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7392 7393 // Transform as necessary 7394 SDValue CWD1 = 7395 DAG.getNode(ISD::AND, dl, MVT::i32, 7396 CWD, DAG.getConstant(3, dl, MVT::i32)); 7397 SDValue CWD2 = 7398 DAG.getNode(ISD::SRL, dl, MVT::i32, 7399 DAG.getNode(ISD::AND, dl, MVT::i32, 7400 DAG.getNode(ISD::XOR, dl, MVT::i32, 7401 CWD, DAG.getConstant(3, dl, MVT::i32)), 7402 DAG.getConstant(3, dl, MVT::i32)), 7403 DAG.getConstant(1, dl, MVT::i32)); 7404 7405 SDValue RetVal = 7406 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7407 7408 return DAG.getNode((VT.getSizeInBits() < 16 ? 7409 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7410 } 7411 7412 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7413 EVT VT = Op.getValueType(); 7414 unsigned BitWidth = VT.getSizeInBits(); 7415 SDLoc dl(Op); 7416 assert(Op.getNumOperands() == 3 && 7417 VT == Op.getOperand(1).getValueType() && 7418 "Unexpected SHL!"); 7419 7420 // Expand into a bunch of logical ops. Note that these ops 7421 // depend on the PPC behavior for oversized shift amounts. 7422 SDValue Lo = Op.getOperand(0); 7423 SDValue Hi = Op.getOperand(1); 7424 SDValue Amt = Op.getOperand(2); 7425 EVT AmtVT = Amt.getValueType(); 7426 7427 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7428 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7429 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7430 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7431 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7432 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7433 DAG.getConstant(-BitWidth, dl, AmtVT)); 7434 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7435 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7436 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7437 SDValue OutOps[] = { OutLo, OutHi }; 7438 return DAG.getMergeValues(OutOps, dl); 7439 } 7440 7441 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7442 EVT VT = Op.getValueType(); 7443 SDLoc dl(Op); 7444 unsigned BitWidth = VT.getSizeInBits(); 7445 assert(Op.getNumOperands() == 3 && 7446 VT == Op.getOperand(1).getValueType() && 7447 "Unexpected SRL!"); 7448 7449 // Expand into a bunch of logical ops. Note that these ops 7450 // depend on the PPC behavior for oversized shift amounts. 7451 SDValue Lo = Op.getOperand(0); 7452 SDValue Hi = Op.getOperand(1); 7453 SDValue Amt = Op.getOperand(2); 7454 EVT AmtVT = Amt.getValueType(); 7455 7456 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7457 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7458 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7459 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7460 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7461 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7462 DAG.getConstant(-BitWidth, dl, AmtVT)); 7463 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7464 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7465 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7466 SDValue OutOps[] = { OutLo, OutHi }; 7467 return DAG.getMergeValues(OutOps, dl); 7468 } 7469 7470 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7471 SDLoc dl(Op); 7472 EVT VT = Op.getValueType(); 7473 unsigned BitWidth = VT.getSizeInBits(); 7474 assert(Op.getNumOperands() == 3 && 7475 VT == Op.getOperand(1).getValueType() && 7476 "Unexpected SRA!"); 7477 7478 // Expand into a bunch of logical ops, followed by a select_cc. 7479 SDValue Lo = Op.getOperand(0); 7480 SDValue Hi = Op.getOperand(1); 7481 SDValue Amt = Op.getOperand(2); 7482 EVT AmtVT = Amt.getValueType(); 7483 7484 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7485 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7486 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7487 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7488 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7489 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7490 DAG.getConstant(-BitWidth, dl, AmtVT)); 7491 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7492 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7493 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7494 Tmp4, Tmp6, ISD::SETLE); 7495 SDValue OutOps[] = { OutLo, OutHi }; 7496 return DAG.getMergeValues(OutOps, dl); 7497 } 7498 7499 //===----------------------------------------------------------------------===// 7500 // Vector related lowering. 7501 // 7502 7503 /// BuildSplatI - Build a canonical splati of Val with an element size of 7504 /// SplatSize. Cast the result to VT. 7505 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7506 SelectionDAG &DAG, const SDLoc &dl) { 7507 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7508 7509 static const MVT VTys[] = { // canonical VT to use for each size. 7510 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7511 }; 7512 7513 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7514 7515 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7516 if (Val == -1) 7517 SplatSize = 1; 7518 7519 EVT CanonicalVT = VTys[SplatSize-1]; 7520 7521 // Build a canonical splat for this value. 7522 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7523 } 7524 7525 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7526 /// specified intrinsic ID. 7527 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7528 const SDLoc &dl, EVT DestVT = MVT::Other) { 7529 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7530 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7531 DAG.getConstant(IID, dl, MVT::i32), Op); 7532 } 7533 7534 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7535 /// specified intrinsic ID. 7536 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7537 SelectionDAG &DAG, const SDLoc &dl, 7538 EVT DestVT = MVT::Other) { 7539 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7540 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7541 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7542 } 7543 7544 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7545 /// specified intrinsic ID. 7546 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7547 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7548 EVT DestVT = MVT::Other) { 7549 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7550 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7551 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7552 } 7553 7554 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7555 /// amount. The result has the specified value type. 7556 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7557 SelectionDAG &DAG, const SDLoc &dl) { 7558 // Force LHS/RHS to be the right type. 7559 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7560 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7561 7562 int Ops[16]; 7563 for (unsigned i = 0; i != 16; ++i) 7564 Ops[i] = i + Amt; 7565 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7566 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7567 } 7568 7569 /// Do we have an efficient pattern in a .td file for this node? 7570 /// 7571 /// \param V - pointer to the BuildVectorSDNode being matched 7572 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7573 /// 7574 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7575 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7576 /// the opposite is true (expansion is beneficial) are: 7577 /// - The node builds a vector out of integers that are not 32 or 64-bits 7578 /// - The node builds a vector out of constants 7579 /// - The node is a "load-and-splat" 7580 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7581 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7582 bool HasDirectMove, 7583 bool HasP8Vector) { 7584 EVT VecVT = V->getValueType(0); 7585 bool RightType = VecVT == MVT::v2f64 || 7586 (HasP8Vector && VecVT == MVT::v4f32) || 7587 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7588 if (!RightType) 7589 return false; 7590 7591 bool IsSplat = true; 7592 bool IsLoad = false; 7593 SDValue Op0 = V->getOperand(0); 7594 7595 // This function is called in a block that confirms the node is not a constant 7596 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7597 // different constants. 7598 if (V->isConstant()) 7599 return false; 7600 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7601 if (V->getOperand(i).isUndef()) 7602 return false; 7603 // We want to expand nodes that represent load-and-splat even if the 7604 // loaded value is a floating point truncation or conversion to int. 7605 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7606 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7607 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7608 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7609 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7610 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7611 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7612 IsLoad = true; 7613 // If the operands are different or the input is not a load and has more 7614 // uses than just this BV node, then it isn't a splat. 7615 if (V->getOperand(i) != Op0 || 7616 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7617 IsSplat = false; 7618 } 7619 return !(IsSplat && IsLoad); 7620 } 7621 7622 // If this is a case we can't handle, return null and let the default 7623 // expansion code take care of it. If we CAN select this case, and if it 7624 // selects to a single instruction, return Op. Otherwise, if we can codegen 7625 // this case more efficiently than a constant pool load, lower it to the 7626 // sequence of ops that should be used. 7627 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7628 SelectionDAG &DAG) const { 7629 SDLoc dl(Op); 7630 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7631 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7632 7633 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7634 // We first build an i32 vector, load it into a QPX register, 7635 // then convert it to a floating-point vector and compare it 7636 // to a zero vector to get the boolean result. 7637 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7638 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7639 MachinePointerInfo PtrInfo = 7640 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7641 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7642 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7643 7644 assert(BVN->getNumOperands() == 4 && 7645 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7646 7647 bool IsConst = true; 7648 for (unsigned i = 0; i < 4; ++i) { 7649 if (BVN->getOperand(i).isUndef()) continue; 7650 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7651 IsConst = false; 7652 break; 7653 } 7654 } 7655 7656 if (IsConst) { 7657 Constant *One = 7658 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7659 Constant *NegOne = 7660 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7661 7662 Constant *CV[4]; 7663 for (unsigned i = 0; i < 4; ++i) { 7664 if (BVN->getOperand(i).isUndef()) 7665 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7666 else if (isNullConstant(BVN->getOperand(i))) 7667 CV[i] = NegOne; 7668 else 7669 CV[i] = One; 7670 } 7671 7672 Constant *CP = ConstantVector::get(CV); 7673 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7674 16 /* alignment */); 7675 7676 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7677 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7678 return DAG.getMemIntrinsicNode( 7679 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7680 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7681 } 7682 7683 SmallVector<SDValue, 4> Stores; 7684 for (unsigned i = 0; i < 4; ++i) { 7685 if (BVN->getOperand(i).isUndef()) continue; 7686 7687 unsigned Offset = 4*i; 7688 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7689 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7690 7691 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7692 if (StoreSize > 4) { 7693 Stores.push_back( 7694 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7695 PtrInfo.getWithOffset(Offset), MVT::i32)); 7696 } else { 7697 SDValue StoreValue = BVN->getOperand(i); 7698 if (StoreSize < 4) 7699 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7700 7701 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7702 PtrInfo.getWithOffset(Offset))); 7703 } 7704 } 7705 7706 SDValue StoreChain; 7707 if (!Stores.empty()) 7708 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7709 else 7710 StoreChain = DAG.getEntryNode(); 7711 7712 // Now load from v4i32 into the QPX register; this will extend it to 7713 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7714 // is typed as v4f64 because the QPX register integer states are not 7715 // explicitly represented. 7716 7717 SDValue Ops[] = {StoreChain, 7718 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7719 FIdx}; 7720 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7721 7722 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7723 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7724 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7725 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7726 LoadedVect); 7727 7728 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7729 7730 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7731 } 7732 7733 // All other QPX vectors are handled by generic code. 7734 if (Subtarget.hasQPX()) 7735 return SDValue(); 7736 7737 // Check if this is a splat of a constant value. 7738 APInt APSplatBits, APSplatUndef; 7739 unsigned SplatBitSize; 7740 bool HasAnyUndefs; 7741 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7742 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7743 SplatBitSize > 32) { 7744 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7745 // lowered to VSX instructions under certain conditions. 7746 // Without VSX, there is no pattern more efficient than expanding the node. 7747 if (Subtarget.hasVSX() && 7748 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7749 Subtarget.hasP8Vector())) 7750 return Op; 7751 return SDValue(); 7752 } 7753 7754 unsigned SplatBits = APSplatBits.getZExtValue(); 7755 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7756 unsigned SplatSize = SplatBitSize / 8; 7757 7758 // First, handle single instruction cases. 7759 7760 // All zeros? 7761 if (SplatBits == 0) { 7762 // Canonicalize all zero vectors to be v4i32. 7763 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7764 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7765 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7766 } 7767 return Op; 7768 } 7769 7770 // We have XXSPLTIB for constant splats one byte wide 7771 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7772 // This is a splat of 1-byte elements with some elements potentially undef. 7773 // Rather than trying to match undef in the SDAG patterns, ensure that all 7774 // elements are the same constant. 7775 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7776 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7777 dl, MVT::i32)); 7778 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7779 if (Op.getValueType() != MVT::v16i8) 7780 return DAG.getBitcast(Op.getValueType(), NewBV); 7781 return NewBV; 7782 } 7783 7784 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7785 // detect that constant splats like v8i16: 0xABAB are really just splats 7786 // of a 1-byte constant. In this case, we need to convert the node to a 7787 // splat of v16i8 and a bitcast. 7788 if (Op.getValueType() != MVT::v16i8) 7789 return DAG.getBitcast(Op.getValueType(), 7790 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7791 7792 return Op; 7793 } 7794 7795 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7796 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7797 (32-SplatBitSize)); 7798 if (SextVal >= -16 && SextVal <= 15) 7799 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7800 7801 // Two instruction sequences. 7802 7803 // If this value is in the range [-32,30] and is even, use: 7804 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7805 // If this value is in the range [17,31] and is odd, use: 7806 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7807 // If this value is in the range [-31,-17] and is odd, use: 7808 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7809 // Note the last two are three-instruction sequences. 7810 if (SextVal >= -32 && SextVal <= 31) { 7811 // To avoid having these optimizations undone by constant folding, 7812 // we convert to a pseudo that will be expanded later into one of 7813 // the above forms. 7814 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7815 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7816 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7817 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7818 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7819 if (VT == Op.getValueType()) 7820 return RetVal; 7821 else 7822 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7823 } 7824 7825 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7826 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7827 // for fneg/fabs. 7828 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7829 // Make -1 and vspltisw -1: 7830 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7831 7832 // Make the VSLW intrinsic, computing 0x8000_0000. 7833 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7834 OnesV, DAG, dl); 7835 7836 // xor by OnesV to invert it. 7837 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7838 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7839 } 7840 7841 // Check to see if this is a wide variety of vsplti*, binop self cases. 7842 static const signed char SplatCsts[] = { 7843 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7844 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7845 }; 7846 7847 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7848 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7849 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7850 int i = SplatCsts[idx]; 7851 7852 // Figure out what shift amount will be used by altivec if shifted by i in 7853 // this splat size. 7854 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7855 7856 // vsplti + shl self. 7857 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7858 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7859 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7860 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7861 Intrinsic::ppc_altivec_vslw 7862 }; 7863 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7864 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7865 } 7866 7867 // vsplti + srl self. 7868 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7869 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7870 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7871 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7872 Intrinsic::ppc_altivec_vsrw 7873 }; 7874 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7875 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7876 } 7877 7878 // vsplti + sra self. 7879 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7880 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7881 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7882 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7883 Intrinsic::ppc_altivec_vsraw 7884 }; 7885 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7886 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7887 } 7888 7889 // vsplti + rol self. 7890 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7891 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7892 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7893 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7894 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7895 Intrinsic::ppc_altivec_vrlw 7896 }; 7897 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7898 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7899 } 7900 7901 // t = vsplti c, result = vsldoi t, t, 1 7902 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7903 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7904 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7905 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7906 } 7907 // t = vsplti c, result = vsldoi t, t, 2 7908 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7909 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7910 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7911 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7912 } 7913 // t = vsplti c, result = vsldoi t, t, 3 7914 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7915 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7916 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7917 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7918 } 7919 } 7920 7921 return SDValue(); 7922 } 7923 7924 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7925 /// the specified operations to build the shuffle. 7926 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7927 SDValue RHS, SelectionDAG &DAG, 7928 const SDLoc &dl) { 7929 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7930 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7931 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7932 7933 enum { 7934 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7935 OP_VMRGHW, 7936 OP_VMRGLW, 7937 OP_VSPLTISW0, 7938 OP_VSPLTISW1, 7939 OP_VSPLTISW2, 7940 OP_VSPLTISW3, 7941 OP_VSLDOI4, 7942 OP_VSLDOI8, 7943 OP_VSLDOI12 7944 }; 7945 7946 if (OpNum == OP_COPY) { 7947 if (LHSID == (1*9+2)*9+3) return LHS; 7948 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7949 return RHS; 7950 } 7951 7952 SDValue OpLHS, OpRHS; 7953 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7954 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7955 7956 int ShufIdxs[16]; 7957 switch (OpNum) { 7958 default: llvm_unreachable("Unknown i32 permute!"); 7959 case OP_VMRGHW: 7960 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7961 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7962 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7963 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7964 break; 7965 case OP_VMRGLW: 7966 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7967 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7968 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7969 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7970 break; 7971 case OP_VSPLTISW0: 7972 for (unsigned i = 0; i != 16; ++i) 7973 ShufIdxs[i] = (i&3)+0; 7974 break; 7975 case OP_VSPLTISW1: 7976 for (unsigned i = 0; i != 16; ++i) 7977 ShufIdxs[i] = (i&3)+4; 7978 break; 7979 case OP_VSPLTISW2: 7980 for (unsigned i = 0; i != 16; ++i) 7981 ShufIdxs[i] = (i&3)+8; 7982 break; 7983 case OP_VSPLTISW3: 7984 for (unsigned i = 0; i != 16; ++i) 7985 ShufIdxs[i] = (i&3)+12; 7986 break; 7987 case OP_VSLDOI4: 7988 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7989 case OP_VSLDOI8: 7990 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7991 case OP_VSLDOI12: 7992 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7993 } 7994 EVT VT = OpLHS.getValueType(); 7995 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7996 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7997 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7998 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7999 } 8000 8001 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8002 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8003 /// SDValue. 8004 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8005 SelectionDAG &DAG) const { 8006 const unsigned BytesInVector = 16; 8007 bool IsLE = Subtarget.isLittleEndian(); 8008 SDLoc dl(N); 8009 SDValue V1 = N->getOperand(0); 8010 SDValue V2 = N->getOperand(1); 8011 unsigned ShiftElts = 0, InsertAtByte = 0; 8012 bool Swap = false; 8013 8014 // Shifts required to get the byte we want at element 7. 8015 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8016 0, 15, 14, 13, 12, 11, 10, 9}; 8017 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8018 1, 2, 3, 4, 5, 6, 7, 8}; 8019 8020 ArrayRef<int> Mask = N->getMask(); 8021 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8022 8023 // For each mask element, find out if we're just inserting something 8024 // from V2 into V1 or vice versa. 8025 // Possible permutations inserting an element from V2 into V1: 8026 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8027 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8028 // ... 8029 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8030 // Inserting from V1 into V2 will be similar, except mask range will be 8031 // [16,31]. 8032 8033 bool FoundCandidate = false; 8034 // If both vector operands for the shuffle are the same vector, the mask 8035 // will contain only elements from the first one and the second one will be 8036 // undef. 8037 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8038 // Go through the mask of half-words to find an element that's being moved 8039 // from one vector to the other. 8040 for (unsigned i = 0; i < BytesInVector; ++i) { 8041 unsigned CurrentElement = Mask[i]; 8042 // If 2nd operand is undefined, we should only look for element 7 in the 8043 // Mask. 8044 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8045 continue; 8046 8047 bool OtherElementsInOrder = true; 8048 // Examine the other elements in the Mask to see if they're in original 8049 // order. 8050 for (unsigned j = 0; j < BytesInVector; ++j) { 8051 if (j == i) 8052 continue; 8053 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8054 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8055 // in which we always assume we're always picking from the 1st operand. 8056 int MaskOffset = 8057 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8058 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8059 OtherElementsInOrder = false; 8060 break; 8061 } 8062 } 8063 // If other elements are in original order, we record the number of shifts 8064 // we need to get the element we want into element 7. Also record which byte 8065 // in the vector we should insert into. 8066 if (OtherElementsInOrder) { 8067 // If 2nd operand is undefined, we assume no shifts and no swapping. 8068 if (V2.isUndef()) { 8069 ShiftElts = 0; 8070 Swap = false; 8071 } else { 8072 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8073 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8074 : BigEndianShifts[CurrentElement & 0xF]; 8075 Swap = CurrentElement < BytesInVector; 8076 } 8077 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8078 FoundCandidate = true; 8079 break; 8080 } 8081 } 8082 8083 if (!FoundCandidate) 8084 return SDValue(); 8085 8086 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8087 // optionally with VECSHL if shift is required. 8088 if (Swap) 8089 std::swap(V1, V2); 8090 if (V2.isUndef()) 8091 V2 = V1; 8092 if (ShiftElts) { 8093 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8094 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8095 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8096 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8097 } 8098 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8099 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8100 } 8101 8102 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8103 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8104 /// SDValue. 8105 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8106 SelectionDAG &DAG) const { 8107 const unsigned NumHalfWords = 8; 8108 const unsigned BytesInVector = NumHalfWords * 2; 8109 // Check that the shuffle is on half-words. 8110 if (!isNByteElemShuffleMask(N, 2, 1)) 8111 return SDValue(); 8112 8113 bool IsLE = Subtarget.isLittleEndian(); 8114 SDLoc dl(N); 8115 SDValue V1 = N->getOperand(0); 8116 SDValue V2 = N->getOperand(1); 8117 unsigned ShiftElts = 0, InsertAtByte = 0; 8118 bool Swap = false; 8119 8120 // Shifts required to get the half-word we want at element 3. 8121 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8122 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8123 8124 uint32_t Mask = 0; 8125 uint32_t OriginalOrderLow = 0x1234567; 8126 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8127 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8128 // 32-bit space, only need 4-bit nibbles per element. 8129 for (unsigned i = 0; i < NumHalfWords; ++i) { 8130 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8131 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8132 } 8133 8134 // For each mask element, find out if we're just inserting something 8135 // from V2 into V1 or vice versa. Possible permutations inserting an element 8136 // from V2 into V1: 8137 // X, 1, 2, 3, 4, 5, 6, 7 8138 // 0, X, 2, 3, 4, 5, 6, 7 8139 // 0, 1, X, 3, 4, 5, 6, 7 8140 // 0, 1, 2, X, 4, 5, 6, 7 8141 // 0, 1, 2, 3, X, 5, 6, 7 8142 // 0, 1, 2, 3, 4, X, 6, 7 8143 // 0, 1, 2, 3, 4, 5, X, 7 8144 // 0, 1, 2, 3, 4, 5, 6, X 8145 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8146 8147 bool FoundCandidate = false; 8148 // Go through the mask of half-words to find an element that's being moved 8149 // from one vector to the other. 8150 for (unsigned i = 0; i < NumHalfWords; ++i) { 8151 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8152 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8153 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8154 uint32_t TargetOrder = 0x0; 8155 8156 // If both vector operands for the shuffle are the same vector, the mask 8157 // will contain only elements from the first one and the second one will be 8158 // undef. 8159 if (V2.isUndef()) { 8160 ShiftElts = 0; 8161 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8162 TargetOrder = OriginalOrderLow; 8163 Swap = false; 8164 // Skip if not the correct element or mask of other elements don't equal 8165 // to our expected order. 8166 if (MaskOneElt == VINSERTHSrcElem && 8167 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8168 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8169 FoundCandidate = true; 8170 break; 8171 } 8172 } else { // If both operands are defined. 8173 // Target order is [8,15] if the current mask is between [0,7]. 8174 TargetOrder = 8175 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8176 // Skip if mask of other elements don't equal our expected order. 8177 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8178 // We only need the last 3 bits for the number of shifts. 8179 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8180 : BigEndianShifts[MaskOneElt & 0x7]; 8181 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8182 Swap = MaskOneElt < NumHalfWords; 8183 FoundCandidate = true; 8184 break; 8185 } 8186 } 8187 } 8188 8189 if (!FoundCandidate) 8190 return SDValue(); 8191 8192 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8193 // optionally with VECSHL if shift is required. 8194 if (Swap) 8195 std::swap(V1, V2); 8196 if (V2.isUndef()) 8197 V2 = V1; 8198 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8199 if (ShiftElts) { 8200 // Double ShiftElts because we're left shifting on v16i8 type. 8201 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8202 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8203 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8204 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8205 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8206 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8207 } 8208 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8209 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8210 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8211 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8212 } 8213 8214 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8215 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8216 /// return the code it can be lowered into. Worst case, it can always be 8217 /// lowered into a vperm. 8218 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8219 SelectionDAG &DAG) const { 8220 SDLoc dl(Op); 8221 SDValue V1 = Op.getOperand(0); 8222 SDValue V2 = Op.getOperand(1); 8223 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8224 EVT VT = Op.getValueType(); 8225 bool isLittleEndian = Subtarget.isLittleEndian(); 8226 8227 unsigned ShiftElts, InsertAtByte; 8228 bool Swap = false; 8229 if (Subtarget.hasP9Vector() && 8230 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8231 isLittleEndian)) { 8232 if (Swap) 8233 std::swap(V1, V2); 8234 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8235 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8236 if (ShiftElts) { 8237 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8238 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8239 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8240 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8241 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8242 } 8243 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8244 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8245 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8246 } 8247 8248 if (Subtarget.hasP9Altivec()) { 8249 SDValue NewISDNode; 8250 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8251 return NewISDNode; 8252 8253 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8254 return NewISDNode; 8255 } 8256 8257 if (Subtarget.hasVSX() && 8258 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8259 if (Swap) 8260 std::swap(V1, V2); 8261 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8262 SDValue Conv2 = 8263 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8264 8265 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8266 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8267 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8268 } 8269 8270 if (Subtarget.hasVSX() && 8271 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8272 if (Swap) 8273 std::swap(V1, V2); 8274 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8275 SDValue Conv2 = 8276 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8277 8278 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8279 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8280 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8281 } 8282 8283 if (Subtarget.hasP9Vector()) { 8284 if (PPC::isXXBRHShuffleMask(SVOp)) { 8285 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8286 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8287 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8288 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8289 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8290 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8291 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8292 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8293 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8294 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8295 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8296 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8297 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8298 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8299 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8300 } 8301 } 8302 8303 if (Subtarget.hasVSX()) { 8304 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8305 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8306 8307 // If the source for the shuffle is a scalar_to_vector that came from a 8308 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 8309 if (Subtarget.hasP9Vector() && 8310 ((isLittleEndian && SplatIdx == 3) || 8311 (!isLittleEndian && SplatIdx == 0))) { 8312 SDValue Src = V1.getOperand(0); 8313 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 8314 Src.getOperand(0).getOpcode() == ISD::LOAD && 8315 Src.getOperand(0).hasOneUse()) 8316 return V1; 8317 } 8318 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8319 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8320 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8321 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8322 } 8323 8324 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8325 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8326 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8327 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8328 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8329 } 8330 } 8331 8332 if (Subtarget.hasQPX()) { 8333 if (VT.getVectorNumElements() != 4) 8334 return SDValue(); 8335 8336 if (V2.isUndef()) V2 = V1; 8337 8338 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8339 if (AlignIdx != -1) { 8340 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8341 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8342 } else if (SVOp->isSplat()) { 8343 int SplatIdx = SVOp->getSplatIndex(); 8344 if (SplatIdx >= 4) { 8345 std::swap(V1, V2); 8346 SplatIdx -= 4; 8347 } 8348 8349 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8350 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8351 } 8352 8353 // Lower this into a qvgpci/qvfperm pair. 8354 8355 // Compute the qvgpci literal 8356 unsigned idx = 0; 8357 for (unsigned i = 0; i < 4; ++i) { 8358 int m = SVOp->getMaskElt(i); 8359 unsigned mm = m >= 0 ? (unsigned) m : i; 8360 idx |= mm << (3-i)*3; 8361 } 8362 8363 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8364 DAG.getConstant(idx, dl, MVT::i32)); 8365 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8366 } 8367 8368 // Cases that are handled by instructions that take permute immediates 8369 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8370 // selected by the instruction selector. 8371 if (V2.isUndef()) { 8372 if (PPC::isSplatShuffleMask(SVOp, 1) || 8373 PPC::isSplatShuffleMask(SVOp, 2) || 8374 PPC::isSplatShuffleMask(SVOp, 4) || 8375 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8376 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8377 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8378 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8379 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8380 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8381 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8382 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8383 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8384 (Subtarget.hasP8Altivec() && ( 8385 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8386 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8387 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8388 return Op; 8389 } 8390 } 8391 8392 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8393 // and produce a fixed permutation. If any of these match, do not lower to 8394 // VPERM. 8395 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8396 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8397 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8398 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8399 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8400 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8401 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8402 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8403 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8404 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8405 (Subtarget.hasP8Altivec() && ( 8406 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8407 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8408 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8409 return Op; 8410 8411 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8412 // perfect shuffle table to emit an optimal matching sequence. 8413 ArrayRef<int> PermMask = SVOp->getMask(); 8414 8415 unsigned PFIndexes[4]; 8416 bool isFourElementShuffle = true; 8417 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8418 unsigned EltNo = 8; // Start out undef. 8419 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8420 if (PermMask[i*4+j] < 0) 8421 continue; // Undef, ignore it. 8422 8423 unsigned ByteSource = PermMask[i*4+j]; 8424 if ((ByteSource & 3) != j) { 8425 isFourElementShuffle = false; 8426 break; 8427 } 8428 8429 if (EltNo == 8) { 8430 EltNo = ByteSource/4; 8431 } else if (EltNo != ByteSource/4) { 8432 isFourElementShuffle = false; 8433 break; 8434 } 8435 } 8436 PFIndexes[i] = EltNo; 8437 } 8438 8439 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8440 // perfect shuffle vector to determine if it is cost effective to do this as 8441 // discrete instructions, or whether we should use a vperm. 8442 // For now, we skip this for little endian until such time as we have a 8443 // little-endian perfect shuffle table. 8444 if (isFourElementShuffle && !isLittleEndian) { 8445 // Compute the index in the perfect shuffle table. 8446 unsigned PFTableIndex = 8447 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8448 8449 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8450 unsigned Cost = (PFEntry >> 30); 8451 8452 // Determining when to avoid vperm is tricky. Many things affect the cost 8453 // of vperm, particularly how many times the perm mask needs to be computed. 8454 // For example, if the perm mask can be hoisted out of a loop or is already 8455 // used (perhaps because there are multiple permutes with the same shuffle 8456 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8457 // the loop requires an extra register. 8458 // 8459 // As a compromise, we only emit discrete instructions if the shuffle can be 8460 // generated in 3 or fewer operations. When we have loop information 8461 // available, if this block is within a loop, we should avoid using vperm 8462 // for 3-operation perms and use a constant pool load instead. 8463 if (Cost < 3) 8464 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8465 } 8466 8467 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8468 // vector that will get spilled to the constant pool. 8469 if (V2.isUndef()) V2 = V1; 8470 8471 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8472 // that it is in input element units, not in bytes. Convert now. 8473 8474 // For little endian, the order of the input vectors is reversed, and 8475 // the permutation mask is complemented with respect to 31. This is 8476 // necessary to produce proper semantics with the big-endian-biased vperm 8477 // instruction. 8478 EVT EltVT = V1.getValueType().getVectorElementType(); 8479 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8480 8481 SmallVector<SDValue, 16> ResultMask; 8482 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8483 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8484 8485 for (unsigned j = 0; j != BytesPerElement; ++j) 8486 if (isLittleEndian) 8487 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8488 dl, MVT::i32)); 8489 else 8490 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8491 MVT::i32)); 8492 } 8493 8494 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8495 if (isLittleEndian) 8496 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8497 V2, V1, VPermMask); 8498 else 8499 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8500 V1, V2, VPermMask); 8501 } 8502 8503 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8504 /// vector comparison. If it is, return true and fill in Opc/isDot with 8505 /// information about the intrinsic. 8506 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8507 bool &isDot, const PPCSubtarget &Subtarget) { 8508 unsigned IntrinsicID = 8509 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8510 CompareOpc = -1; 8511 isDot = false; 8512 switch (IntrinsicID) { 8513 default: 8514 return false; 8515 // Comparison predicates. 8516 case Intrinsic::ppc_altivec_vcmpbfp_p: 8517 CompareOpc = 966; 8518 isDot = true; 8519 break; 8520 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8521 CompareOpc = 198; 8522 isDot = true; 8523 break; 8524 case Intrinsic::ppc_altivec_vcmpequb_p: 8525 CompareOpc = 6; 8526 isDot = true; 8527 break; 8528 case Intrinsic::ppc_altivec_vcmpequh_p: 8529 CompareOpc = 70; 8530 isDot = true; 8531 break; 8532 case Intrinsic::ppc_altivec_vcmpequw_p: 8533 CompareOpc = 134; 8534 isDot = true; 8535 break; 8536 case Intrinsic::ppc_altivec_vcmpequd_p: 8537 if (Subtarget.hasP8Altivec()) { 8538 CompareOpc = 199; 8539 isDot = true; 8540 } else 8541 return false; 8542 break; 8543 case Intrinsic::ppc_altivec_vcmpneb_p: 8544 case Intrinsic::ppc_altivec_vcmpneh_p: 8545 case Intrinsic::ppc_altivec_vcmpnew_p: 8546 case Intrinsic::ppc_altivec_vcmpnezb_p: 8547 case Intrinsic::ppc_altivec_vcmpnezh_p: 8548 case Intrinsic::ppc_altivec_vcmpnezw_p: 8549 if (Subtarget.hasP9Altivec()) { 8550 switch (IntrinsicID) { 8551 default: 8552 llvm_unreachable("Unknown comparison intrinsic."); 8553 case Intrinsic::ppc_altivec_vcmpneb_p: 8554 CompareOpc = 7; 8555 break; 8556 case Intrinsic::ppc_altivec_vcmpneh_p: 8557 CompareOpc = 71; 8558 break; 8559 case Intrinsic::ppc_altivec_vcmpnew_p: 8560 CompareOpc = 135; 8561 break; 8562 case Intrinsic::ppc_altivec_vcmpnezb_p: 8563 CompareOpc = 263; 8564 break; 8565 case Intrinsic::ppc_altivec_vcmpnezh_p: 8566 CompareOpc = 327; 8567 break; 8568 case Intrinsic::ppc_altivec_vcmpnezw_p: 8569 CompareOpc = 391; 8570 break; 8571 } 8572 isDot = true; 8573 } else 8574 return false; 8575 break; 8576 case Intrinsic::ppc_altivec_vcmpgefp_p: 8577 CompareOpc = 454; 8578 isDot = true; 8579 break; 8580 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8581 CompareOpc = 710; 8582 isDot = true; 8583 break; 8584 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8585 CompareOpc = 774; 8586 isDot = true; 8587 break; 8588 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8589 CompareOpc = 838; 8590 isDot = true; 8591 break; 8592 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8593 CompareOpc = 902; 8594 isDot = true; 8595 break; 8596 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8597 if (Subtarget.hasP8Altivec()) { 8598 CompareOpc = 967; 8599 isDot = true; 8600 } else 8601 return false; 8602 break; 8603 case Intrinsic::ppc_altivec_vcmpgtub_p: 8604 CompareOpc = 518; 8605 isDot = true; 8606 break; 8607 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8608 CompareOpc = 582; 8609 isDot = true; 8610 break; 8611 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8612 CompareOpc = 646; 8613 isDot = true; 8614 break; 8615 case Intrinsic::ppc_altivec_vcmpgtud_p: 8616 if (Subtarget.hasP8Altivec()) { 8617 CompareOpc = 711; 8618 isDot = true; 8619 } else 8620 return false; 8621 break; 8622 8623 // VSX predicate comparisons use the same infrastructure 8624 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8625 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8626 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8627 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8628 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8629 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8630 if (Subtarget.hasVSX()) { 8631 switch (IntrinsicID) { 8632 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8633 CompareOpc = 99; 8634 break; 8635 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8636 CompareOpc = 115; 8637 break; 8638 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8639 CompareOpc = 107; 8640 break; 8641 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8642 CompareOpc = 67; 8643 break; 8644 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8645 CompareOpc = 83; 8646 break; 8647 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8648 CompareOpc = 75; 8649 break; 8650 } 8651 isDot = true; 8652 } else 8653 return false; 8654 break; 8655 8656 // Normal Comparisons. 8657 case Intrinsic::ppc_altivec_vcmpbfp: 8658 CompareOpc = 966; 8659 break; 8660 case Intrinsic::ppc_altivec_vcmpeqfp: 8661 CompareOpc = 198; 8662 break; 8663 case Intrinsic::ppc_altivec_vcmpequb: 8664 CompareOpc = 6; 8665 break; 8666 case Intrinsic::ppc_altivec_vcmpequh: 8667 CompareOpc = 70; 8668 break; 8669 case Intrinsic::ppc_altivec_vcmpequw: 8670 CompareOpc = 134; 8671 break; 8672 case Intrinsic::ppc_altivec_vcmpequd: 8673 if (Subtarget.hasP8Altivec()) 8674 CompareOpc = 199; 8675 else 8676 return false; 8677 break; 8678 case Intrinsic::ppc_altivec_vcmpneb: 8679 case Intrinsic::ppc_altivec_vcmpneh: 8680 case Intrinsic::ppc_altivec_vcmpnew: 8681 case Intrinsic::ppc_altivec_vcmpnezb: 8682 case Intrinsic::ppc_altivec_vcmpnezh: 8683 case Intrinsic::ppc_altivec_vcmpnezw: 8684 if (Subtarget.hasP9Altivec()) 8685 switch (IntrinsicID) { 8686 default: 8687 llvm_unreachable("Unknown comparison intrinsic."); 8688 case Intrinsic::ppc_altivec_vcmpneb: 8689 CompareOpc = 7; 8690 break; 8691 case Intrinsic::ppc_altivec_vcmpneh: 8692 CompareOpc = 71; 8693 break; 8694 case Intrinsic::ppc_altivec_vcmpnew: 8695 CompareOpc = 135; 8696 break; 8697 case Intrinsic::ppc_altivec_vcmpnezb: 8698 CompareOpc = 263; 8699 break; 8700 case Intrinsic::ppc_altivec_vcmpnezh: 8701 CompareOpc = 327; 8702 break; 8703 case Intrinsic::ppc_altivec_vcmpnezw: 8704 CompareOpc = 391; 8705 break; 8706 } 8707 else 8708 return false; 8709 break; 8710 case Intrinsic::ppc_altivec_vcmpgefp: 8711 CompareOpc = 454; 8712 break; 8713 case Intrinsic::ppc_altivec_vcmpgtfp: 8714 CompareOpc = 710; 8715 break; 8716 case Intrinsic::ppc_altivec_vcmpgtsb: 8717 CompareOpc = 774; 8718 break; 8719 case Intrinsic::ppc_altivec_vcmpgtsh: 8720 CompareOpc = 838; 8721 break; 8722 case Intrinsic::ppc_altivec_vcmpgtsw: 8723 CompareOpc = 902; 8724 break; 8725 case Intrinsic::ppc_altivec_vcmpgtsd: 8726 if (Subtarget.hasP8Altivec()) 8727 CompareOpc = 967; 8728 else 8729 return false; 8730 break; 8731 case Intrinsic::ppc_altivec_vcmpgtub: 8732 CompareOpc = 518; 8733 break; 8734 case Intrinsic::ppc_altivec_vcmpgtuh: 8735 CompareOpc = 582; 8736 break; 8737 case Intrinsic::ppc_altivec_vcmpgtuw: 8738 CompareOpc = 646; 8739 break; 8740 case Intrinsic::ppc_altivec_vcmpgtud: 8741 if (Subtarget.hasP8Altivec()) 8742 CompareOpc = 711; 8743 else 8744 return false; 8745 break; 8746 } 8747 return true; 8748 } 8749 8750 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8751 /// lower, do it, otherwise return null. 8752 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8753 SelectionDAG &DAG) const { 8754 unsigned IntrinsicID = 8755 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8756 8757 SDLoc dl(Op); 8758 8759 if (IntrinsicID == Intrinsic::thread_pointer) { 8760 // Reads the thread pointer register, used for __builtin_thread_pointer. 8761 if (Subtarget.isPPC64()) 8762 return DAG.getRegister(PPC::X13, MVT::i64); 8763 return DAG.getRegister(PPC::R2, MVT::i32); 8764 } 8765 8766 // We are looking for absolute values here. 8767 // The idea is to try to fit one of two patterns: 8768 // max (a, (0-a)) OR max ((0-a), a) 8769 if (Subtarget.hasP9Vector() && 8770 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8771 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8772 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8773 SDValue V1 = Op.getOperand(1); 8774 SDValue V2 = Op.getOperand(2); 8775 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8776 (V1.getSimpleValueType() == MVT::v4i32 || 8777 V1.getSimpleValueType() == MVT::v8i16 || 8778 V1.getSimpleValueType() == MVT::v16i8)) { 8779 if ( V1.getOpcode() == ISD::SUB && 8780 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8781 V1.getOperand(1) == V2 ) { 8782 // Generate the abs instruction with the operands 8783 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8784 } 8785 8786 if ( V2.getOpcode() == ISD::SUB && 8787 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8788 V2.getOperand(1) == V1 ) { 8789 // Generate the abs instruction with the operands 8790 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8791 } 8792 } 8793 } 8794 8795 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8796 // opcode number of the comparison. 8797 int CompareOpc; 8798 bool isDot; 8799 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8800 return SDValue(); // Don't custom lower most intrinsics. 8801 8802 // If this is a non-dot comparison, make the VCMP node and we are done. 8803 if (!isDot) { 8804 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8805 Op.getOperand(1), Op.getOperand(2), 8806 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8807 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8808 } 8809 8810 // Create the PPCISD altivec 'dot' comparison node. 8811 SDValue Ops[] = { 8812 Op.getOperand(2), // LHS 8813 Op.getOperand(3), // RHS 8814 DAG.getConstant(CompareOpc, dl, MVT::i32) 8815 }; 8816 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8817 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8818 8819 // Now that we have the comparison, emit a copy from the CR to a GPR. 8820 // This is flagged to the above dot comparison. 8821 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8822 DAG.getRegister(PPC::CR6, MVT::i32), 8823 CompNode.getValue(1)); 8824 8825 // Unpack the result based on how the target uses it. 8826 unsigned BitNo; // Bit # of CR6. 8827 bool InvertBit; // Invert result? 8828 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8829 default: // Can't happen, don't crash on invalid number though. 8830 case 0: // Return the value of the EQ bit of CR6. 8831 BitNo = 0; InvertBit = false; 8832 break; 8833 case 1: // Return the inverted value of the EQ bit of CR6. 8834 BitNo = 0; InvertBit = true; 8835 break; 8836 case 2: // Return the value of the LT bit of CR6. 8837 BitNo = 2; InvertBit = false; 8838 break; 8839 case 3: // Return the inverted value of the LT bit of CR6. 8840 BitNo = 2; InvertBit = true; 8841 break; 8842 } 8843 8844 // Shift the bit into the low position. 8845 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8846 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8847 // Isolate the bit. 8848 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8849 DAG.getConstant(1, dl, MVT::i32)); 8850 8851 // If we are supposed to, toggle the bit. 8852 if (InvertBit) 8853 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8854 DAG.getConstant(1, dl, MVT::i32)); 8855 return Flags; 8856 } 8857 8858 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8859 SelectionDAG &DAG) const { 8860 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8861 // the beginning of the argument list. 8862 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8863 SDLoc DL(Op); 8864 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8865 case Intrinsic::ppc_cfence: { 8866 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8867 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8868 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8869 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8870 Op.getOperand(ArgStart + 1)), 8871 Op.getOperand(0)), 8872 0); 8873 } 8874 default: 8875 break; 8876 } 8877 return SDValue(); 8878 } 8879 8880 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8881 // Check for a DIV with the same operands as this REM. 8882 for (auto UI : Op.getOperand(1)->uses()) { 8883 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8884 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8885 if (UI->getOperand(0) == Op.getOperand(0) && 8886 UI->getOperand(1) == Op.getOperand(1)) 8887 return SDValue(); 8888 } 8889 return Op; 8890 } 8891 8892 // Lower scalar BSWAP64 to xxbrd. 8893 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 8894 SDLoc dl(Op); 8895 // MTVSRDD 8896 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 8897 Op.getOperand(0)); 8898 // XXBRD 8899 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 8900 // MFVSRD 8901 int VectorIndex = 0; 8902 if (Subtarget.isLittleEndian()) 8903 VectorIndex = 1; 8904 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 8905 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 8906 return Op; 8907 } 8908 8909 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 8910 // compared to a value that is atomically loaded (atomic loads zero-extend). 8911 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 8912 SelectionDAG &DAG) const { 8913 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 8914 "Expecting an atomic compare-and-swap here."); 8915 SDLoc dl(Op); 8916 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 8917 EVT MemVT = AtomicNode->getMemoryVT(); 8918 if (MemVT.getSizeInBits() >= 32) 8919 return Op; 8920 8921 SDValue CmpOp = Op.getOperand(2); 8922 // If this is already correctly zero-extended, leave it alone. 8923 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 8924 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 8925 return Op; 8926 8927 // Clear the high bits of the compare operand. 8928 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 8929 SDValue NewCmpOp = 8930 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 8931 DAG.getConstant(MaskVal, dl, MVT::i32)); 8932 8933 // Replace the existing compare operand with the properly zero-extended one. 8934 SmallVector<SDValue, 4> Ops; 8935 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 8936 Ops.push_back(AtomicNode->getOperand(i)); 8937 Ops[2] = NewCmpOp; 8938 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 8939 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 8940 auto NodeTy = 8941 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 8942 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 8943 } 8944 8945 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8946 SelectionDAG &DAG) const { 8947 SDLoc dl(Op); 8948 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8949 // instructions), but for smaller types, we need to first extend up to v2i32 8950 // before doing going farther. 8951 if (Op.getValueType() == MVT::v2i64) { 8952 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8953 if (ExtVT != MVT::v2i32) { 8954 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8955 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8956 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8957 ExtVT.getVectorElementType(), 4))); 8958 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8959 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8960 DAG.getValueType(MVT::v2i32)); 8961 } 8962 8963 return Op; 8964 } 8965 8966 return SDValue(); 8967 } 8968 8969 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8970 SelectionDAG &DAG) const { 8971 SDLoc dl(Op); 8972 // Create a stack slot that is 16-byte aligned. 8973 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8974 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8975 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8976 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8977 8978 // Store the input value into Value#0 of the stack slot. 8979 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8980 MachinePointerInfo()); 8981 // Load it out. 8982 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8983 } 8984 8985 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8986 SelectionDAG &DAG) const { 8987 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8988 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8989 8990 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8991 // We have legal lowering for constant indices but not for variable ones. 8992 if (!C) 8993 return SDValue(); 8994 8995 EVT VT = Op.getValueType(); 8996 SDLoc dl(Op); 8997 SDValue V1 = Op.getOperand(0); 8998 SDValue V2 = Op.getOperand(1); 8999 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9000 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9001 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9002 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9003 unsigned InsertAtElement = C->getZExtValue(); 9004 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9005 if (Subtarget.isLittleEndian()) { 9006 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9007 } 9008 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9009 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9010 } 9011 return Op; 9012 } 9013 9014 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9015 SelectionDAG &DAG) const { 9016 SDLoc dl(Op); 9017 SDNode *N = Op.getNode(); 9018 9019 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9020 "Unknown extract_vector_elt type"); 9021 9022 SDValue Value = N->getOperand(0); 9023 9024 // The first part of this is like the store lowering except that we don't 9025 // need to track the chain. 9026 9027 // The values are now known to be -1 (false) or 1 (true). To convert this 9028 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9029 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9030 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9031 9032 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9033 // understand how to form the extending load. 9034 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9035 9036 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9037 9038 // Now convert to an integer and store. 9039 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9040 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9041 Value); 9042 9043 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9044 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9045 MachinePointerInfo PtrInfo = 9046 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9047 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9048 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9049 9050 SDValue StoreChain = DAG.getEntryNode(); 9051 SDValue Ops[] = {StoreChain, 9052 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9053 Value, FIdx}; 9054 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9055 9056 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9057 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9058 9059 // Extract the value requested. 9060 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9061 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9062 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9063 9064 SDValue IntVal = 9065 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9066 9067 if (!Subtarget.useCRBits()) 9068 return IntVal; 9069 9070 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9071 } 9072 9073 /// Lowering for QPX v4i1 loads 9074 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9075 SelectionDAG &DAG) const { 9076 SDLoc dl(Op); 9077 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9078 SDValue LoadChain = LN->getChain(); 9079 SDValue BasePtr = LN->getBasePtr(); 9080 9081 if (Op.getValueType() == MVT::v4f64 || 9082 Op.getValueType() == MVT::v4f32) { 9083 EVT MemVT = LN->getMemoryVT(); 9084 unsigned Alignment = LN->getAlignment(); 9085 9086 // If this load is properly aligned, then it is legal. 9087 if (Alignment >= MemVT.getStoreSize()) 9088 return Op; 9089 9090 EVT ScalarVT = Op.getValueType().getScalarType(), 9091 ScalarMemVT = MemVT.getScalarType(); 9092 unsigned Stride = ScalarMemVT.getStoreSize(); 9093 9094 SDValue Vals[4], LoadChains[4]; 9095 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9096 SDValue Load; 9097 if (ScalarVT != ScalarMemVT) 9098 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9099 BasePtr, 9100 LN->getPointerInfo().getWithOffset(Idx * Stride), 9101 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9102 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9103 else 9104 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9105 LN->getPointerInfo().getWithOffset(Idx * Stride), 9106 MinAlign(Alignment, Idx * Stride), 9107 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9108 9109 if (Idx == 0 && LN->isIndexed()) { 9110 assert(LN->getAddressingMode() == ISD::PRE_INC && 9111 "Unknown addressing mode on vector load"); 9112 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9113 LN->getAddressingMode()); 9114 } 9115 9116 Vals[Idx] = Load; 9117 LoadChains[Idx] = Load.getValue(1); 9118 9119 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9120 DAG.getConstant(Stride, dl, 9121 BasePtr.getValueType())); 9122 } 9123 9124 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9125 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9126 9127 if (LN->isIndexed()) { 9128 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9129 return DAG.getMergeValues(RetOps, dl); 9130 } 9131 9132 SDValue RetOps[] = { Value, TF }; 9133 return DAG.getMergeValues(RetOps, dl); 9134 } 9135 9136 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9137 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9138 9139 // To lower v4i1 from a byte array, we load the byte elements of the 9140 // vector and then reuse the BUILD_VECTOR logic. 9141 9142 SDValue VectElmts[4], VectElmtChains[4]; 9143 for (unsigned i = 0; i < 4; ++i) { 9144 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9145 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9146 9147 VectElmts[i] = DAG.getExtLoad( 9148 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9149 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9150 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9151 VectElmtChains[i] = VectElmts[i].getValue(1); 9152 } 9153 9154 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9155 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9156 9157 SDValue RVals[] = { Value, LoadChain }; 9158 return DAG.getMergeValues(RVals, dl); 9159 } 9160 9161 /// Lowering for QPX v4i1 stores 9162 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9163 SelectionDAG &DAG) const { 9164 SDLoc dl(Op); 9165 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9166 SDValue StoreChain = SN->getChain(); 9167 SDValue BasePtr = SN->getBasePtr(); 9168 SDValue Value = SN->getValue(); 9169 9170 if (Value.getValueType() == MVT::v4f64 || 9171 Value.getValueType() == MVT::v4f32) { 9172 EVT MemVT = SN->getMemoryVT(); 9173 unsigned Alignment = SN->getAlignment(); 9174 9175 // If this store is properly aligned, then it is legal. 9176 if (Alignment >= MemVT.getStoreSize()) 9177 return Op; 9178 9179 EVT ScalarVT = Value.getValueType().getScalarType(), 9180 ScalarMemVT = MemVT.getScalarType(); 9181 unsigned Stride = ScalarMemVT.getStoreSize(); 9182 9183 SDValue Stores[4]; 9184 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9185 SDValue Ex = DAG.getNode( 9186 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9187 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9188 SDValue Store; 9189 if (ScalarVT != ScalarMemVT) 9190 Store = 9191 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9192 SN->getPointerInfo().getWithOffset(Idx * Stride), 9193 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9194 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9195 else 9196 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9197 SN->getPointerInfo().getWithOffset(Idx * Stride), 9198 MinAlign(Alignment, Idx * Stride), 9199 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9200 9201 if (Idx == 0 && SN->isIndexed()) { 9202 assert(SN->getAddressingMode() == ISD::PRE_INC && 9203 "Unknown addressing mode on vector store"); 9204 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9205 SN->getAddressingMode()); 9206 } 9207 9208 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9209 DAG.getConstant(Stride, dl, 9210 BasePtr.getValueType())); 9211 Stores[Idx] = Store; 9212 } 9213 9214 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9215 9216 if (SN->isIndexed()) { 9217 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9218 return DAG.getMergeValues(RetOps, dl); 9219 } 9220 9221 return TF; 9222 } 9223 9224 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9225 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9226 9227 // The values are now known to be -1 (false) or 1 (true). To convert this 9228 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9229 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9230 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9231 9232 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9233 // understand how to form the extending load. 9234 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9235 9236 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9237 9238 // Now convert to an integer and store. 9239 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9240 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9241 Value); 9242 9243 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9244 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9245 MachinePointerInfo PtrInfo = 9246 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9247 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9248 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9249 9250 SDValue Ops[] = {StoreChain, 9251 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9252 Value, FIdx}; 9253 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9254 9255 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9256 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9257 9258 // Move data into the byte array. 9259 SDValue Loads[4], LoadChains[4]; 9260 for (unsigned i = 0; i < 4; ++i) { 9261 unsigned Offset = 4*i; 9262 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9263 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9264 9265 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9266 PtrInfo.getWithOffset(Offset)); 9267 LoadChains[i] = Loads[i].getValue(1); 9268 } 9269 9270 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9271 9272 SDValue Stores[4]; 9273 for (unsigned i = 0; i < 4; ++i) { 9274 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9275 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9276 9277 Stores[i] = DAG.getTruncStore( 9278 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9279 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9280 SN->getAAInfo()); 9281 } 9282 9283 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9284 9285 return StoreChain; 9286 } 9287 9288 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9289 SDLoc dl(Op); 9290 if (Op.getValueType() == MVT::v4i32) { 9291 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9292 9293 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9294 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9295 9296 SDValue RHSSwap = // = vrlw RHS, 16 9297 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9298 9299 // Shrinkify inputs to v8i16. 9300 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9301 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9302 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9303 9304 // Low parts multiplied together, generating 32-bit results (we ignore the 9305 // top parts). 9306 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9307 LHS, RHS, DAG, dl, MVT::v4i32); 9308 9309 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9310 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9311 // Shift the high parts up 16 bits. 9312 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9313 Neg16, DAG, dl); 9314 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9315 } else if (Op.getValueType() == MVT::v8i16) { 9316 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9317 9318 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9319 9320 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9321 LHS, RHS, Zero, DAG, dl); 9322 } else if (Op.getValueType() == MVT::v16i8) { 9323 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9324 bool isLittleEndian = Subtarget.isLittleEndian(); 9325 9326 // Multiply the even 8-bit parts, producing 16-bit sums. 9327 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9328 LHS, RHS, DAG, dl, MVT::v8i16); 9329 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9330 9331 // Multiply the odd 8-bit parts, producing 16-bit sums. 9332 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9333 LHS, RHS, DAG, dl, MVT::v8i16); 9334 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9335 9336 // Merge the results together. Because vmuleub and vmuloub are 9337 // instructions with a big-endian bias, we must reverse the 9338 // element numbering and reverse the meaning of "odd" and "even" 9339 // when generating little endian code. 9340 int Ops[16]; 9341 for (unsigned i = 0; i != 8; ++i) { 9342 if (isLittleEndian) { 9343 Ops[i*2 ] = 2*i; 9344 Ops[i*2+1] = 2*i+16; 9345 } else { 9346 Ops[i*2 ] = 2*i+1; 9347 Ops[i*2+1] = 2*i+1+16; 9348 } 9349 } 9350 if (isLittleEndian) 9351 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9352 else 9353 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9354 } else { 9355 llvm_unreachable("Unknown mul to lower!"); 9356 } 9357 } 9358 9359 /// LowerOperation - Provide custom lowering hooks for some operations. 9360 /// 9361 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9362 switch (Op.getOpcode()) { 9363 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9364 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9365 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9366 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9367 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9368 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9369 case ISD::SETCC: return LowerSETCC(Op, DAG); 9370 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9371 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9372 case ISD::VASTART: 9373 return LowerVASTART(Op, DAG); 9374 9375 case ISD::VAARG: 9376 return LowerVAARG(Op, DAG); 9377 9378 case ISD::VACOPY: 9379 return LowerVACOPY(Op, DAG); 9380 9381 case ISD::STACKRESTORE: 9382 return LowerSTACKRESTORE(Op, DAG); 9383 9384 case ISD::DYNAMIC_STACKALLOC: 9385 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9386 9387 case ISD::GET_DYNAMIC_AREA_OFFSET: 9388 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9389 9390 case ISD::EH_DWARF_CFA: 9391 return LowerEH_DWARF_CFA(Op, DAG); 9392 9393 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9394 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9395 9396 case ISD::LOAD: return LowerLOAD(Op, DAG); 9397 case ISD::STORE: return LowerSTORE(Op, DAG); 9398 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9399 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9400 case ISD::FP_TO_UINT: 9401 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 9402 SDLoc(Op)); 9403 case ISD::UINT_TO_FP: 9404 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9405 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9406 9407 // Lower 64-bit shifts. 9408 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9409 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9410 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9411 9412 // Vector-related lowering. 9413 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9414 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9415 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9416 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9417 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9418 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9419 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9420 case ISD::MUL: return LowerMUL(Op, DAG); 9421 9422 // For counter-based loop handling. 9423 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9424 9425 // Frame & Return address. 9426 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9427 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9428 9429 case ISD::INTRINSIC_VOID: 9430 return LowerINTRINSIC_VOID(Op, DAG); 9431 case ISD::SREM: 9432 case ISD::UREM: 9433 return LowerREM(Op, DAG); 9434 case ISD::BSWAP: 9435 return LowerBSWAP(Op, DAG); 9436 case ISD::ATOMIC_CMP_SWAP: 9437 return LowerATOMIC_CMP_SWAP(Op, DAG); 9438 } 9439 } 9440 9441 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9442 SmallVectorImpl<SDValue>&Results, 9443 SelectionDAG &DAG) const { 9444 SDLoc dl(N); 9445 switch (N->getOpcode()) { 9446 default: 9447 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9448 case ISD::READCYCLECOUNTER: { 9449 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9450 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9451 9452 Results.push_back(RTB); 9453 Results.push_back(RTB.getValue(1)); 9454 Results.push_back(RTB.getValue(2)); 9455 break; 9456 } 9457 case ISD::INTRINSIC_W_CHAIN: { 9458 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9459 Intrinsic::ppc_is_decremented_ctr_nonzero) 9460 break; 9461 9462 assert(N->getValueType(0) == MVT::i1 && 9463 "Unexpected result type for CTR decrement intrinsic"); 9464 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9465 N->getValueType(0)); 9466 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9467 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9468 N->getOperand(1)); 9469 9470 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9471 Results.push_back(NewInt.getValue(1)); 9472 break; 9473 } 9474 case ISD::VAARG: { 9475 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9476 return; 9477 9478 EVT VT = N->getValueType(0); 9479 9480 if (VT == MVT::i64) { 9481 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9482 9483 Results.push_back(NewNode); 9484 Results.push_back(NewNode.getValue(1)); 9485 } 9486 return; 9487 } 9488 case ISD::FP_TO_SINT: 9489 case ISD::FP_TO_UINT: 9490 // LowerFP_TO_INT() can only handle f32 and f64. 9491 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9492 return; 9493 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9494 return; 9495 } 9496 } 9497 9498 //===----------------------------------------------------------------------===// 9499 // Other Lowering Code 9500 //===----------------------------------------------------------------------===// 9501 9502 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9503 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9504 Function *Func = Intrinsic::getDeclaration(M, Id); 9505 return Builder.CreateCall(Func, {}); 9506 } 9507 9508 // The mappings for emitLeading/TrailingFence is taken from 9509 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9510 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9511 Instruction *Inst, 9512 AtomicOrdering Ord) const { 9513 if (Ord == AtomicOrdering::SequentiallyConsistent) 9514 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9515 if (isReleaseOrStronger(Ord)) 9516 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9517 return nullptr; 9518 } 9519 9520 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9521 Instruction *Inst, 9522 AtomicOrdering Ord) const { 9523 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9524 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9525 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9526 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9527 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9528 return Builder.CreateCall( 9529 Intrinsic::getDeclaration( 9530 Builder.GetInsertBlock()->getParent()->getParent(), 9531 Intrinsic::ppc_cfence, {Inst->getType()}), 9532 {Inst}); 9533 // FIXME: Can use isync for rmw operation. 9534 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9535 } 9536 return nullptr; 9537 } 9538 9539 MachineBasicBlock * 9540 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9541 unsigned AtomicSize, 9542 unsigned BinOpcode, 9543 unsigned CmpOpcode, 9544 unsigned CmpPred) const { 9545 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9546 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9547 9548 auto LoadMnemonic = PPC::LDARX; 9549 auto StoreMnemonic = PPC::STDCX; 9550 switch (AtomicSize) { 9551 default: 9552 llvm_unreachable("Unexpected size of atomic entity"); 9553 case 1: 9554 LoadMnemonic = PPC::LBARX; 9555 StoreMnemonic = PPC::STBCX; 9556 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9557 break; 9558 case 2: 9559 LoadMnemonic = PPC::LHARX; 9560 StoreMnemonic = PPC::STHCX; 9561 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9562 break; 9563 case 4: 9564 LoadMnemonic = PPC::LWARX; 9565 StoreMnemonic = PPC::STWCX; 9566 break; 9567 case 8: 9568 LoadMnemonic = PPC::LDARX; 9569 StoreMnemonic = PPC::STDCX; 9570 break; 9571 } 9572 9573 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9574 MachineFunction *F = BB->getParent(); 9575 MachineFunction::iterator It = ++BB->getIterator(); 9576 9577 unsigned dest = MI.getOperand(0).getReg(); 9578 unsigned ptrA = MI.getOperand(1).getReg(); 9579 unsigned ptrB = MI.getOperand(2).getReg(); 9580 unsigned incr = MI.getOperand(3).getReg(); 9581 DebugLoc dl = MI.getDebugLoc(); 9582 9583 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9584 MachineBasicBlock *loop2MBB = 9585 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9586 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9587 F->insert(It, loopMBB); 9588 if (CmpOpcode) 9589 F->insert(It, loop2MBB); 9590 F->insert(It, exitMBB); 9591 exitMBB->splice(exitMBB->begin(), BB, 9592 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9593 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9594 9595 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9596 unsigned TmpReg = (!BinOpcode) ? incr : 9597 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9598 : &PPC::GPRCRegClass); 9599 9600 // thisMBB: 9601 // ... 9602 // fallthrough --> loopMBB 9603 BB->addSuccessor(loopMBB); 9604 9605 // loopMBB: 9606 // l[wd]arx dest, ptr 9607 // add r0, dest, incr 9608 // st[wd]cx. r0, ptr 9609 // bne- loopMBB 9610 // fallthrough --> exitMBB 9611 9612 // For max/min... 9613 // loopMBB: 9614 // l[wd]arx dest, ptr 9615 // cmpl?[wd] incr, dest 9616 // bgt exitMBB 9617 // loop2MBB: 9618 // st[wd]cx. dest, ptr 9619 // bne- loopMBB 9620 // fallthrough --> exitMBB 9621 9622 BB = loopMBB; 9623 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9624 .addReg(ptrA).addReg(ptrB); 9625 if (BinOpcode) 9626 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9627 if (CmpOpcode) { 9628 // Signed comparisons of byte or halfword values must be sign-extended. 9629 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9630 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9631 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9632 ExtReg).addReg(dest); 9633 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9634 .addReg(incr).addReg(ExtReg); 9635 } else 9636 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9637 .addReg(incr).addReg(dest); 9638 9639 BuildMI(BB, dl, TII->get(PPC::BCC)) 9640 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9641 BB->addSuccessor(loop2MBB); 9642 BB->addSuccessor(exitMBB); 9643 BB = loop2MBB; 9644 } 9645 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9646 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9647 BuildMI(BB, dl, TII->get(PPC::BCC)) 9648 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9649 BB->addSuccessor(loopMBB); 9650 BB->addSuccessor(exitMBB); 9651 9652 // exitMBB: 9653 // ... 9654 BB = exitMBB; 9655 return BB; 9656 } 9657 9658 MachineBasicBlock * 9659 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9660 MachineBasicBlock *BB, 9661 bool is8bit, // operation 9662 unsigned BinOpcode, 9663 unsigned CmpOpcode, 9664 unsigned CmpPred) const { 9665 // If we support part-word atomic mnemonics, just use them 9666 if (Subtarget.hasPartwordAtomics()) 9667 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9668 CmpOpcode, CmpPred); 9669 9670 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9671 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9672 // In 64 bit mode we have to use 64 bits for addresses, even though the 9673 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9674 // registers without caring whether they're 32 or 64, but here we're 9675 // doing actual arithmetic on the addresses. 9676 bool is64bit = Subtarget.isPPC64(); 9677 bool isLittleEndian = Subtarget.isLittleEndian(); 9678 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9679 9680 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9681 MachineFunction *F = BB->getParent(); 9682 MachineFunction::iterator It = ++BB->getIterator(); 9683 9684 unsigned dest = MI.getOperand(0).getReg(); 9685 unsigned ptrA = MI.getOperand(1).getReg(); 9686 unsigned ptrB = MI.getOperand(2).getReg(); 9687 unsigned incr = MI.getOperand(3).getReg(); 9688 DebugLoc dl = MI.getDebugLoc(); 9689 9690 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9691 MachineBasicBlock *loop2MBB = 9692 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9693 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9694 F->insert(It, loopMBB); 9695 if (CmpOpcode) 9696 F->insert(It, loop2MBB); 9697 F->insert(It, exitMBB); 9698 exitMBB->splice(exitMBB->begin(), BB, 9699 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9700 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9701 9702 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9703 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9704 : &PPC::GPRCRegClass; 9705 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9706 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9707 unsigned ShiftReg = 9708 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9709 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9710 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9711 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9712 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9713 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9714 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9715 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9716 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9717 unsigned Ptr1Reg; 9718 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9719 9720 // thisMBB: 9721 // ... 9722 // fallthrough --> loopMBB 9723 BB->addSuccessor(loopMBB); 9724 9725 // The 4-byte load must be aligned, while a char or short may be 9726 // anywhere in the word. Hence all this nasty bookkeeping code. 9727 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9728 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9729 // xori shift, shift1, 24 [16] 9730 // rlwinm ptr, ptr1, 0, 0, 29 9731 // slw incr2, incr, shift 9732 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9733 // slw mask, mask2, shift 9734 // loopMBB: 9735 // lwarx tmpDest, ptr 9736 // add tmp, tmpDest, incr2 9737 // andc tmp2, tmpDest, mask 9738 // and tmp3, tmp, mask 9739 // or tmp4, tmp3, tmp2 9740 // stwcx. tmp4, ptr 9741 // bne- loopMBB 9742 // fallthrough --> exitMBB 9743 // srw dest, tmpDest, shift 9744 if (ptrA != ZeroReg) { 9745 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9746 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9747 .addReg(ptrA).addReg(ptrB); 9748 } else { 9749 Ptr1Reg = ptrB; 9750 } 9751 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9752 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9753 if (!isLittleEndian) 9754 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9755 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9756 if (is64bit) 9757 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9758 .addReg(Ptr1Reg).addImm(0).addImm(61); 9759 else 9760 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9761 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9762 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9763 .addReg(incr).addReg(ShiftReg); 9764 if (is8bit) 9765 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9766 else { 9767 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9768 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9769 } 9770 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9771 .addReg(Mask2Reg).addReg(ShiftReg); 9772 9773 BB = loopMBB; 9774 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9775 .addReg(ZeroReg).addReg(PtrReg); 9776 if (BinOpcode) 9777 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9778 .addReg(Incr2Reg).addReg(TmpDestReg); 9779 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9780 .addReg(TmpDestReg).addReg(MaskReg); 9781 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9782 .addReg(TmpReg).addReg(MaskReg); 9783 if (CmpOpcode) { 9784 // For unsigned comparisons, we can directly compare the shifted values. 9785 // For signed comparisons we shift and sign extend. 9786 unsigned SReg = RegInfo.createVirtualRegister(RC); 9787 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9788 .addReg(TmpDestReg).addReg(MaskReg); 9789 unsigned ValueReg = SReg; 9790 unsigned CmpReg = Incr2Reg; 9791 if (CmpOpcode == PPC::CMPW) { 9792 ValueReg = RegInfo.createVirtualRegister(RC); 9793 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9794 .addReg(SReg).addReg(ShiftReg); 9795 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9796 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9797 .addReg(ValueReg); 9798 ValueReg = ValueSReg; 9799 CmpReg = incr; 9800 } 9801 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9802 .addReg(CmpReg).addReg(ValueReg); 9803 BuildMI(BB, dl, TII->get(PPC::BCC)) 9804 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9805 BB->addSuccessor(loop2MBB); 9806 BB->addSuccessor(exitMBB); 9807 BB = loop2MBB; 9808 } 9809 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9810 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9811 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9812 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9813 BuildMI(BB, dl, TII->get(PPC::BCC)) 9814 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9815 BB->addSuccessor(loopMBB); 9816 BB->addSuccessor(exitMBB); 9817 9818 // exitMBB: 9819 // ... 9820 BB = exitMBB; 9821 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9822 .addReg(ShiftReg); 9823 return BB; 9824 } 9825 9826 llvm::MachineBasicBlock * 9827 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9828 MachineBasicBlock *MBB) const { 9829 DebugLoc DL = MI.getDebugLoc(); 9830 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9831 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9832 9833 MachineFunction *MF = MBB->getParent(); 9834 MachineRegisterInfo &MRI = MF->getRegInfo(); 9835 9836 const BasicBlock *BB = MBB->getBasicBlock(); 9837 MachineFunction::iterator I = ++MBB->getIterator(); 9838 9839 // Memory Reference 9840 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9841 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9842 9843 unsigned DstReg = MI.getOperand(0).getReg(); 9844 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9845 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9846 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9847 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9848 9849 MVT PVT = getPointerTy(MF->getDataLayout()); 9850 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9851 "Invalid Pointer Size!"); 9852 // For v = setjmp(buf), we generate 9853 // 9854 // thisMBB: 9855 // SjLjSetup mainMBB 9856 // bl mainMBB 9857 // v_restore = 1 9858 // b sinkMBB 9859 // 9860 // mainMBB: 9861 // buf[LabelOffset] = LR 9862 // v_main = 0 9863 // 9864 // sinkMBB: 9865 // v = phi(main, restore) 9866 // 9867 9868 MachineBasicBlock *thisMBB = MBB; 9869 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9870 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9871 MF->insert(I, mainMBB); 9872 MF->insert(I, sinkMBB); 9873 9874 MachineInstrBuilder MIB; 9875 9876 // Transfer the remainder of BB and its successor edges to sinkMBB. 9877 sinkMBB->splice(sinkMBB->begin(), MBB, 9878 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9879 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9880 9881 // Note that the structure of the jmp_buf used here is not compatible 9882 // with that used by libc, and is not designed to be. Specifically, it 9883 // stores only those 'reserved' registers that LLVM does not otherwise 9884 // understand how to spill. Also, by convention, by the time this 9885 // intrinsic is called, Clang has already stored the frame address in the 9886 // first slot of the buffer and stack address in the third. Following the 9887 // X86 target code, we'll store the jump address in the second slot. We also 9888 // need to save the TOC pointer (R2) to handle jumps between shared 9889 // libraries, and that will be stored in the fourth slot. The thread 9890 // identifier (R13) is not affected. 9891 9892 // thisMBB: 9893 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9894 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9895 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9896 9897 // Prepare IP either in reg. 9898 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9899 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9900 unsigned BufReg = MI.getOperand(1).getReg(); 9901 9902 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9903 setUsesTOCBasePtr(*MBB->getParent()); 9904 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9905 .addReg(PPC::X2) 9906 .addImm(TOCOffset) 9907 .addReg(BufReg); 9908 MIB.setMemRefs(MMOBegin, MMOEnd); 9909 } 9910 9911 // Naked functions never have a base pointer, and so we use r1. For all 9912 // other functions, this decision must be delayed until during PEI. 9913 unsigned BaseReg; 9914 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 9915 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9916 else 9917 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9918 9919 MIB = BuildMI(*thisMBB, MI, DL, 9920 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9921 .addReg(BaseReg) 9922 .addImm(BPOffset) 9923 .addReg(BufReg); 9924 MIB.setMemRefs(MMOBegin, MMOEnd); 9925 9926 // Setup 9927 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9928 MIB.addRegMask(TRI->getNoPreservedMask()); 9929 9930 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9931 9932 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9933 .addMBB(mainMBB); 9934 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9935 9936 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9937 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9938 9939 // mainMBB: 9940 // mainDstReg = 0 9941 MIB = 9942 BuildMI(mainMBB, DL, 9943 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9944 9945 // Store IP 9946 if (Subtarget.isPPC64()) { 9947 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9948 .addReg(LabelReg) 9949 .addImm(LabelOffset) 9950 .addReg(BufReg); 9951 } else { 9952 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9953 .addReg(LabelReg) 9954 .addImm(LabelOffset) 9955 .addReg(BufReg); 9956 } 9957 9958 MIB.setMemRefs(MMOBegin, MMOEnd); 9959 9960 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9961 mainMBB->addSuccessor(sinkMBB); 9962 9963 // sinkMBB: 9964 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9965 TII->get(PPC::PHI), DstReg) 9966 .addReg(mainDstReg).addMBB(mainMBB) 9967 .addReg(restoreDstReg).addMBB(thisMBB); 9968 9969 MI.eraseFromParent(); 9970 return sinkMBB; 9971 } 9972 9973 MachineBasicBlock * 9974 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9975 MachineBasicBlock *MBB) const { 9976 DebugLoc DL = MI.getDebugLoc(); 9977 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9978 9979 MachineFunction *MF = MBB->getParent(); 9980 MachineRegisterInfo &MRI = MF->getRegInfo(); 9981 9982 // Memory Reference 9983 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9984 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9985 9986 MVT PVT = getPointerTy(MF->getDataLayout()); 9987 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9988 "Invalid Pointer Size!"); 9989 9990 const TargetRegisterClass *RC = 9991 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9992 unsigned Tmp = MRI.createVirtualRegister(RC); 9993 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9994 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9995 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9996 unsigned BP = 9997 (PVT == MVT::i64) 9998 ? PPC::X30 9999 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10000 : PPC::R30); 10001 10002 MachineInstrBuilder MIB; 10003 10004 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10005 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10006 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10007 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10008 10009 unsigned BufReg = MI.getOperand(0).getReg(); 10010 10011 // Reload FP (the jumped-to function may not have had a 10012 // frame pointer, and if so, then its r31 will be restored 10013 // as necessary). 10014 if (PVT == MVT::i64) { 10015 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10016 .addImm(0) 10017 .addReg(BufReg); 10018 } else { 10019 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10020 .addImm(0) 10021 .addReg(BufReg); 10022 } 10023 MIB.setMemRefs(MMOBegin, MMOEnd); 10024 10025 // Reload IP 10026 if (PVT == MVT::i64) { 10027 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10028 .addImm(LabelOffset) 10029 .addReg(BufReg); 10030 } else { 10031 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10032 .addImm(LabelOffset) 10033 .addReg(BufReg); 10034 } 10035 MIB.setMemRefs(MMOBegin, MMOEnd); 10036 10037 // Reload SP 10038 if (PVT == MVT::i64) { 10039 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10040 .addImm(SPOffset) 10041 .addReg(BufReg); 10042 } else { 10043 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10044 .addImm(SPOffset) 10045 .addReg(BufReg); 10046 } 10047 MIB.setMemRefs(MMOBegin, MMOEnd); 10048 10049 // Reload BP 10050 if (PVT == MVT::i64) { 10051 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10052 .addImm(BPOffset) 10053 .addReg(BufReg); 10054 } else { 10055 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10056 .addImm(BPOffset) 10057 .addReg(BufReg); 10058 } 10059 MIB.setMemRefs(MMOBegin, MMOEnd); 10060 10061 // Reload TOC 10062 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10063 setUsesTOCBasePtr(*MBB->getParent()); 10064 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10065 .addImm(TOCOffset) 10066 .addReg(BufReg); 10067 10068 MIB.setMemRefs(MMOBegin, MMOEnd); 10069 } 10070 10071 // Jump 10072 BuildMI(*MBB, MI, DL, 10073 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10074 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10075 10076 MI.eraseFromParent(); 10077 return MBB; 10078 } 10079 10080 MachineBasicBlock * 10081 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10082 MachineBasicBlock *BB) const { 10083 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10084 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10085 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10086 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10087 // Call lowering should have added an r2 operand to indicate a dependence 10088 // on the TOC base pointer value. It can't however, because there is no 10089 // way to mark the dependence as implicit there, and so the stackmap code 10090 // will confuse it with a regular operand. Instead, add the dependence 10091 // here. 10092 setUsesTOCBasePtr(*BB->getParent()); 10093 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10094 } 10095 10096 return emitPatchPoint(MI, BB); 10097 } 10098 10099 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10100 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10101 return emitEHSjLjSetJmp(MI, BB); 10102 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10103 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10104 return emitEHSjLjLongJmp(MI, BB); 10105 } 10106 10107 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10108 10109 // To "insert" these instructions we actually have to insert their 10110 // control-flow patterns. 10111 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10112 MachineFunction::iterator It = ++BB->getIterator(); 10113 10114 MachineFunction *F = BB->getParent(); 10115 10116 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10117 MI.getOpcode() == PPC::SELECT_CC_I8 || 10118 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10119 SmallVector<MachineOperand, 2> Cond; 10120 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10121 MI.getOpcode() == PPC::SELECT_CC_I8) 10122 Cond.push_back(MI.getOperand(4)); 10123 else 10124 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10125 Cond.push_back(MI.getOperand(1)); 10126 10127 DebugLoc dl = MI.getDebugLoc(); 10128 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10129 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10130 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10131 MI.getOpcode() == PPC::SELECT_CC_I8 || 10132 MI.getOpcode() == PPC::SELECT_CC_F4 || 10133 MI.getOpcode() == PPC::SELECT_CC_F8 || 10134 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10135 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10136 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10137 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10138 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10139 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10140 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10141 MI.getOpcode() == PPC::SELECT_I4 || 10142 MI.getOpcode() == PPC::SELECT_I8 || 10143 MI.getOpcode() == PPC::SELECT_F4 || 10144 MI.getOpcode() == PPC::SELECT_F8 || 10145 MI.getOpcode() == PPC::SELECT_QFRC || 10146 MI.getOpcode() == PPC::SELECT_QSRC || 10147 MI.getOpcode() == PPC::SELECT_QBRC || 10148 MI.getOpcode() == PPC::SELECT_VRRC || 10149 MI.getOpcode() == PPC::SELECT_VSFRC || 10150 MI.getOpcode() == PPC::SELECT_VSSRC || 10151 MI.getOpcode() == PPC::SELECT_VSRC) { 10152 // The incoming instruction knows the destination vreg to set, the 10153 // condition code register to branch on, the true/false values to 10154 // select between, and a branch opcode to use. 10155 10156 // thisMBB: 10157 // ... 10158 // TrueVal = ... 10159 // cmpTY ccX, r1, r2 10160 // bCC copy1MBB 10161 // fallthrough --> copy0MBB 10162 MachineBasicBlock *thisMBB = BB; 10163 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10164 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10165 DebugLoc dl = MI.getDebugLoc(); 10166 F->insert(It, copy0MBB); 10167 F->insert(It, sinkMBB); 10168 10169 // Transfer the remainder of BB and its successor edges to sinkMBB. 10170 sinkMBB->splice(sinkMBB->begin(), BB, 10171 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10172 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10173 10174 // Next, add the true and fallthrough blocks as its successors. 10175 BB->addSuccessor(copy0MBB); 10176 BB->addSuccessor(sinkMBB); 10177 10178 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10179 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10180 MI.getOpcode() == PPC::SELECT_QFRC || 10181 MI.getOpcode() == PPC::SELECT_QSRC || 10182 MI.getOpcode() == PPC::SELECT_QBRC || 10183 MI.getOpcode() == PPC::SELECT_VRRC || 10184 MI.getOpcode() == PPC::SELECT_VSFRC || 10185 MI.getOpcode() == PPC::SELECT_VSSRC || 10186 MI.getOpcode() == PPC::SELECT_VSRC) { 10187 BuildMI(BB, dl, TII->get(PPC::BC)) 10188 .addReg(MI.getOperand(1).getReg()) 10189 .addMBB(sinkMBB); 10190 } else { 10191 unsigned SelectPred = MI.getOperand(4).getImm(); 10192 BuildMI(BB, dl, TII->get(PPC::BCC)) 10193 .addImm(SelectPred) 10194 .addReg(MI.getOperand(1).getReg()) 10195 .addMBB(sinkMBB); 10196 } 10197 10198 // copy0MBB: 10199 // %FalseValue = ... 10200 // # fallthrough to sinkMBB 10201 BB = copy0MBB; 10202 10203 // Update machine-CFG edges 10204 BB->addSuccessor(sinkMBB); 10205 10206 // sinkMBB: 10207 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10208 // ... 10209 BB = sinkMBB; 10210 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10211 .addReg(MI.getOperand(3).getReg()) 10212 .addMBB(copy0MBB) 10213 .addReg(MI.getOperand(2).getReg()) 10214 .addMBB(thisMBB); 10215 } else if (MI.getOpcode() == PPC::ReadTB) { 10216 // To read the 64-bit time-base register on a 32-bit target, we read the 10217 // two halves. Should the counter have wrapped while it was being read, we 10218 // need to try again. 10219 // ... 10220 // readLoop: 10221 // mfspr Rx,TBU # load from TBU 10222 // mfspr Ry,TB # load from TB 10223 // mfspr Rz,TBU # load from TBU 10224 // cmpw crX,Rx,Rz # check if 'old'='new' 10225 // bne readLoop # branch if they're not equal 10226 // ... 10227 10228 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10229 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10230 DebugLoc dl = MI.getDebugLoc(); 10231 F->insert(It, readMBB); 10232 F->insert(It, sinkMBB); 10233 10234 // Transfer the remainder of BB and its successor edges to sinkMBB. 10235 sinkMBB->splice(sinkMBB->begin(), BB, 10236 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10237 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10238 10239 BB->addSuccessor(readMBB); 10240 BB = readMBB; 10241 10242 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10243 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10244 unsigned LoReg = MI.getOperand(0).getReg(); 10245 unsigned HiReg = MI.getOperand(1).getReg(); 10246 10247 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10248 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10249 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10250 10251 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10252 10253 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10254 .addReg(HiReg).addReg(ReadAgainReg); 10255 BuildMI(BB, dl, TII->get(PPC::BCC)) 10256 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10257 10258 BB->addSuccessor(readMBB); 10259 BB->addSuccessor(sinkMBB); 10260 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10261 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10262 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10263 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10264 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10265 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10266 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10267 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10268 10269 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10270 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10271 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10272 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10273 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10274 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10275 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10276 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10277 10278 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10279 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10280 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10281 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10282 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10283 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10284 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10285 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10286 10287 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10288 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10289 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10290 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10291 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10292 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10293 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10294 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10295 10296 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10297 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10298 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10299 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10300 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10301 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10302 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10303 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10304 10305 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10306 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10307 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10308 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10309 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10310 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10311 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10312 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10313 10314 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10315 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10316 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10317 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10318 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10319 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10320 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10321 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10322 10323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10324 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10325 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10326 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10327 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10328 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10329 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10330 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10331 10332 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10333 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10334 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10335 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10336 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10337 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10338 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10339 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10340 10341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10342 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10343 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10344 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10345 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10346 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10347 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10348 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10349 10350 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10351 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10352 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10353 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10354 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10355 BB = EmitAtomicBinary(MI, BB, 4, 0); 10356 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10357 BB = EmitAtomicBinary(MI, BB, 8, 0); 10358 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10359 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10360 (Subtarget.hasPartwordAtomics() && 10361 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10362 (Subtarget.hasPartwordAtomics() && 10363 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10364 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10365 10366 auto LoadMnemonic = PPC::LDARX; 10367 auto StoreMnemonic = PPC::STDCX; 10368 switch (MI.getOpcode()) { 10369 default: 10370 llvm_unreachable("Compare and swap of unknown size"); 10371 case PPC::ATOMIC_CMP_SWAP_I8: 10372 LoadMnemonic = PPC::LBARX; 10373 StoreMnemonic = PPC::STBCX; 10374 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10375 break; 10376 case PPC::ATOMIC_CMP_SWAP_I16: 10377 LoadMnemonic = PPC::LHARX; 10378 StoreMnemonic = PPC::STHCX; 10379 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10380 break; 10381 case PPC::ATOMIC_CMP_SWAP_I32: 10382 LoadMnemonic = PPC::LWARX; 10383 StoreMnemonic = PPC::STWCX; 10384 break; 10385 case PPC::ATOMIC_CMP_SWAP_I64: 10386 LoadMnemonic = PPC::LDARX; 10387 StoreMnemonic = PPC::STDCX; 10388 break; 10389 } 10390 unsigned dest = MI.getOperand(0).getReg(); 10391 unsigned ptrA = MI.getOperand(1).getReg(); 10392 unsigned ptrB = MI.getOperand(2).getReg(); 10393 unsigned oldval = MI.getOperand(3).getReg(); 10394 unsigned newval = MI.getOperand(4).getReg(); 10395 DebugLoc dl = MI.getDebugLoc(); 10396 10397 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10398 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10399 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10400 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10401 F->insert(It, loop1MBB); 10402 F->insert(It, loop2MBB); 10403 F->insert(It, midMBB); 10404 F->insert(It, exitMBB); 10405 exitMBB->splice(exitMBB->begin(), BB, 10406 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10407 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10408 10409 // thisMBB: 10410 // ... 10411 // fallthrough --> loopMBB 10412 BB->addSuccessor(loop1MBB); 10413 10414 // loop1MBB: 10415 // l[bhwd]arx dest, ptr 10416 // cmp[wd] dest, oldval 10417 // bne- midMBB 10418 // loop2MBB: 10419 // st[bhwd]cx. newval, ptr 10420 // bne- loopMBB 10421 // b exitBB 10422 // midMBB: 10423 // st[bhwd]cx. dest, ptr 10424 // exitBB: 10425 BB = loop1MBB; 10426 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10427 .addReg(ptrA).addReg(ptrB); 10428 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10429 .addReg(oldval).addReg(dest); 10430 BuildMI(BB, dl, TII->get(PPC::BCC)) 10431 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10432 BB->addSuccessor(loop2MBB); 10433 BB->addSuccessor(midMBB); 10434 10435 BB = loop2MBB; 10436 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10437 .addReg(newval).addReg(ptrA).addReg(ptrB); 10438 BuildMI(BB, dl, TII->get(PPC::BCC)) 10439 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10440 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10441 BB->addSuccessor(loop1MBB); 10442 BB->addSuccessor(exitMBB); 10443 10444 BB = midMBB; 10445 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10446 .addReg(dest).addReg(ptrA).addReg(ptrB); 10447 BB->addSuccessor(exitMBB); 10448 10449 // exitMBB: 10450 // ... 10451 BB = exitMBB; 10452 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10453 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10454 // We must use 64-bit registers for addresses when targeting 64-bit, 10455 // since we're actually doing arithmetic on them. Other registers 10456 // can be 32-bit. 10457 bool is64bit = Subtarget.isPPC64(); 10458 bool isLittleEndian = Subtarget.isLittleEndian(); 10459 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10460 10461 unsigned dest = MI.getOperand(0).getReg(); 10462 unsigned ptrA = MI.getOperand(1).getReg(); 10463 unsigned ptrB = MI.getOperand(2).getReg(); 10464 unsigned oldval = MI.getOperand(3).getReg(); 10465 unsigned newval = MI.getOperand(4).getReg(); 10466 DebugLoc dl = MI.getDebugLoc(); 10467 10468 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10469 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10470 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10471 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10472 F->insert(It, loop1MBB); 10473 F->insert(It, loop2MBB); 10474 F->insert(It, midMBB); 10475 F->insert(It, exitMBB); 10476 exitMBB->splice(exitMBB->begin(), BB, 10477 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10478 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10479 10480 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10481 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10482 : &PPC::GPRCRegClass; 10483 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10484 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10485 unsigned ShiftReg = 10486 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10487 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10488 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10489 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10490 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10491 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10492 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10493 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10494 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10495 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10496 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10497 unsigned Ptr1Reg; 10498 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10499 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10500 // thisMBB: 10501 // ... 10502 // fallthrough --> loopMBB 10503 BB->addSuccessor(loop1MBB); 10504 10505 // The 4-byte load must be aligned, while a char or short may be 10506 // anywhere in the word. Hence all this nasty bookkeeping code. 10507 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10508 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10509 // xori shift, shift1, 24 [16] 10510 // rlwinm ptr, ptr1, 0, 0, 29 10511 // slw newval2, newval, shift 10512 // slw oldval2, oldval,shift 10513 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10514 // slw mask, mask2, shift 10515 // and newval3, newval2, mask 10516 // and oldval3, oldval2, mask 10517 // loop1MBB: 10518 // lwarx tmpDest, ptr 10519 // and tmp, tmpDest, mask 10520 // cmpw tmp, oldval3 10521 // bne- midMBB 10522 // loop2MBB: 10523 // andc tmp2, tmpDest, mask 10524 // or tmp4, tmp2, newval3 10525 // stwcx. tmp4, ptr 10526 // bne- loop1MBB 10527 // b exitBB 10528 // midMBB: 10529 // stwcx. tmpDest, ptr 10530 // exitBB: 10531 // srw dest, tmpDest, shift 10532 if (ptrA != ZeroReg) { 10533 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10534 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10535 .addReg(ptrA).addReg(ptrB); 10536 } else { 10537 Ptr1Reg = ptrB; 10538 } 10539 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10540 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10541 if (!isLittleEndian) 10542 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10543 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10544 if (is64bit) 10545 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10546 .addReg(Ptr1Reg).addImm(0).addImm(61); 10547 else 10548 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10549 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10550 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10551 .addReg(newval).addReg(ShiftReg); 10552 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10553 .addReg(oldval).addReg(ShiftReg); 10554 if (is8bit) 10555 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10556 else { 10557 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10558 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10559 .addReg(Mask3Reg).addImm(65535); 10560 } 10561 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10562 .addReg(Mask2Reg).addReg(ShiftReg); 10563 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10564 .addReg(NewVal2Reg).addReg(MaskReg); 10565 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10566 .addReg(OldVal2Reg).addReg(MaskReg); 10567 10568 BB = loop1MBB; 10569 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10570 .addReg(ZeroReg).addReg(PtrReg); 10571 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10572 .addReg(TmpDestReg).addReg(MaskReg); 10573 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10574 .addReg(TmpReg).addReg(OldVal3Reg); 10575 BuildMI(BB, dl, TII->get(PPC::BCC)) 10576 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10577 BB->addSuccessor(loop2MBB); 10578 BB->addSuccessor(midMBB); 10579 10580 BB = loop2MBB; 10581 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10582 .addReg(TmpDestReg).addReg(MaskReg); 10583 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10584 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10585 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10586 .addReg(ZeroReg).addReg(PtrReg); 10587 BuildMI(BB, dl, TII->get(PPC::BCC)) 10588 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10589 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10590 BB->addSuccessor(loop1MBB); 10591 BB->addSuccessor(exitMBB); 10592 10593 BB = midMBB; 10594 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10595 .addReg(ZeroReg).addReg(PtrReg); 10596 BB->addSuccessor(exitMBB); 10597 10598 // exitMBB: 10599 // ... 10600 BB = exitMBB; 10601 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10602 .addReg(ShiftReg); 10603 } else if (MI.getOpcode() == PPC::FADDrtz) { 10604 // This pseudo performs an FADD with rounding mode temporarily forced 10605 // to round-to-zero. We emit this via custom inserter since the FPSCR 10606 // is not modeled at the SelectionDAG level. 10607 unsigned Dest = MI.getOperand(0).getReg(); 10608 unsigned Src1 = MI.getOperand(1).getReg(); 10609 unsigned Src2 = MI.getOperand(2).getReg(); 10610 DebugLoc dl = MI.getDebugLoc(); 10611 10612 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10613 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10614 10615 // Save FPSCR value. 10616 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10617 10618 // Set rounding mode to round-to-zero. 10619 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10620 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10621 10622 // Perform addition. 10623 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10624 10625 // Restore FPSCR value. 10626 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10627 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10628 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10629 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10630 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10631 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10632 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10633 ? PPC::ANDIo8 10634 : PPC::ANDIo; 10635 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10636 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10637 10638 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10639 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10640 &PPC::GPRCRegClass : 10641 &PPC::G8RCRegClass); 10642 10643 DebugLoc dl = MI.getDebugLoc(); 10644 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10645 .addReg(MI.getOperand(1).getReg()) 10646 .addImm(1); 10647 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10648 MI.getOperand(0).getReg()) 10649 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10650 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10651 DebugLoc Dl = MI.getDebugLoc(); 10652 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10653 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10654 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10655 return BB; 10656 } else { 10657 llvm_unreachable("Unexpected instr type to insert"); 10658 } 10659 10660 MI.eraseFromParent(); // The pseudo instruction is gone now. 10661 return BB; 10662 } 10663 10664 //===----------------------------------------------------------------------===// 10665 // Target Optimization Hooks 10666 //===----------------------------------------------------------------------===// 10667 10668 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10669 // For the estimates, convergence is quadratic, so we essentially double the 10670 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10671 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10672 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10673 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10674 if (VT.getScalarType() == MVT::f64) 10675 RefinementSteps++; 10676 return RefinementSteps; 10677 } 10678 10679 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10680 int Enabled, int &RefinementSteps, 10681 bool &UseOneConstNR, 10682 bool Reciprocal) const { 10683 EVT VT = Operand.getValueType(); 10684 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10685 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10686 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10687 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10688 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10689 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10690 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10691 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10692 10693 UseOneConstNR = true; 10694 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10695 } 10696 return SDValue(); 10697 } 10698 10699 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10700 int Enabled, 10701 int &RefinementSteps) const { 10702 EVT VT = Operand.getValueType(); 10703 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10704 (VT == MVT::f64 && Subtarget.hasFRE()) || 10705 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10706 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10707 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10708 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10709 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10710 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10711 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10712 } 10713 return SDValue(); 10714 } 10715 10716 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10717 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10718 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10719 // enabled for division), this functionality is redundant with the default 10720 // combiner logic (once the division -> reciprocal/multiply transformation 10721 // has taken place). As a result, this matters more for older cores than for 10722 // newer ones. 10723 10724 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10725 // reciprocal if there are two or more FDIVs (for embedded cores with only 10726 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10727 switch (Subtarget.getDarwinDirective()) { 10728 default: 10729 return 3; 10730 case PPC::DIR_440: 10731 case PPC::DIR_A2: 10732 case PPC::DIR_E500mc: 10733 case PPC::DIR_E5500: 10734 return 2; 10735 } 10736 } 10737 10738 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10739 // collapsed, and so we need to look through chains of them. 10740 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10741 int64_t& Offset, SelectionDAG &DAG) { 10742 if (DAG.isBaseWithConstantOffset(Loc)) { 10743 Base = Loc.getOperand(0); 10744 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10745 10746 // The base might itself be a base plus an offset, and if so, accumulate 10747 // that as well. 10748 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10749 } 10750 } 10751 10752 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10753 unsigned Bytes, int Dist, 10754 SelectionDAG &DAG) { 10755 if (VT.getSizeInBits() / 8 != Bytes) 10756 return false; 10757 10758 SDValue BaseLoc = Base->getBasePtr(); 10759 if (Loc.getOpcode() == ISD::FrameIndex) { 10760 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10761 return false; 10762 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10763 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10764 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10765 int FS = MFI.getObjectSize(FI); 10766 int BFS = MFI.getObjectSize(BFI); 10767 if (FS != BFS || FS != (int)Bytes) return false; 10768 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10769 } 10770 10771 SDValue Base1 = Loc, Base2 = BaseLoc; 10772 int64_t Offset1 = 0, Offset2 = 0; 10773 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10774 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10775 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10776 return true; 10777 10778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10779 const GlobalValue *GV1 = nullptr; 10780 const GlobalValue *GV2 = nullptr; 10781 Offset1 = 0; 10782 Offset2 = 0; 10783 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10784 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10785 if (isGA1 && isGA2 && GV1 == GV2) 10786 return Offset1 == (Offset2 + Dist*Bytes); 10787 return false; 10788 } 10789 10790 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10791 // not enforce equality of the chain operands. 10792 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10793 unsigned Bytes, int Dist, 10794 SelectionDAG &DAG) { 10795 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10796 EVT VT = LS->getMemoryVT(); 10797 SDValue Loc = LS->getBasePtr(); 10798 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10799 } 10800 10801 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10802 EVT VT; 10803 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10804 default: return false; 10805 case Intrinsic::ppc_qpx_qvlfd: 10806 case Intrinsic::ppc_qpx_qvlfda: 10807 VT = MVT::v4f64; 10808 break; 10809 case Intrinsic::ppc_qpx_qvlfs: 10810 case Intrinsic::ppc_qpx_qvlfsa: 10811 VT = MVT::v4f32; 10812 break; 10813 case Intrinsic::ppc_qpx_qvlfcd: 10814 case Intrinsic::ppc_qpx_qvlfcda: 10815 VT = MVT::v2f64; 10816 break; 10817 case Intrinsic::ppc_qpx_qvlfcs: 10818 case Intrinsic::ppc_qpx_qvlfcsa: 10819 VT = MVT::v2f32; 10820 break; 10821 case Intrinsic::ppc_qpx_qvlfiwa: 10822 case Intrinsic::ppc_qpx_qvlfiwz: 10823 case Intrinsic::ppc_altivec_lvx: 10824 case Intrinsic::ppc_altivec_lvxl: 10825 case Intrinsic::ppc_vsx_lxvw4x: 10826 case Intrinsic::ppc_vsx_lxvw4x_be: 10827 VT = MVT::v4i32; 10828 break; 10829 case Intrinsic::ppc_vsx_lxvd2x: 10830 case Intrinsic::ppc_vsx_lxvd2x_be: 10831 VT = MVT::v2f64; 10832 break; 10833 case Intrinsic::ppc_altivec_lvebx: 10834 VT = MVT::i8; 10835 break; 10836 case Intrinsic::ppc_altivec_lvehx: 10837 VT = MVT::i16; 10838 break; 10839 case Intrinsic::ppc_altivec_lvewx: 10840 VT = MVT::i32; 10841 break; 10842 } 10843 10844 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10845 } 10846 10847 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10848 EVT VT; 10849 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10850 default: return false; 10851 case Intrinsic::ppc_qpx_qvstfd: 10852 case Intrinsic::ppc_qpx_qvstfda: 10853 VT = MVT::v4f64; 10854 break; 10855 case Intrinsic::ppc_qpx_qvstfs: 10856 case Intrinsic::ppc_qpx_qvstfsa: 10857 VT = MVT::v4f32; 10858 break; 10859 case Intrinsic::ppc_qpx_qvstfcd: 10860 case Intrinsic::ppc_qpx_qvstfcda: 10861 VT = MVT::v2f64; 10862 break; 10863 case Intrinsic::ppc_qpx_qvstfcs: 10864 case Intrinsic::ppc_qpx_qvstfcsa: 10865 VT = MVT::v2f32; 10866 break; 10867 case Intrinsic::ppc_qpx_qvstfiw: 10868 case Intrinsic::ppc_qpx_qvstfiwa: 10869 case Intrinsic::ppc_altivec_stvx: 10870 case Intrinsic::ppc_altivec_stvxl: 10871 case Intrinsic::ppc_vsx_stxvw4x: 10872 VT = MVT::v4i32; 10873 break; 10874 case Intrinsic::ppc_vsx_stxvd2x: 10875 VT = MVT::v2f64; 10876 break; 10877 case Intrinsic::ppc_vsx_stxvw4x_be: 10878 VT = MVT::v4i32; 10879 break; 10880 case Intrinsic::ppc_vsx_stxvd2x_be: 10881 VT = MVT::v2f64; 10882 break; 10883 case Intrinsic::ppc_altivec_stvebx: 10884 VT = MVT::i8; 10885 break; 10886 case Intrinsic::ppc_altivec_stvehx: 10887 VT = MVT::i16; 10888 break; 10889 case Intrinsic::ppc_altivec_stvewx: 10890 VT = MVT::i32; 10891 break; 10892 } 10893 10894 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10895 } 10896 10897 return false; 10898 } 10899 10900 // Return true is there is a nearyby consecutive load to the one provided 10901 // (regardless of alignment). We search up and down the chain, looking though 10902 // token factors and other loads (but nothing else). As a result, a true result 10903 // indicates that it is safe to create a new consecutive load adjacent to the 10904 // load provided. 10905 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10906 SDValue Chain = LD->getChain(); 10907 EVT VT = LD->getMemoryVT(); 10908 10909 SmallSet<SDNode *, 16> LoadRoots; 10910 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10911 SmallSet<SDNode *, 16> Visited; 10912 10913 // First, search up the chain, branching to follow all token-factor operands. 10914 // If we find a consecutive load, then we're done, otherwise, record all 10915 // nodes just above the top-level loads and token factors. 10916 while (!Queue.empty()) { 10917 SDNode *ChainNext = Queue.pop_back_val(); 10918 if (!Visited.insert(ChainNext).second) 10919 continue; 10920 10921 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10922 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10923 return true; 10924 10925 if (!Visited.count(ChainLD->getChain().getNode())) 10926 Queue.push_back(ChainLD->getChain().getNode()); 10927 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10928 for (const SDUse &O : ChainNext->ops()) 10929 if (!Visited.count(O.getNode())) 10930 Queue.push_back(O.getNode()); 10931 } else 10932 LoadRoots.insert(ChainNext); 10933 } 10934 10935 // Second, search down the chain, starting from the top-level nodes recorded 10936 // in the first phase. These top-level nodes are the nodes just above all 10937 // loads and token factors. Starting with their uses, recursively look though 10938 // all loads (just the chain uses) and token factors to find a consecutive 10939 // load. 10940 Visited.clear(); 10941 Queue.clear(); 10942 10943 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10944 IE = LoadRoots.end(); I != IE; ++I) { 10945 Queue.push_back(*I); 10946 10947 while (!Queue.empty()) { 10948 SDNode *LoadRoot = Queue.pop_back_val(); 10949 if (!Visited.insert(LoadRoot).second) 10950 continue; 10951 10952 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10953 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10954 return true; 10955 10956 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10957 UE = LoadRoot->use_end(); UI != UE; ++UI) 10958 if (((isa<MemSDNode>(*UI) && 10959 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10960 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10961 Queue.push_back(*UI); 10962 } 10963 } 10964 10965 return false; 10966 } 10967 10968 /// This function is called when we have proved that a SETCC node can be replaced 10969 /// by subtraction (and other supporting instructions) so that the result of 10970 /// comparison is kept in a GPR instead of CR. This function is purely for 10971 /// codegen purposes and has some flags to guide the codegen process. 10972 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10973 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10974 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10975 10976 // Zero extend the operands to the largest legal integer. Originally, they 10977 // must be of a strictly smaller size. 10978 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10979 DAG.getConstant(Size, DL, MVT::i32)); 10980 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10981 DAG.getConstant(Size, DL, MVT::i32)); 10982 10983 // Swap if needed. Depends on the condition code. 10984 if (Swap) 10985 std::swap(Op0, Op1); 10986 10987 // Subtract extended integers. 10988 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10989 10990 // Move the sign bit to the least significant position and zero out the rest. 10991 // Now the least significant bit carries the result of original comparison. 10992 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10993 DAG.getConstant(Size - 1, DL, MVT::i32)); 10994 auto Final = Shifted; 10995 10996 // Complement the result if needed. Based on the condition code. 10997 if (Complement) 10998 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10999 DAG.getConstant(1, DL, MVT::i64)); 11000 11001 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11002 } 11003 11004 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11005 DAGCombinerInfo &DCI) const { 11006 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11007 11008 SelectionDAG &DAG = DCI.DAG; 11009 SDLoc DL(N); 11010 11011 // Size of integers being compared has a critical role in the following 11012 // analysis, so we prefer to do this when all types are legal. 11013 if (!DCI.isAfterLegalizeDAG()) 11014 return SDValue(); 11015 11016 // If all users of SETCC extend its value to a legal integer type 11017 // then we replace SETCC with a subtraction 11018 for (SDNode::use_iterator UI = N->use_begin(), 11019 UE = N->use_end(); UI != UE; ++UI) { 11020 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11021 return SDValue(); 11022 } 11023 11024 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11025 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11026 11027 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11028 11029 if (OpSize < Size) { 11030 switch (CC) { 11031 default: break; 11032 case ISD::SETULT: 11033 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11034 case ISD::SETULE: 11035 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11036 case ISD::SETUGT: 11037 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11038 case ISD::SETUGE: 11039 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11040 } 11041 } 11042 11043 return SDValue(); 11044 } 11045 11046 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11047 DAGCombinerInfo &DCI) const { 11048 SelectionDAG &DAG = DCI.DAG; 11049 SDLoc dl(N); 11050 11051 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11052 // If we're tracking CR bits, we need to be careful that we don't have: 11053 // trunc(binary-ops(zext(x), zext(y))) 11054 // or 11055 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11056 // such that we're unnecessarily moving things into GPRs when it would be 11057 // better to keep them in CR bits. 11058 11059 // Note that trunc here can be an actual i1 trunc, or can be the effective 11060 // truncation that comes from a setcc or select_cc. 11061 if (N->getOpcode() == ISD::TRUNCATE && 11062 N->getValueType(0) != MVT::i1) 11063 return SDValue(); 11064 11065 if (N->getOperand(0).getValueType() != MVT::i32 && 11066 N->getOperand(0).getValueType() != MVT::i64) 11067 return SDValue(); 11068 11069 if (N->getOpcode() == ISD::SETCC || 11070 N->getOpcode() == ISD::SELECT_CC) { 11071 // If we're looking at a comparison, then we need to make sure that the 11072 // high bits (all except for the first) don't matter the result. 11073 ISD::CondCode CC = 11074 cast<CondCodeSDNode>(N->getOperand( 11075 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11076 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11077 11078 if (ISD::isSignedIntSetCC(CC)) { 11079 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11080 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11081 return SDValue(); 11082 } else if (ISD::isUnsignedIntSetCC(CC)) { 11083 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11084 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11085 !DAG.MaskedValueIsZero(N->getOperand(1), 11086 APInt::getHighBitsSet(OpBits, OpBits-1))) 11087 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11088 : SDValue()); 11089 } else { 11090 // This is neither a signed nor an unsigned comparison, just make sure 11091 // that the high bits are equal. 11092 KnownBits Op1Known, Op2Known; 11093 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11094 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11095 11096 // We don't really care about what is known about the first bit (if 11097 // anything), so clear it in all masks prior to comparing them. 11098 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11099 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11100 11101 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11102 return SDValue(); 11103 } 11104 } 11105 11106 // We now know that the higher-order bits are irrelevant, we just need to 11107 // make sure that all of the intermediate operations are bit operations, and 11108 // all inputs are extensions. 11109 if (N->getOperand(0).getOpcode() != ISD::AND && 11110 N->getOperand(0).getOpcode() != ISD::OR && 11111 N->getOperand(0).getOpcode() != ISD::XOR && 11112 N->getOperand(0).getOpcode() != ISD::SELECT && 11113 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11114 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11115 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11116 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11117 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11118 return SDValue(); 11119 11120 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11121 N->getOperand(1).getOpcode() != ISD::AND && 11122 N->getOperand(1).getOpcode() != ISD::OR && 11123 N->getOperand(1).getOpcode() != ISD::XOR && 11124 N->getOperand(1).getOpcode() != ISD::SELECT && 11125 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11126 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11127 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11128 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11129 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11130 return SDValue(); 11131 11132 SmallVector<SDValue, 4> Inputs; 11133 SmallVector<SDValue, 8> BinOps, PromOps; 11134 SmallPtrSet<SDNode *, 16> Visited; 11135 11136 for (unsigned i = 0; i < 2; ++i) { 11137 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11138 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11139 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11140 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11141 isa<ConstantSDNode>(N->getOperand(i))) 11142 Inputs.push_back(N->getOperand(i)); 11143 else 11144 BinOps.push_back(N->getOperand(i)); 11145 11146 if (N->getOpcode() == ISD::TRUNCATE) 11147 break; 11148 } 11149 11150 // Visit all inputs, collect all binary operations (and, or, xor and 11151 // select) that are all fed by extensions. 11152 while (!BinOps.empty()) { 11153 SDValue BinOp = BinOps.back(); 11154 BinOps.pop_back(); 11155 11156 if (!Visited.insert(BinOp.getNode()).second) 11157 continue; 11158 11159 PromOps.push_back(BinOp); 11160 11161 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11162 // The condition of the select is not promoted. 11163 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11164 continue; 11165 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11166 continue; 11167 11168 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11169 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11170 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11171 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11172 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11173 Inputs.push_back(BinOp.getOperand(i)); 11174 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11175 BinOp.getOperand(i).getOpcode() == ISD::OR || 11176 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11177 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11178 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11179 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11180 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11181 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11182 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11183 BinOps.push_back(BinOp.getOperand(i)); 11184 } else { 11185 // We have an input that is not an extension or another binary 11186 // operation; we'll abort this transformation. 11187 return SDValue(); 11188 } 11189 } 11190 } 11191 11192 // Make sure that this is a self-contained cluster of operations (which 11193 // is not quite the same thing as saying that everything has only one 11194 // use). 11195 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11196 if (isa<ConstantSDNode>(Inputs[i])) 11197 continue; 11198 11199 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11200 UE = Inputs[i].getNode()->use_end(); 11201 UI != UE; ++UI) { 11202 SDNode *User = *UI; 11203 if (User != N && !Visited.count(User)) 11204 return SDValue(); 11205 11206 // Make sure that we're not going to promote the non-output-value 11207 // operand(s) or SELECT or SELECT_CC. 11208 // FIXME: Although we could sometimes handle this, and it does occur in 11209 // practice that one of the condition inputs to the select is also one of 11210 // the outputs, we currently can't deal with this. 11211 if (User->getOpcode() == ISD::SELECT) { 11212 if (User->getOperand(0) == Inputs[i]) 11213 return SDValue(); 11214 } else if (User->getOpcode() == ISD::SELECT_CC) { 11215 if (User->getOperand(0) == Inputs[i] || 11216 User->getOperand(1) == Inputs[i]) 11217 return SDValue(); 11218 } 11219 } 11220 } 11221 11222 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11223 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11224 UE = PromOps[i].getNode()->use_end(); 11225 UI != UE; ++UI) { 11226 SDNode *User = *UI; 11227 if (User != N && !Visited.count(User)) 11228 return SDValue(); 11229 11230 // Make sure that we're not going to promote the non-output-value 11231 // operand(s) or SELECT or SELECT_CC. 11232 // FIXME: Although we could sometimes handle this, and it does occur in 11233 // practice that one of the condition inputs to the select is also one of 11234 // the outputs, we currently can't deal with this. 11235 if (User->getOpcode() == ISD::SELECT) { 11236 if (User->getOperand(0) == PromOps[i]) 11237 return SDValue(); 11238 } else if (User->getOpcode() == ISD::SELECT_CC) { 11239 if (User->getOperand(0) == PromOps[i] || 11240 User->getOperand(1) == PromOps[i]) 11241 return SDValue(); 11242 } 11243 } 11244 } 11245 11246 // Replace all inputs with the extension operand. 11247 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11248 // Constants may have users outside the cluster of to-be-promoted nodes, 11249 // and so we need to replace those as we do the promotions. 11250 if (isa<ConstantSDNode>(Inputs[i])) 11251 continue; 11252 else 11253 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11254 } 11255 11256 std::list<HandleSDNode> PromOpHandles; 11257 for (auto &PromOp : PromOps) 11258 PromOpHandles.emplace_back(PromOp); 11259 11260 // Replace all operations (these are all the same, but have a different 11261 // (i1) return type). DAG.getNode will validate that the types of 11262 // a binary operator match, so go through the list in reverse so that 11263 // we've likely promoted both operands first. Any intermediate truncations or 11264 // extensions disappear. 11265 while (!PromOpHandles.empty()) { 11266 SDValue PromOp = PromOpHandles.back().getValue(); 11267 PromOpHandles.pop_back(); 11268 11269 if (PromOp.getOpcode() == ISD::TRUNCATE || 11270 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11271 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11272 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11273 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11274 PromOp.getOperand(0).getValueType() != MVT::i1) { 11275 // The operand is not yet ready (see comment below). 11276 PromOpHandles.emplace_front(PromOp); 11277 continue; 11278 } 11279 11280 SDValue RepValue = PromOp.getOperand(0); 11281 if (isa<ConstantSDNode>(RepValue)) 11282 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11283 11284 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11285 continue; 11286 } 11287 11288 unsigned C; 11289 switch (PromOp.getOpcode()) { 11290 default: C = 0; break; 11291 case ISD::SELECT: C = 1; break; 11292 case ISD::SELECT_CC: C = 2; break; 11293 } 11294 11295 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11296 PromOp.getOperand(C).getValueType() != MVT::i1) || 11297 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11298 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11299 // The to-be-promoted operands of this node have not yet been 11300 // promoted (this should be rare because we're going through the 11301 // list backward, but if one of the operands has several users in 11302 // this cluster of to-be-promoted nodes, it is possible). 11303 PromOpHandles.emplace_front(PromOp); 11304 continue; 11305 } 11306 11307 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11308 PromOp.getNode()->op_end()); 11309 11310 // If there are any constant inputs, make sure they're replaced now. 11311 for (unsigned i = 0; i < 2; ++i) 11312 if (isa<ConstantSDNode>(Ops[C+i])) 11313 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11314 11315 DAG.ReplaceAllUsesOfValueWith(PromOp, 11316 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11317 } 11318 11319 // Now we're left with the initial truncation itself. 11320 if (N->getOpcode() == ISD::TRUNCATE) 11321 return N->getOperand(0); 11322 11323 // Otherwise, this is a comparison. The operands to be compared have just 11324 // changed type (to i1), but everything else is the same. 11325 return SDValue(N, 0); 11326 } 11327 11328 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11329 DAGCombinerInfo &DCI) const { 11330 SelectionDAG &DAG = DCI.DAG; 11331 SDLoc dl(N); 11332 11333 // If we're tracking CR bits, we need to be careful that we don't have: 11334 // zext(binary-ops(trunc(x), trunc(y))) 11335 // or 11336 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11337 // such that we're unnecessarily moving things into CR bits that can more 11338 // efficiently stay in GPRs. Note that if we're not certain that the high 11339 // bits are set as required by the final extension, we still may need to do 11340 // some masking to get the proper behavior. 11341 11342 // This same functionality is important on PPC64 when dealing with 11343 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11344 // the return values of functions. Because it is so similar, it is handled 11345 // here as well. 11346 11347 if (N->getValueType(0) != MVT::i32 && 11348 N->getValueType(0) != MVT::i64) 11349 return SDValue(); 11350 11351 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11352 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11353 return SDValue(); 11354 11355 if (N->getOperand(0).getOpcode() != ISD::AND && 11356 N->getOperand(0).getOpcode() != ISD::OR && 11357 N->getOperand(0).getOpcode() != ISD::XOR && 11358 N->getOperand(0).getOpcode() != ISD::SELECT && 11359 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11360 return SDValue(); 11361 11362 SmallVector<SDValue, 4> Inputs; 11363 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11364 SmallPtrSet<SDNode *, 16> Visited; 11365 11366 // Visit all inputs, collect all binary operations (and, or, xor and 11367 // select) that are all fed by truncations. 11368 while (!BinOps.empty()) { 11369 SDValue BinOp = BinOps.back(); 11370 BinOps.pop_back(); 11371 11372 if (!Visited.insert(BinOp.getNode()).second) 11373 continue; 11374 11375 PromOps.push_back(BinOp); 11376 11377 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11378 // The condition of the select is not promoted. 11379 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11380 continue; 11381 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11382 continue; 11383 11384 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11385 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11386 Inputs.push_back(BinOp.getOperand(i)); 11387 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11388 BinOp.getOperand(i).getOpcode() == ISD::OR || 11389 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11390 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11391 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11392 BinOps.push_back(BinOp.getOperand(i)); 11393 } else { 11394 // We have an input that is not a truncation or another binary 11395 // operation; we'll abort this transformation. 11396 return SDValue(); 11397 } 11398 } 11399 } 11400 11401 // The operands of a select that must be truncated when the select is 11402 // promoted because the operand is actually part of the to-be-promoted set. 11403 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11404 11405 // Make sure that this is a self-contained cluster of operations (which 11406 // is not quite the same thing as saying that everything has only one 11407 // use). 11408 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11409 if (isa<ConstantSDNode>(Inputs[i])) 11410 continue; 11411 11412 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11413 UE = Inputs[i].getNode()->use_end(); 11414 UI != UE; ++UI) { 11415 SDNode *User = *UI; 11416 if (User != N && !Visited.count(User)) 11417 return SDValue(); 11418 11419 // If we're going to promote the non-output-value operand(s) or SELECT or 11420 // SELECT_CC, record them for truncation. 11421 if (User->getOpcode() == ISD::SELECT) { 11422 if (User->getOperand(0) == Inputs[i]) 11423 SelectTruncOp[0].insert(std::make_pair(User, 11424 User->getOperand(0).getValueType())); 11425 } else if (User->getOpcode() == ISD::SELECT_CC) { 11426 if (User->getOperand(0) == Inputs[i]) 11427 SelectTruncOp[0].insert(std::make_pair(User, 11428 User->getOperand(0).getValueType())); 11429 if (User->getOperand(1) == Inputs[i]) 11430 SelectTruncOp[1].insert(std::make_pair(User, 11431 User->getOperand(1).getValueType())); 11432 } 11433 } 11434 } 11435 11436 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11437 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11438 UE = PromOps[i].getNode()->use_end(); 11439 UI != UE; ++UI) { 11440 SDNode *User = *UI; 11441 if (User != N && !Visited.count(User)) 11442 return SDValue(); 11443 11444 // If we're going to promote the non-output-value operand(s) or SELECT or 11445 // SELECT_CC, record them for truncation. 11446 if (User->getOpcode() == ISD::SELECT) { 11447 if (User->getOperand(0) == PromOps[i]) 11448 SelectTruncOp[0].insert(std::make_pair(User, 11449 User->getOperand(0).getValueType())); 11450 } else if (User->getOpcode() == ISD::SELECT_CC) { 11451 if (User->getOperand(0) == PromOps[i]) 11452 SelectTruncOp[0].insert(std::make_pair(User, 11453 User->getOperand(0).getValueType())); 11454 if (User->getOperand(1) == PromOps[i]) 11455 SelectTruncOp[1].insert(std::make_pair(User, 11456 User->getOperand(1).getValueType())); 11457 } 11458 } 11459 } 11460 11461 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11462 bool ReallyNeedsExt = false; 11463 if (N->getOpcode() != ISD::ANY_EXTEND) { 11464 // If all of the inputs are not already sign/zero extended, then 11465 // we'll still need to do that at the end. 11466 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11467 if (isa<ConstantSDNode>(Inputs[i])) 11468 continue; 11469 11470 unsigned OpBits = 11471 Inputs[i].getOperand(0).getValueSizeInBits(); 11472 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11473 11474 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11475 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11476 APInt::getHighBitsSet(OpBits, 11477 OpBits-PromBits))) || 11478 (N->getOpcode() == ISD::SIGN_EXTEND && 11479 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11480 (OpBits-(PromBits-1)))) { 11481 ReallyNeedsExt = true; 11482 break; 11483 } 11484 } 11485 } 11486 11487 // Replace all inputs, either with the truncation operand, or a 11488 // truncation or extension to the final output type. 11489 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11490 // Constant inputs need to be replaced with the to-be-promoted nodes that 11491 // use them because they might have users outside of the cluster of 11492 // promoted nodes. 11493 if (isa<ConstantSDNode>(Inputs[i])) 11494 continue; 11495 11496 SDValue InSrc = Inputs[i].getOperand(0); 11497 if (Inputs[i].getValueType() == N->getValueType(0)) 11498 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11499 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11500 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11501 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11502 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11503 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11504 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11505 else 11506 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11507 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11508 } 11509 11510 std::list<HandleSDNode> PromOpHandles; 11511 for (auto &PromOp : PromOps) 11512 PromOpHandles.emplace_back(PromOp); 11513 11514 // Replace all operations (these are all the same, but have a different 11515 // (promoted) return type). DAG.getNode will validate that the types of 11516 // a binary operator match, so go through the list in reverse so that 11517 // we've likely promoted both operands first. 11518 while (!PromOpHandles.empty()) { 11519 SDValue PromOp = PromOpHandles.back().getValue(); 11520 PromOpHandles.pop_back(); 11521 11522 unsigned C; 11523 switch (PromOp.getOpcode()) { 11524 default: C = 0; break; 11525 case ISD::SELECT: C = 1; break; 11526 case ISD::SELECT_CC: C = 2; break; 11527 } 11528 11529 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11530 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11531 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11532 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11533 // The to-be-promoted operands of this node have not yet been 11534 // promoted (this should be rare because we're going through the 11535 // list backward, but if one of the operands has several users in 11536 // this cluster of to-be-promoted nodes, it is possible). 11537 PromOpHandles.emplace_front(PromOp); 11538 continue; 11539 } 11540 11541 // For SELECT and SELECT_CC nodes, we do a similar check for any 11542 // to-be-promoted comparison inputs. 11543 if (PromOp.getOpcode() == ISD::SELECT || 11544 PromOp.getOpcode() == ISD::SELECT_CC) { 11545 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11546 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11547 (SelectTruncOp[1].count(PromOp.getNode()) && 11548 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11549 PromOpHandles.emplace_front(PromOp); 11550 continue; 11551 } 11552 } 11553 11554 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11555 PromOp.getNode()->op_end()); 11556 11557 // If this node has constant inputs, then they'll need to be promoted here. 11558 for (unsigned i = 0; i < 2; ++i) { 11559 if (!isa<ConstantSDNode>(Ops[C+i])) 11560 continue; 11561 if (Ops[C+i].getValueType() == N->getValueType(0)) 11562 continue; 11563 11564 if (N->getOpcode() == ISD::SIGN_EXTEND) 11565 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11566 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11567 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11568 else 11569 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11570 } 11571 11572 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11573 // truncate them again to the original value type. 11574 if (PromOp.getOpcode() == ISD::SELECT || 11575 PromOp.getOpcode() == ISD::SELECT_CC) { 11576 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11577 if (SI0 != SelectTruncOp[0].end()) 11578 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11579 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11580 if (SI1 != SelectTruncOp[1].end()) 11581 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11582 } 11583 11584 DAG.ReplaceAllUsesOfValueWith(PromOp, 11585 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11586 } 11587 11588 // Now we're left with the initial extension itself. 11589 if (!ReallyNeedsExt) 11590 return N->getOperand(0); 11591 11592 // To zero extend, just mask off everything except for the first bit (in the 11593 // i1 case). 11594 if (N->getOpcode() == ISD::ZERO_EXTEND) 11595 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11596 DAG.getConstant(APInt::getLowBitsSet( 11597 N->getValueSizeInBits(0), PromBits), 11598 dl, N->getValueType(0))); 11599 11600 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11601 "Invalid extension type"); 11602 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11603 SDValue ShiftCst = 11604 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11605 return DAG.getNode( 11606 ISD::SRA, dl, N->getValueType(0), 11607 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11608 ShiftCst); 11609 } 11610 11611 /// \brief Reduces the number of fp-to-int conversion when building a vector. 11612 /// 11613 /// If this vector is built out of floating to integer conversions, 11614 /// transform it to a vector built out of floating point values followed by a 11615 /// single floating to integer conversion of the vector. 11616 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11617 /// becomes (fptosi (build_vector ($A, $B, ...))) 11618 SDValue PPCTargetLowering:: 11619 combineElementTruncationToVectorTruncation(SDNode *N, 11620 DAGCombinerInfo &DCI) const { 11621 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11622 "Should be called with a BUILD_VECTOR node"); 11623 11624 SelectionDAG &DAG = DCI.DAG; 11625 SDLoc dl(N); 11626 11627 SDValue FirstInput = N->getOperand(0); 11628 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11629 "The input operand must be an fp-to-int conversion."); 11630 11631 // This combine happens after legalization so the fp_to_[su]i nodes are 11632 // already converted to PPCSISD nodes. 11633 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11634 if (FirstConversion == PPCISD::FCTIDZ || 11635 FirstConversion == PPCISD::FCTIDUZ || 11636 FirstConversion == PPCISD::FCTIWZ || 11637 FirstConversion == PPCISD::FCTIWUZ) { 11638 bool IsSplat = true; 11639 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11640 FirstConversion == PPCISD::FCTIWUZ; 11641 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11642 SmallVector<SDValue, 4> Ops; 11643 EVT TargetVT = N->getValueType(0); 11644 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11645 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11646 return SDValue(); 11647 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11648 if (NextConversion != FirstConversion) 11649 return SDValue(); 11650 if (N->getOperand(i) != FirstInput) 11651 IsSplat = false; 11652 } 11653 11654 // If this is a splat, we leave it as-is since there will be only a single 11655 // fp-to-int conversion followed by a splat of the integer. This is better 11656 // for 32-bit and smaller ints and neutral for 64-bit ints. 11657 if (IsSplat) 11658 return SDValue(); 11659 11660 // Now that we know we have the right type of node, get its operands 11661 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11662 SDValue In = N->getOperand(i).getOperand(0); 11663 // For 32-bit values, we need to add an FP_ROUND node. 11664 if (Is32Bit) { 11665 if (In.isUndef()) 11666 Ops.push_back(DAG.getUNDEF(SrcVT)); 11667 else { 11668 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11669 MVT::f32, In.getOperand(0), 11670 DAG.getIntPtrConstant(1, dl)); 11671 Ops.push_back(Trunc); 11672 } 11673 } else 11674 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11675 } 11676 11677 unsigned Opcode; 11678 if (FirstConversion == PPCISD::FCTIDZ || 11679 FirstConversion == PPCISD::FCTIWZ) 11680 Opcode = ISD::FP_TO_SINT; 11681 else 11682 Opcode = ISD::FP_TO_UINT; 11683 11684 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11685 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11686 return DAG.getNode(Opcode, dl, TargetVT, BV); 11687 } 11688 return SDValue(); 11689 } 11690 11691 /// \brief Reduce the number of loads when building a vector. 11692 /// 11693 /// Building a vector out of multiple loads can be converted to a load 11694 /// of the vector type if the loads are consecutive. If the loads are 11695 /// consecutive but in descending order, a shuffle is added at the end 11696 /// to reorder the vector. 11697 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11698 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11699 "Should be called with a BUILD_VECTOR node"); 11700 11701 SDLoc dl(N); 11702 bool InputsAreConsecutiveLoads = true; 11703 bool InputsAreReverseConsecutive = true; 11704 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11705 SDValue FirstInput = N->getOperand(0); 11706 bool IsRoundOfExtLoad = false; 11707 11708 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11709 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11710 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11711 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11712 } 11713 // Not a build vector of (possibly fp_rounded) loads. 11714 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11715 return SDValue(); 11716 11717 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11718 // If any inputs are fp_round(extload), they all must be. 11719 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11720 return SDValue(); 11721 11722 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11723 N->getOperand(i); 11724 if (NextInput.getOpcode() != ISD::LOAD) 11725 return SDValue(); 11726 11727 SDValue PreviousInput = 11728 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11729 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11730 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11731 11732 // If any inputs are fp_round(extload), they all must be. 11733 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11734 return SDValue(); 11735 11736 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11737 InputsAreConsecutiveLoads = false; 11738 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11739 InputsAreReverseConsecutive = false; 11740 11741 // Exit early if the loads are neither consecutive nor reverse consecutive. 11742 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11743 return SDValue(); 11744 } 11745 11746 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11747 "The loads cannot be both consecutive and reverse consecutive."); 11748 11749 SDValue FirstLoadOp = 11750 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11751 SDValue LastLoadOp = 11752 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11753 N->getOperand(N->getNumOperands()-1); 11754 11755 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11756 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11757 if (InputsAreConsecutiveLoads) { 11758 assert(LD1 && "Input needs to be a LoadSDNode."); 11759 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11760 LD1->getBasePtr(), LD1->getPointerInfo(), 11761 LD1->getAlignment()); 11762 } 11763 if (InputsAreReverseConsecutive) { 11764 assert(LDL && "Input needs to be a LoadSDNode."); 11765 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11766 LDL->getBasePtr(), LDL->getPointerInfo(), 11767 LDL->getAlignment()); 11768 SmallVector<int, 16> Ops; 11769 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11770 Ops.push_back(i); 11771 11772 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11773 DAG.getUNDEF(N->getValueType(0)), Ops); 11774 } 11775 return SDValue(); 11776 } 11777 11778 // This function adds the required vector_shuffle needed to get 11779 // the elements of the vector extract in the correct position 11780 // as specified by the CorrectElems encoding. 11781 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11782 SDValue Input, uint64_t Elems, 11783 uint64_t CorrectElems) { 11784 SDLoc dl(N); 11785 11786 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11787 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11788 11789 // Knowing the element indices being extracted from the original 11790 // vector and the order in which they're being inserted, just put 11791 // them at element indices required for the instruction. 11792 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11793 if (DAG.getDataLayout().isLittleEndian()) 11794 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11795 else 11796 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11797 CorrectElems = CorrectElems >> 8; 11798 Elems = Elems >> 8; 11799 } 11800 11801 SDValue Shuffle = 11802 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11803 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11804 11805 EVT Ty = N->getValueType(0); 11806 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11807 return BV; 11808 } 11809 11810 // Look for build vector patterns where input operands come from sign 11811 // extended vector_extract elements of specific indices. If the correct indices 11812 // aren't used, add a vector shuffle to fix up the indices and create a new 11813 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11814 // during instruction selection. 11815 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11816 // This array encodes the indices that the vector sign extend instructions 11817 // extract from when extending from one type to another for both BE and LE. 11818 // The right nibble of each byte corresponds to the LE incides. 11819 // and the left nibble of each byte corresponds to the BE incides. 11820 // For example: 0x3074B8FC byte->word 11821 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11822 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11823 // For example: 0x000070F8 byte->double word 11824 // For LE: the allowed indices are: 0x0,0x8 11825 // For BE: the allowed indices are: 0x7,0xF 11826 uint64_t TargetElems[] = { 11827 0x3074B8FC, // b->w 11828 0x000070F8, // b->d 11829 0x10325476, // h->w 11830 0x00003074, // h->d 11831 0x00001032, // w->d 11832 }; 11833 11834 uint64_t Elems = 0; 11835 int Index; 11836 SDValue Input; 11837 11838 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11839 if (!Op) 11840 return false; 11841 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11842 return false; 11843 11844 SDValue Extract = Op.getOperand(0); 11845 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11846 return false; 11847 11848 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11849 if (!ExtOp) 11850 return false; 11851 11852 Index = ExtOp->getZExtValue(); 11853 if (Input && Input != Extract.getOperand(0)) 11854 return false; 11855 11856 if (!Input) 11857 Input = Extract.getOperand(0); 11858 11859 Elems = Elems << 8; 11860 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11861 Elems |= Index; 11862 11863 return true; 11864 }; 11865 11866 // If the build vector operands aren't sign extended vector extracts, 11867 // of the same input vector, then return. 11868 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11869 if (!isSExtOfVecExtract(N->getOperand(i))) { 11870 return SDValue(); 11871 } 11872 } 11873 11874 // If the vector extract indicies are not correct, add the appropriate 11875 // vector_shuffle. 11876 int TgtElemArrayIdx; 11877 int InputSize = Input.getValueType().getScalarSizeInBits(); 11878 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11879 if (InputSize + OutputSize == 40) 11880 TgtElemArrayIdx = 0; 11881 else if (InputSize + OutputSize == 72) 11882 TgtElemArrayIdx = 1; 11883 else if (InputSize + OutputSize == 48) 11884 TgtElemArrayIdx = 2; 11885 else if (InputSize + OutputSize == 80) 11886 TgtElemArrayIdx = 3; 11887 else if (InputSize + OutputSize == 96) 11888 TgtElemArrayIdx = 4; 11889 else 11890 return SDValue(); 11891 11892 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11893 CorrectElems = DAG.getDataLayout().isLittleEndian() 11894 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11895 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11896 if (Elems != CorrectElems) { 11897 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11898 } 11899 11900 // Regular lowering will catch cases where a shuffle is not needed. 11901 return SDValue(); 11902 } 11903 11904 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11905 DAGCombinerInfo &DCI) const { 11906 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11907 "Should be called with a BUILD_VECTOR node"); 11908 11909 SelectionDAG &DAG = DCI.DAG; 11910 SDLoc dl(N); 11911 11912 if (!Subtarget.hasVSX()) 11913 return SDValue(); 11914 11915 // The target independent DAG combiner will leave a build_vector of 11916 // float-to-int conversions intact. We can generate MUCH better code for 11917 // a float-to-int conversion of a vector of floats. 11918 SDValue FirstInput = N->getOperand(0); 11919 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11920 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11921 if (Reduced) 11922 return Reduced; 11923 } 11924 11925 // If we're building a vector out of consecutive loads, just load that 11926 // vector type. 11927 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11928 if (Reduced) 11929 return Reduced; 11930 11931 // If we're building a vector out of extended elements from another vector 11932 // we have P9 vector integer extend instructions. 11933 if (Subtarget.hasP9Altivec()) { 11934 Reduced = combineBVOfVecSExt(N, DAG); 11935 if (Reduced) 11936 return Reduced; 11937 } 11938 11939 11940 if (N->getValueType(0) != MVT::v2f64) 11941 return SDValue(); 11942 11943 // Looking for: 11944 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11945 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11946 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11947 return SDValue(); 11948 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11949 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11950 return SDValue(); 11951 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11952 return SDValue(); 11953 11954 SDValue Ext1 = FirstInput.getOperand(0); 11955 SDValue Ext2 = N->getOperand(1).getOperand(0); 11956 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11957 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11958 return SDValue(); 11959 11960 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11961 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11962 if (!Ext1Op || !Ext2Op) 11963 return SDValue(); 11964 if (Ext1.getValueType() != MVT::i32 || 11965 Ext2.getValueType() != MVT::i32) 11966 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11967 return SDValue(); 11968 11969 int FirstElem = Ext1Op->getZExtValue(); 11970 int SecondElem = Ext2Op->getZExtValue(); 11971 int SubvecIdx; 11972 if (FirstElem == 0 && SecondElem == 1) 11973 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11974 else if (FirstElem == 2 && SecondElem == 3) 11975 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11976 else 11977 return SDValue(); 11978 11979 SDValue SrcVec = Ext1.getOperand(0); 11980 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11981 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11982 return DAG.getNode(NodeType, dl, MVT::v2f64, 11983 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11984 } 11985 11986 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11987 DAGCombinerInfo &DCI) const { 11988 assert((N->getOpcode() == ISD::SINT_TO_FP || 11989 N->getOpcode() == ISD::UINT_TO_FP) && 11990 "Need an int -> FP conversion node here"); 11991 11992 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11993 return SDValue(); 11994 11995 SelectionDAG &DAG = DCI.DAG; 11996 SDLoc dl(N); 11997 SDValue Op(N, 0); 11998 11999 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12000 // from the hardware. 12001 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12002 return SDValue(); 12003 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12004 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12005 return SDValue(); 12006 12007 SDValue FirstOperand(Op.getOperand(0)); 12008 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12009 (FirstOperand.getValueType() == MVT::i8 || 12010 FirstOperand.getValueType() == MVT::i16); 12011 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12012 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12013 bool DstDouble = Op.getValueType() == MVT::f64; 12014 unsigned ConvOp = Signed ? 12015 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12016 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12017 SDValue WidthConst = 12018 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12019 dl, false); 12020 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12021 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12022 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12023 DAG.getVTList(MVT::f64, MVT::Other), 12024 Ops, MVT::i8, LDN->getMemOperand()); 12025 12026 // For signed conversion, we need to sign-extend the value in the VSR 12027 if (Signed) { 12028 SDValue ExtOps[] = { Ld, WidthConst }; 12029 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12030 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12031 } else 12032 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12033 } 12034 12035 12036 // For i32 intermediate values, unfortunately, the conversion functions 12037 // leave the upper 32 bits of the value are undefined. Within the set of 12038 // scalar instructions, we have no method for zero- or sign-extending the 12039 // value. Thus, we cannot handle i32 intermediate values here. 12040 if (Op.getOperand(0).getValueType() == MVT::i32) 12041 return SDValue(); 12042 12043 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12044 "UINT_TO_FP is supported only with FPCVT"); 12045 12046 // If we have FCFIDS, then use it when converting to single-precision. 12047 // Otherwise, convert to double-precision and then round. 12048 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12049 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12050 : PPCISD::FCFIDS) 12051 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12052 : PPCISD::FCFID); 12053 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12054 ? MVT::f32 12055 : MVT::f64; 12056 12057 // If we're converting from a float, to an int, and back to a float again, 12058 // then we don't need the store/load pair at all. 12059 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12060 Subtarget.hasFPCVT()) || 12061 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12062 SDValue Src = Op.getOperand(0).getOperand(0); 12063 if (Src.getValueType() == MVT::f32) { 12064 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12065 DCI.AddToWorklist(Src.getNode()); 12066 } else if (Src.getValueType() != MVT::f64) { 12067 // Make sure that we don't pick up a ppc_fp128 source value. 12068 return SDValue(); 12069 } 12070 12071 unsigned FCTOp = 12072 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12073 PPCISD::FCTIDUZ; 12074 12075 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12076 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12077 12078 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12079 FP = DAG.getNode(ISD::FP_ROUND, dl, 12080 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12081 DCI.AddToWorklist(FP.getNode()); 12082 } 12083 12084 return FP; 12085 } 12086 12087 return SDValue(); 12088 } 12089 12090 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12091 // builtins) into loads with swaps. 12092 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12093 DAGCombinerInfo &DCI) const { 12094 SelectionDAG &DAG = DCI.DAG; 12095 SDLoc dl(N); 12096 SDValue Chain; 12097 SDValue Base; 12098 MachineMemOperand *MMO; 12099 12100 switch (N->getOpcode()) { 12101 default: 12102 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12103 case ISD::LOAD: { 12104 LoadSDNode *LD = cast<LoadSDNode>(N); 12105 Chain = LD->getChain(); 12106 Base = LD->getBasePtr(); 12107 MMO = LD->getMemOperand(); 12108 // If the MMO suggests this isn't a load of a full vector, leave 12109 // things alone. For a built-in, we have to make the change for 12110 // correctness, so if there is a size problem that will be a bug. 12111 if (MMO->getSize() < 16) 12112 return SDValue(); 12113 break; 12114 } 12115 case ISD::INTRINSIC_W_CHAIN: { 12116 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12117 Chain = Intrin->getChain(); 12118 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12119 // us what we want. Get operand 2 instead. 12120 Base = Intrin->getOperand(2); 12121 MMO = Intrin->getMemOperand(); 12122 break; 12123 } 12124 } 12125 12126 MVT VecTy = N->getValueType(0).getSimpleVT(); 12127 12128 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12129 // aligned and the type is a vector with elements up to 4 bytes 12130 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12131 && VecTy.getScalarSizeInBits() <= 32 ) { 12132 return SDValue(); 12133 } 12134 12135 SDValue LoadOps[] = { Chain, Base }; 12136 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12137 DAG.getVTList(MVT::v2f64, MVT::Other), 12138 LoadOps, MVT::v2f64, MMO); 12139 12140 DCI.AddToWorklist(Load.getNode()); 12141 Chain = Load.getValue(1); 12142 SDValue Swap = DAG.getNode( 12143 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12144 DCI.AddToWorklist(Swap.getNode()); 12145 12146 // Add a bitcast if the resulting load type doesn't match v2f64. 12147 if (VecTy != MVT::v2f64) { 12148 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12149 DCI.AddToWorklist(N.getNode()); 12150 // Package {bitcast value, swap's chain} to match Load's shape. 12151 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12152 N, Swap.getValue(1)); 12153 } 12154 12155 return Swap; 12156 } 12157 12158 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12159 // builtins) into stores with swaps. 12160 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12161 DAGCombinerInfo &DCI) const { 12162 SelectionDAG &DAG = DCI.DAG; 12163 SDLoc dl(N); 12164 SDValue Chain; 12165 SDValue Base; 12166 unsigned SrcOpnd; 12167 MachineMemOperand *MMO; 12168 12169 switch (N->getOpcode()) { 12170 default: 12171 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12172 case ISD::STORE: { 12173 StoreSDNode *ST = cast<StoreSDNode>(N); 12174 Chain = ST->getChain(); 12175 Base = ST->getBasePtr(); 12176 MMO = ST->getMemOperand(); 12177 SrcOpnd = 1; 12178 // If the MMO suggests this isn't a store of a full vector, leave 12179 // things alone. For a built-in, we have to make the change for 12180 // correctness, so if there is a size problem that will be a bug. 12181 if (MMO->getSize() < 16) 12182 return SDValue(); 12183 break; 12184 } 12185 case ISD::INTRINSIC_VOID: { 12186 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12187 Chain = Intrin->getChain(); 12188 // Intrin->getBasePtr() oddly does not get what we want. 12189 Base = Intrin->getOperand(3); 12190 MMO = Intrin->getMemOperand(); 12191 SrcOpnd = 2; 12192 break; 12193 } 12194 } 12195 12196 SDValue Src = N->getOperand(SrcOpnd); 12197 MVT VecTy = Src.getValueType().getSimpleVT(); 12198 12199 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12200 // aligned and the type is a vector with elements up to 4 bytes 12201 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12202 && VecTy.getScalarSizeInBits() <= 32 ) { 12203 return SDValue(); 12204 } 12205 12206 // All stores are done as v2f64 and possible bit cast. 12207 if (VecTy != MVT::v2f64) { 12208 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12209 DCI.AddToWorklist(Src.getNode()); 12210 } 12211 12212 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12213 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12214 DCI.AddToWorklist(Swap.getNode()); 12215 Chain = Swap.getValue(1); 12216 SDValue StoreOps[] = { Chain, Swap, Base }; 12217 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12218 DAG.getVTList(MVT::Other), 12219 StoreOps, VecTy, MMO); 12220 DCI.AddToWorklist(Store.getNode()); 12221 return Store; 12222 } 12223 12224 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12225 DAGCombinerInfo &DCI) const { 12226 SelectionDAG &DAG = DCI.DAG; 12227 SDLoc dl(N); 12228 switch (N->getOpcode()) { 12229 default: break; 12230 case ISD::SHL: 12231 return combineSHL(N, DCI); 12232 case ISD::SRA: 12233 return combineSRA(N, DCI); 12234 case ISD::SRL: 12235 return combineSRL(N, DCI); 12236 case PPCISD::SHL: 12237 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12238 return N->getOperand(0); 12239 break; 12240 case PPCISD::SRL: 12241 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12242 return N->getOperand(0); 12243 break; 12244 case PPCISD::SRA: 12245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12246 if (C->isNullValue() || // 0 >>s V -> 0. 12247 C->isAllOnesValue()) // -1 >>s V -> -1. 12248 return N->getOperand(0); 12249 } 12250 break; 12251 case ISD::SIGN_EXTEND: 12252 case ISD::ZERO_EXTEND: 12253 case ISD::ANY_EXTEND: 12254 return DAGCombineExtBoolTrunc(N, DCI); 12255 case ISD::TRUNCATE: 12256 case ISD::SETCC: 12257 case ISD::SELECT_CC: 12258 return DAGCombineTruncBoolExt(N, DCI); 12259 case ISD::SINT_TO_FP: 12260 case ISD::UINT_TO_FP: 12261 return combineFPToIntToFP(N, DCI); 12262 case ISD::STORE: { 12263 EVT Op1VT = N->getOperand(1).getValueType(); 12264 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 12265 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 12266 12267 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 12268 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 12269 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 12270 ValidTypeForStoreFltAsInt && 12271 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 12272 SDValue Val = N->getOperand(1).getOperand(0); 12273 if (Val.getValueType() == MVT::f32) { 12274 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12275 DCI.AddToWorklist(Val.getNode()); 12276 } 12277 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 12278 DCI.AddToWorklist(Val.getNode()); 12279 12280 if (Op1VT == MVT::i32) { 12281 SDValue Ops[] = { 12282 N->getOperand(0), Val, N->getOperand(2), 12283 DAG.getValueType(N->getOperand(1).getValueType()) 12284 }; 12285 12286 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 12287 DAG.getVTList(MVT::Other), Ops, 12288 cast<StoreSDNode>(N)->getMemoryVT(), 12289 cast<StoreSDNode>(N)->getMemOperand()); 12290 } else { 12291 unsigned WidthInBytes = 12292 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 12293 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 12294 12295 SDValue Ops[] = { 12296 N->getOperand(0), Val, N->getOperand(2), WidthConst, 12297 DAG.getValueType(N->getOperand(1).getValueType()) 12298 }; 12299 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 12300 DAG.getVTList(MVT::Other), Ops, 12301 cast<StoreSDNode>(N)->getMemoryVT(), 12302 cast<StoreSDNode>(N)->getMemOperand()); 12303 } 12304 12305 DCI.AddToWorklist(Val.getNode()); 12306 return Val; 12307 } 12308 12309 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12310 if (cast<StoreSDNode>(N)->isUnindexed() && 12311 N->getOperand(1).getOpcode() == ISD::BSWAP && 12312 N->getOperand(1).getNode()->hasOneUse() && 12313 (N->getOperand(1).getValueType() == MVT::i32 || 12314 N->getOperand(1).getValueType() == MVT::i16 || 12315 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12316 N->getOperand(1).getValueType() == MVT::i64))) { 12317 // STBRX can only handle simple types. 12318 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12319 if (mVT.isExtended()) 12320 break; 12321 12322 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12323 // Do an any-extend to 32-bits if this is a half-word input. 12324 if (BSwapOp.getValueType() == MVT::i16) 12325 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12326 12327 // If the type of BSWAP operand is wider than stored memory width 12328 // it need to be shifted to the right side before STBRX. 12329 if (Op1VT.bitsGT(mVT)) { 12330 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12331 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12332 DAG.getConstant(Shift, dl, MVT::i32)); 12333 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12334 if (Op1VT == MVT::i64) 12335 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12336 } 12337 12338 SDValue Ops[] = { 12339 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12340 }; 12341 return 12342 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12343 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12344 cast<StoreSDNode>(N)->getMemOperand()); 12345 } 12346 12347 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12348 // So it can increase the chance of CSE constant construction. 12349 EVT VT = N->getOperand(1).getValueType(); 12350 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12351 isa<ConstantSDNode>(N->getOperand(1)) && VT == MVT::i32) { 12352 // Need to sign-extended to 64-bits to handle negative values. 12353 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12354 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12355 MemVT.getSizeInBits()); 12356 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12357 12358 // DAG.getTruncStore() can't be used here because it doesn't accept 12359 // the general (base + offset) addressing mode. 12360 // So we use UpdateNodeOperands and setTruncatingStore instead. 12361 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12362 N->getOperand(3)); 12363 cast<StoreSDNode>(N)->setTruncatingStore(true); 12364 return SDValue(N, 0); 12365 } 12366 12367 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12368 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12369 if (VT.isSimple()) { 12370 MVT StoreVT = VT.getSimpleVT(); 12371 if (Subtarget.needsSwapsForVSXMemOps() && 12372 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12373 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12374 return expandVSXStoreForLE(N, DCI); 12375 } 12376 break; 12377 } 12378 case ISD::LOAD: { 12379 LoadSDNode *LD = cast<LoadSDNode>(N); 12380 EVT VT = LD->getValueType(0); 12381 12382 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12383 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12384 if (VT.isSimple()) { 12385 MVT LoadVT = VT.getSimpleVT(); 12386 if (Subtarget.needsSwapsForVSXMemOps() && 12387 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12388 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12389 return expandVSXLoadForLE(N, DCI); 12390 } 12391 12392 // We sometimes end up with a 64-bit integer load, from which we extract 12393 // two single-precision floating-point numbers. This happens with 12394 // std::complex<float>, and other similar structures, because of the way we 12395 // canonicalize structure copies. However, if we lack direct moves, 12396 // then the final bitcasts from the extracted integer values to the 12397 // floating-point numbers turn into store/load pairs. Even with direct moves, 12398 // just loading the two floating-point numbers is likely better. 12399 auto ReplaceTwoFloatLoad = [&]() { 12400 if (VT != MVT::i64) 12401 return false; 12402 12403 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12404 LD->isVolatile()) 12405 return false; 12406 12407 // We're looking for a sequence like this: 12408 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12409 // t16: i64 = srl t13, Constant:i32<32> 12410 // t17: i32 = truncate t16 12411 // t18: f32 = bitcast t17 12412 // t19: i32 = truncate t13 12413 // t20: f32 = bitcast t19 12414 12415 if (!LD->hasNUsesOfValue(2, 0)) 12416 return false; 12417 12418 auto UI = LD->use_begin(); 12419 while (UI.getUse().getResNo() != 0) ++UI; 12420 SDNode *Trunc = *UI++; 12421 while (UI.getUse().getResNo() != 0) ++UI; 12422 SDNode *RightShift = *UI; 12423 if (Trunc->getOpcode() != ISD::TRUNCATE) 12424 std::swap(Trunc, RightShift); 12425 12426 if (Trunc->getOpcode() != ISD::TRUNCATE || 12427 Trunc->getValueType(0) != MVT::i32 || 12428 !Trunc->hasOneUse()) 12429 return false; 12430 if (RightShift->getOpcode() != ISD::SRL || 12431 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12432 RightShift->getConstantOperandVal(1) != 32 || 12433 !RightShift->hasOneUse()) 12434 return false; 12435 12436 SDNode *Trunc2 = *RightShift->use_begin(); 12437 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12438 Trunc2->getValueType(0) != MVT::i32 || 12439 !Trunc2->hasOneUse()) 12440 return false; 12441 12442 SDNode *Bitcast = *Trunc->use_begin(); 12443 SDNode *Bitcast2 = *Trunc2->use_begin(); 12444 12445 if (Bitcast->getOpcode() != ISD::BITCAST || 12446 Bitcast->getValueType(0) != MVT::f32) 12447 return false; 12448 if (Bitcast2->getOpcode() != ISD::BITCAST || 12449 Bitcast2->getValueType(0) != MVT::f32) 12450 return false; 12451 12452 if (Subtarget.isLittleEndian()) 12453 std::swap(Bitcast, Bitcast2); 12454 12455 // Bitcast has the second float (in memory-layout order) and Bitcast2 12456 // has the first one. 12457 12458 SDValue BasePtr = LD->getBasePtr(); 12459 if (LD->isIndexed()) { 12460 assert(LD->getAddressingMode() == ISD::PRE_INC && 12461 "Non-pre-inc AM on PPC?"); 12462 BasePtr = 12463 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12464 LD->getOffset()); 12465 } 12466 12467 auto MMOFlags = 12468 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12469 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12470 LD->getPointerInfo(), LD->getAlignment(), 12471 MMOFlags, LD->getAAInfo()); 12472 SDValue AddPtr = 12473 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12474 BasePtr, DAG.getIntPtrConstant(4, dl)); 12475 SDValue FloatLoad2 = DAG.getLoad( 12476 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12477 LD->getPointerInfo().getWithOffset(4), 12478 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12479 12480 if (LD->isIndexed()) { 12481 // Note that DAGCombine should re-form any pre-increment load(s) from 12482 // what is produced here if that makes sense. 12483 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12484 } 12485 12486 DCI.CombineTo(Bitcast2, FloatLoad); 12487 DCI.CombineTo(Bitcast, FloatLoad2); 12488 12489 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12490 SDValue(FloatLoad2.getNode(), 1)); 12491 return true; 12492 }; 12493 12494 if (ReplaceTwoFloatLoad()) 12495 return SDValue(N, 0); 12496 12497 EVT MemVT = LD->getMemoryVT(); 12498 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12499 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12500 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12501 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12502 if (LD->isUnindexed() && VT.isVector() && 12503 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12504 // P8 and later hardware should just use LOAD. 12505 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12506 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12507 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12508 LD->getAlignment() >= ScalarABIAlignment)) && 12509 LD->getAlignment() < ABIAlignment) { 12510 // This is a type-legal unaligned Altivec or QPX load. 12511 SDValue Chain = LD->getChain(); 12512 SDValue Ptr = LD->getBasePtr(); 12513 bool isLittleEndian = Subtarget.isLittleEndian(); 12514 12515 // This implements the loading of unaligned vectors as described in 12516 // the venerable Apple Velocity Engine overview. Specifically: 12517 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12518 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12519 // 12520 // The general idea is to expand a sequence of one or more unaligned 12521 // loads into an alignment-based permutation-control instruction (lvsl 12522 // or lvsr), a series of regular vector loads (which always truncate 12523 // their input address to an aligned address), and a series of 12524 // permutations. The results of these permutations are the requested 12525 // loaded values. The trick is that the last "extra" load is not taken 12526 // from the address you might suspect (sizeof(vector) bytes after the 12527 // last requested load), but rather sizeof(vector) - 1 bytes after the 12528 // last requested vector. The point of this is to avoid a page fault if 12529 // the base address happened to be aligned. This works because if the 12530 // base address is aligned, then adding less than a full vector length 12531 // will cause the last vector in the sequence to be (re)loaded. 12532 // Otherwise, the next vector will be fetched as you might suspect was 12533 // necessary. 12534 12535 // We might be able to reuse the permutation generation from 12536 // a different base address offset from this one by an aligned amount. 12537 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12538 // optimization later. 12539 Intrinsic::ID Intr, IntrLD, IntrPerm; 12540 MVT PermCntlTy, PermTy, LDTy; 12541 if (Subtarget.hasAltivec()) { 12542 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12543 Intrinsic::ppc_altivec_lvsl; 12544 IntrLD = Intrinsic::ppc_altivec_lvx; 12545 IntrPerm = Intrinsic::ppc_altivec_vperm; 12546 PermCntlTy = MVT::v16i8; 12547 PermTy = MVT::v4i32; 12548 LDTy = MVT::v4i32; 12549 } else { 12550 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12551 Intrinsic::ppc_qpx_qvlpcls; 12552 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12553 Intrinsic::ppc_qpx_qvlfs; 12554 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12555 PermCntlTy = MVT::v4f64; 12556 PermTy = MVT::v4f64; 12557 LDTy = MemVT.getSimpleVT(); 12558 } 12559 12560 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12561 12562 // Create the new MMO for the new base load. It is like the original MMO, 12563 // but represents an area in memory almost twice the vector size centered 12564 // on the original address. If the address is unaligned, we might start 12565 // reading up to (sizeof(vector)-1) bytes below the address of the 12566 // original unaligned load. 12567 MachineFunction &MF = DAG.getMachineFunction(); 12568 MachineMemOperand *BaseMMO = 12569 MF.getMachineMemOperand(LD->getMemOperand(), 12570 -(long)MemVT.getStoreSize()+1, 12571 2*MemVT.getStoreSize()-1); 12572 12573 // Create the new base load. 12574 SDValue LDXIntID = 12575 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12576 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12577 SDValue BaseLoad = 12578 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12579 DAG.getVTList(PermTy, MVT::Other), 12580 BaseLoadOps, LDTy, BaseMMO); 12581 12582 // Note that the value of IncOffset (which is provided to the next 12583 // load's pointer info offset value, and thus used to calculate the 12584 // alignment), and the value of IncValue (which is actually used to 12585 // increment the pointer value) are different! This is because we 12586 // require the next load to appear to be aligned, even though it 12587 // is actually offset from the base pointer by a lesser amount. 12588 int IncOffset = VT.getSizeInBits() / 8; 12589 int IncValue = IncOffset; 12590 12591 // Walk (both up and down) the chain looking for another load at the real 12592 // (aligned) offset (the alignment of the other load does not matter in 12593 // this case). If found, then do not use the offset reduction trick, as 12594 // that will prevent the loads from being later combined (as they would 12595 // otherwise be duplicates). 12596 if (!findConsecutiveLoad(LD, DAG)) 12597 --IncValue; 12598 12599 SDValue Increment = 12600 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12601 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12602 12603 MachineMemOperand *ExtraMMO = 12604 MF.getMachineMemOperand(LD->getMemOperand(), 12605 1, 2*MemVT.getStoreSize()-1); 12606 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12607 SDValue ExtraLoad = 12608 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12609 DAG.getVTList(PermTy, MVT::Other), 12610 ExtraLoadOps, LDTy, ExtraMMO); 12611 12612 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12613 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12614 12615 // Because vperm has a big-endian bias, we must reverse the order 12616 // of the input vectors and complement the permute control vector 12617 // when generating little endian code. We have already handled the 12618 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12619 // and ExtraLoad here. 12620 SDValue Perm; 12621 if (isLittleEndian) 12622 Perm = BuildIntrinsicOp(IntrPerm, 12623 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12624 else 12625 Perm = BuildIntrinsicOp(IntrPerm, 12626 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12627 12628 if (VT != PermTy) 12629 Perm = Subtarget.hasAltivec() ? 12630 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12631 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12632 DAG.getTargetConstant(1, dl, MVT::i64)); 12633 // second argument is 1 because this rounding 12634 // is always exact. 12635 12636 // The output of the permutation is our loaded result, the TokenFactor is 12637 // our new chain. 12638 DCI.CombineTo(N, Perm, TF); 12639 return SDValue(N, 0); 12640 } 12641 } 12642 break; 12643 case ISD::INTRINSIC_WO_CHAIN: { 12644 bool isLittleEndian = Subtarget.isLittleEndian(); 12645 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12646 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12647 : Intrinsic::ppc_altivec_lvsl); 12648 if ((IID == Intr || 12649 IID == Intrinsic::ppc_qpx_qvlpcld || 12650 IID == Intrinsic::ppc_qpx_qvlpcls) && 12651 N->getOperand(1)->getOpcode() == ISD::ADD) { 12652 SDValue Add = N->getOperand(1); 12653 12654 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12655 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12656 12657 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12658 APInt::getAllOnesValue(Bits /* alignment */) 12659 .zext(Add.getScalarValueSizeInBits()))) { 12660 SDNode *BasePtr = Add->getOperand(0).getNode(); 12661 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12662 UE = BasePtr->use_end(); 12663 UI != UE; ++UI) { 12664 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12665 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12666 // We've found another LVSL/LVSR, and this address is an aligned 12667 // multiple of that one. The results will be the same, so use the 12668 // one we've just found instead. 12669 12670 return SDValue(*UI, 0); 12671 } 12672 } 12673 } 12674 12675 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12676 SDNode *BasePtr = Add->getOperand(0).getNode(); 12677 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12678 UE = BasePtr->use_end(); UI != UE; ++UI) { 12679 if (UI->getOpcode() == ISD::ADD && 12680 isa<ConstantSDNode>(UI->getOperand(1)) && 12681 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12682 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12683 (1ULL << Bits) == 0) { 12684 SDNode *OtherAdd = *UI; 12685 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12686 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12687 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12688 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12689 return SDValue(*VI, 0); 12690 } 12691 } 12692 } 12693 } 12694 } 12695 } 12696 } 12697 12698 break; 12699 case ISD::INTRINSIC_W_CHAIN: 12700 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12701 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12702 if (Subtarget.needsSwapsForVSXMemOps()) { 12703 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12704 default: 12705 break; 12706 case Intrinsic::ppc_vsx_lxvw4x: 12707 case Intrinsic::ppc_vsx_lxvd2x: 12708 return expandVSXLoadForLE(N, DCI); 12709 } 12710 } 12711 break; 12712 case ISD::INTRINSIC_VOID: 12713 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12714 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12715 if (Subtarget.needsSwapsForVSXMemOps()) { 12716 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12717 default: 12718 break; 12719 case Intrinsic::ppc_vsx_stxvw4x: 12720 case Intrinsic::ppc_vsx_stxvd2x: 12721 return expandVSXStoreForLE(N, DCI); 12722 } 12723 } 12724 break; 12725 case ISD::BSWAP: 12726 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12727 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12728 N->getOperand(0).hasOneUse() && 12729 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12730 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12731 N->getValueType(0) == MVT::i64))) { 12732 SDValue Load = N->getOperand(0); 12733 LoadSDNode *LD = cast<LoadSDNode>(Load); 12734 // Create the byte-swapping load. 12735 SDValue Ops[] = { 12736 LD->getChain(), // Chain 12737 LD->getBasePtr(), // Ptr 12738 DAG.getValueType(N->getValueType(0)) // VT 12739 }; 12740 SDValue BSLoad = 12741 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12742 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12743 MVT::i64 : MVT::i32, MVT::Other), 12744 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12745 12746 // If this is an i16 load, insert the truncate. 12747 SDValue ResVal = BSLoad; 12748 if (N->getValueType(0) == MVT::i16) 12749 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12750 12751 // First, combine the bswap away. This makes the value produced by the 12752 // load dead. 12753 DCI.CombineTo(N, ResVal); 12754 12755 // Next, combine the load away, we give it a bogus result value but a real 12756 // chain result. The result value is dead because the bswap is dead. 12757 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12758 12759 // Return N so it doesn't get rechecked! 12760 return SDValue(N, 0); 12761 } 12762 break; 12763 case PPCISD::VCMP: 12764 // If a VCMPo node already exists with exactly the same operands as this 12765 // node, use its result instead of this node (VCMPo computes both a CR6 and 12766 // a normal output). 12767 // 12768 if (!N->getOperand(0).hasOneUse() && 12769 !N->getOperand(1).hasOneUse() && 12770 !N->getOperand(2).hasOneUse()) { 12771 12772 // Scan all of the users of the LHS, looking for VCMPo's that match. 12773 SDNode *VCMPoNode = nullptr; 12774 12775 SDNode *LHSN = N->getOperand(0).getNode(); 12776 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12777 UI != E; ++UI) 12778 if (UI->getOpcode() == PPCISD::VCMPo && 12779 UI->getOperand(1) == N->getOperand(1) && 12780 UI->getOperand(2) == N->getOperand(2) && 12781 UI->getOperand(0) == N->getOperand(0)) { 12782 VCMPoNode = *UI; 12783 break; 12784 } 12785 12786 // If there is no VCMPo node, or if the flag value has a single use, don't 12787 // transform this. 12788 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12789 break; 12790 12791 // Look at the (necessarily single) use of the flag value. If it has a 12792 // chain, this transformation is more complex. Note that multiple things 12793 // could use the value result, which we should ignore. 12794 SDNode *FlagUser = nullptr; 12795 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12796 FlagUser == nullptr; ++UI) { 12797 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12798 SDNode *User = *UI; 12799 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12800 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12801 FlagUser = User; 12802 break; 12803 } 12804 } 12805 } 12806 12807 // If the user is a MFOCRF instruction, we know this is safe. 12808 // Otherwise we give up for right now. 12809 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12810 return SDValue(VCMPoNode, 0); 12811 } 12812 break; 12813 case ISD::BRCOND: { 12814 SDValue Cond = N->getOperand(1); 12815 SDValue Target = N->getOperand(2); 12816 12817 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12818 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12819 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12820 12821 // We now need to make the intrinsic dead (it cannot be instruction 12822 // selected). 12823 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12824 assert(Cond.getNode()->hasOneUse() && 12825 "Counter decrement has more than one use"); 12826 12827 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12828 N->getOperand(0), Target); 12829 } 12830 } 12831 break; 12832 case ISD::BR_CC: { 12833 // If this is a branch on an altivec predicate comparison, lower this so 12834 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12835 // lowering is done pre-legalize, because the legalizer lowers the predicate 12836 // compare down to code that is difficult to reassemble. 12837 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12838 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12839 12840 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12841 // value. If so, pass-through the AND to get to the intrinsic. 12842 if (LHS.getOpcode() == ISD::AND && 12843 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12844 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12845 Intrinsic::ppc_is_decremented_ctr_nonzero && 12846 isa<ConstantSDNode>(LHS.getOperand(1)) && 12847 !isNullConstant(LHS.getOperand(1))) 12848 LHS = LHS.getOperand(0); 12849 12850 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12851 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12852 Intrinsic::ppc_is_decremented_ctr_nonzero && 12853 isa<ConstantSDNode>(RHS)) { 12854 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12855 "Counter decrement comparison is not EQ or NE"); 12856 12857 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12858 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12859 (CC == ISD::SETNE && !Val); 12860 12861 // We now need to make the intrinsic dead (it cannot be instruction 12862 // selected). 12863 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12864 assert(LHS.getNode()->hasOneUse() && 12865 "Counter decrement has more than one use"); 12866 12867 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12868 N->getOperand(0), N->getOperand(4)); 12869 } 12870 12871 int CompareOpc; 12872 bool isDot; 12873 12874 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12875 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12876 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12877 assert(isDot && "Can't compare against a vector result!"); 12878 12879 // If this is a comparison against something other than 0/1, then we know 12880 // that the condition is never/always true. 12881 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12882 if (Val != 0 && Val != 1) { 12883 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12884 return N->getOperand(0); 12885 // Always !=, turn it into an unconditional branch. 12886 return DAG.getNode(ISD::BR, dl, MVT::Other, 12887 N->getOperand(0), N->getOperand(4)); 12888 } 12889 12890 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12891 12892 // Create the PPCISD altivec 'dot' comparison node. 12893 SDValue Ops[] = { 12894 LHS.getOperand(2), // LHS of compare 12895 LHS.getOperand(3), // RHS of compare 12896 DAG.getConstant(CompareOpc, dl, MVT::i32) 12897 }; 12898 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12899 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12900 12901 // Unpack the result based on how the target uses it. 12902 PPC::Predicate CompOpc; 12903 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12904 default: // Can't happen, don't crash on invalid number though. 12905 case 0: // Branch on the value of the EQ bit of CR6. 12906 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12907 break; 12908 case 1: // Branch on the inverted value of the EQ bit of CR6. 12909 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12910 break; 12911 case 2: // Branch on the value of the LT bit of CR6. 12912 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12913 break; 12914 case 3: // Branch on the inverted value of the LT bit of CR6. 12915 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12916 break; 12917 } 12918 12919 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12920 DAG.getConstant(CompOpc, dl, MVT::i32), 12921 DAG.getRegister(PPC::CR6, MVT::i32), 12922 N->getOperand(4), CompNode.getValue(1)); 12923 } 12924 break; 12925 } 12926 case ISD::BUILD_VECTOR: 12927 return DAGCombineBuildVector(N, DCI); 12928 } 12929 12930 return SDValue(); 12931 } 12932 12933 SDValue 12934 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12935 SelectionDAG &DAG, 12936 std::vector<SDNode *> *Created) const { 12937 // fold (sdiv X, pow2) 12938 EVT VT = N->getValueType(0); 12939 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12940 return SDValue(); 12941 if ((VT != MVT::i32 && VT != MVT::i64) || 12942 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12943 return SDValue(); 12944 12945 SDLoc DL(N); 12946 SDValue N0 = N->getOperand(0); 12947 12948 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12949 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12950 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12951 12952 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12953 if (Created) 12954 Created->push_back(Op.getNode()); 12955 12956 if (IsNegPow2) { 12957 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12958 if (Created) 12959 Created->push_back(Op.getNode()); 12960 } 12961 12962 return Op; 12963 } 12964 12965 //===----------------------------------------------------------------------===// 12966 // Inline Assembly Support 12967 //===----------------------------------------------------------------------===// 12968 12969 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12970 KnownBits &Known, 12971 const APInt &DemandedElts, 12972 const SelectionDAG &DAG, 12973 unsigned Depth) const { 12974 Known.resetAll(); 12975 switch (Op.getOpcode()) { 12976 default: break; 12977 case PPCISD::LBRX: { 12978 // lhbrx is known to have the top bits cleared out. 12979 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12980 Known.Zero = 0xFFFF0000; 12981 break; 12982 } 12983 case ISD::INTRINSIC_WO_CHAIN: { 12984 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12985 default: break; 12986 case Intrinsic::ppc_altivec_vcmpbfp_p: 12987 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12988 case Intrinsic::ppc_altivec_vcmpequb_p: 12989 case Intrinsic::ppc_altivec_vcmpequh_p: 12990 case Intrinsic::ppc_altivec_vcmpequw_p: 12991 case Intrinsic::ppc_altivec_vcmpequd_p: 12992 case Intrinsic::ppc_altivec_vcmpgefp_p: 12993 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12994 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12995 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12996 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12997 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12998 case Intrinsic::ppc_altivec_vcmpgtub_p: 12999 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13000 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13001 case Intrinsic::ppc_altivec_vcmpgtud_p: 13002 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13003 break; 13004 } 13005 } 13006 } 13007 } 13008 13009 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13010 switch (Subtarget.getDarwinDirective()) { 13011 default: break; 13012 case PPC::DIR_970: 13013 case PPC::DIR_PWR4: 13014 case PPC::DIR_PWR5: 13015 case PPC::DIR_PWR5X: 13016 case PPC::DIR_PWR6: 13017 case PPC::DIR_PWR6X: 13018 case PPC::DIR_PWR7: 13019 case PPC::DIR_PWR8: 13020 case PPC::DIR_PWR9: { 13021 if (!ML) 13022 break; 13023 13024 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13025 13026 // For small loops (between 5 and 8 instructions), align to a 32-byte 13027 // boundary so that the entire loop fits in one instruction-cache line. 13028 uint64_t LoopSize = 0; 13029 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13030 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13031 LoopSize += TII->getInstSizeInBytes(*J); 13032 if (LoopSize > 32) 13033 break; 13034 } 13035 13036 if (LoopSize > 16 && LoopSize <= 32) 13037 return 5; 13038 13039 break; 13040 } 13041 } 13042 13043 return TargetLowering::getPrefLoopAlignment(ML); 13044 } 13045 13046 /// getConstraintType - Given a constraint, return the type of 13047 /// constraint it is for this target. 13048 PPCTargetLowering::ConstraintType 13049 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13050 if (Constraint.size() == 1) { 13051 switch (Constraint[0]) { 13052 default: break; 13053 case 'b': 13054 case 'r': 13055 case 'f': 13056 case 'd': 13057 case 'v': 13058 case 'y': 13059 return C_RegisterClass; 13060 case 'Z': 13061 // FIXME: While Z does indicate a memory constraint, it specifically 13062 // indicates an r+r address (used in conjunction with the 'y' modifier 13063 // in the replacement string). Currently, we're forcing the base 13064 // register to be r0 in the asm printer (which is interpreted as zero) 13065 // and forming the complete address in the second register. This is 13066 // suboptimal. 13067 return C_Memory; 13068 } 13069 } else if (Constraint == "wc") { // individual CR bits. 13070 return C_RegisterClass; 13071 } else if (Constraint == "wa" || Constraint == "wd" || 13072 Constraint == "wf" || Constraint == "ws") { 13073 return C_RegisterClass; // VSX registers. 13074 } 13075 return TargetLowering::getConstraintType(Constraint); 13076 } 13077 13078 /// Examine constraint type and operand type and determine a weight value. 13079 /// This object must already have been set up with the operand type 13080 /// and the current alternative constraint selected. 13081 TargetLowering::ConstraintWeight 13082 PPCTargetLowering::getSingleConstraintMatchWeight( 13083 AsmOperandInfo &info, const char *constraint) const { 13084 ConstraintWeight weight = CW_Invalid; 13085 Value *CallOperandVal = info.CallOperandVal; 13086 // If we don't have a value, we can't do a match, 13087 // but allow it at the lowest weight. 13088 if (!CallOperandVal) 13089 return CW_Default; 13090 Type *type = CallOperandVal->getType(); 13091 13092 // Look at the constraint type. 13093 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13094 return CW_Register; // an individual CR bit. 13095 else if ((StringRef(constraint) == "wa" || 13096 StringRef(constraint) == "wd" || 13097 StringRef(constraint) == "wf") && 13098 type->isVectorTy()) 13099 return CW_Register; 13100 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13101 return CW_Register; 13102 13103 switch (*constraint) { 13104 default: 13105 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13106 break; 13107 case 'b': 13108 if (type->isIntegerTy()) 13109 weight = CW_Register; 13110 break; 13111 case 'f': 13112 if (type->isFloatTy()) 13113 weight = CW_Register; 13114 break; 13115 case 'd': 13116 if (type->isDoubleTy()) 13117 weight = CW_Register; 13118 break; 13119 case 'v': 13120 if (type->isVectorTy()) 13121 weight = CW_Register; 13122 break; 13123 case 'y': 13124 weight = CW_Register; 13125 break; 13126 case 'Z': 13127 weight = CW_Memory; 13128 break; 13129 } 13130 return weight; 13131 } 13132 13133 std::pair<unsigned, const TargetRegisterClass *> 13134 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13135 StringRef Constraint, 13136 MVT VT) const { 13137 if (Constraint.size() == 1) { 13138 // GCC RS6000 Constraint Letters 13139 switch (Constraint[0]) { 13140 case 'b': // R1-R31 13141 if (VT == MVT::i64 && Subtarget.isPPC64()) 13142 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13143 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13144 case 'r': // R0-R31 13145 if (VT == MVT::i64 && Subtarget.isPPC64()) 13146 return std::make_pair(0U, &PPC::G8RCRegClass); 13147 return std::make_pair(0U, &PPC::GPRCRegClass); 13148 // 'd' and 'f' constraints are both defined to be "the floating point 13149 // registers", where one is for 32-bit and the other for 64-bit. We don't 13150 // really care overly much here so just give them all the same reg classes. 13151 case 'd': 13152 case 'f': 13153 if (VT == MVT::f32 || VT == MVT::i32) 13154 return std::make_pair(0U, &PPC::F4RCRegClass); 13155 if (VT == MVT::f64 || VT == MVT::i64) 13156 return std::make_pair(0U, &PPC::F8RCRegClass); 13157 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13158 return std::make_pair(0U, &PPC::QFRCRegClass); 13159 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13160 return std::make_pair(0U, &PPC::QSRCRegClass); 13161 break; 13162 case 'v': 13163 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13164 return std::make_pair(0U, &PPC::QFRCRegClass); 13165 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13166 return std::make_pair(0U, &PPC::QSRCRegClass); 13167 if (Subtarget.hasAltivec()) 13168 return std::make_pair(0U, &PPC::VRRCRegClass); 13169 break; 13170 case 'y': // crrc 13171 return std::make_pair(0U, &PPC::CRRCRegClass); 13172 } 13173 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13174 // An individual CR bit. 13175 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13176 } else if ((Constraint == "wa" || Constraint == "wd" || 13177 Constraint == "wf") && Subtarget.hasVSX()) { 13178 return std::make_pair(0U, &PPC::VSRCRegClass); 13179 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13180 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13181 return std::make_pair(0U, &PPC::VSSRCRegClass); 13182 else 13183 return std::make_pair(0U, &PPC::VSFRCRegClass); 13184 } 13185 13186 std::pair<unsigned, const TargetRegisterClass *> R = 13187 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13188 13189 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13190 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13191 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13192 // register. 13193 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13194 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13195 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13196 PPC::GPRCRegClass.contains(R.first)) 13197 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13198 PPC::sub_32, &PPC::G8RCRegClass), 13199 &PPC::G8RCRegClass); 13200 13201 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13202 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13203 R.first = PPC::CR0; 13204 R.second = &PPC::CRRCRegClass; 13205 } 13206 13207 return R; 13208 } 13209 13210 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13211 /// vector. If it is invalid, don't add anything to Ops. 13212 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13213 std::string &Constraint, 13214 std::vector<SDValue>&Ops, 13215 SelectionDAG &DAG) const { 13216 SDValue Result; 13217 13218 // Only support length 1 constraints. 13219 if (Constraint.length() > 1) return; 13220 13221 char Letter = Constraint[0]; 13222 switch (Letter) { 13223 default: break; 13224 case 'I': 13225 case 'J': 13226 case 'K': 13227 case 'L': 13228 case 'M': 13229 case 'N': 13230 case 'O': 13231 case 'P': { 13232 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13233 if (!CST) return; // Must be an immediate to match. 13234 SDLoc dl(Op); 13235 int64_t Value = CST->getSExtValue(); 13236 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13237 // numbers are printed as such. 13238 switch (Letter) { 13239 default: llvm_unreachable("Unknown constraint letter!"); 13240 case 'I': // "I" is a signed 16-bit constant. 13241 if (isInt<16>(Value)) 13242 Result = DAG.getTargetConstant(Value, dl, TCVT); 13243 break; 13244 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13245 if (isShiftedUInt<16, 16>(Value)) 13246 Result = DAG.getTargetConstant(Value, dl, TCVT); 13247 break; 13248 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13249 if (isShiftedInt<16, 16>(Value)) 13250 Result = DAG.getTargetConstant(Value, dl, TCVT); 13251 break; 13252 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13253 if (isUInt<16>(Value)) 13254 Result = DAG.getTargetConstant(Value, dl, TCVT); 13255 break; 13256 case 'M': // "M" is a constant that is greater than 31. 13257 if (Value > 31) 13258 Result = DAG.getTargetConstant(Value, dl, TCVT); 13259 break; 13260 case 'N': // "N" is a positive constant that is an exact power of two. 13261 if (Value > 0 && isPowerOf2_64(Value)) 13262 Result = DAG.getTargetConstant(Value, dl, TCVT); 13263 break; 13264 case 'O': // "O" is the constant zero. 13265 if (Value == 0) 13266 Result = DAG.getTargetConstant(Value, dl, TCVT); 13267 break; 13268 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13269 if (isInt<16>(-Value)) 13270 Result = DAG.getTargetConstant(Value, dl, TCVT); 13271 break; 13272 } 13273 break; 13274 } 13275 } 13276 13277 if (Result.getNode()) { 13278 Ops.push_back(Result); 13279 return; 13280 } 13281 13282 // Handle standard constraint letters. 13283 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13284 } 13285 13286 // isLegalAddressingMode - Return true if the addressing mode represented 13287 // by AM is legal for this target, for a load/store of the specified type. 13288 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13289 const AddrMode &AM, Type *Ty, 13290 unsigned AS, Instruction *I) const { 13291 // PPC does not allow r+i addressing modes for vectors! 13292 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13293 return false; 13294 13295 // PPC allows a sign-extended 16-bit immediate field. 13296 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13297 return false; 13298 13299 // No global is ever allowed as a base. 13300 if (AM.BaseGV) 13301 return false; 13302 13303 // PPC only support r+r, 13304 switch (AM.Scale) { 13305 case 0: // "r+i" or just "i", depending on HasBaseReg. 13306 break; 13307 case 1: 13308 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13309 return false; 13310 // Otherwise we have r+r or r+i. 13311 break; 13312 case 2: 13313 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13314 return false; 13315 // Allow 2*r as r+r. 13316 break; 13317 default: 13318 // No other scales are supported. 13319 return false; 13320 } 13321 13322 return true; 13323 } 13324 13325 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13326 SelectionDAG &DAG) const { 13327 MachineFunction &MF = DAG.getMachineFunction(); 13328 MachineFrameInfo &MFI = MF.getFrameInfo(); 13329 MFI.setReturnAddressIsTaken(true); 13330 13331 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13332 return SDValue(); 13333 13334 SDLoc dl(Op); 13335 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13336 13337 // Make sure the function does not optimize away the store of the RA to 13338 // the stack. 13339 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13340 FuncInfo->setLRStoreRequired(); 13341 bool isPPC64 = Subtarget.isPPC64(); 13342 auto PtrVT = getPointerTy(MF.getDataLayout()); 13343 13344 if (Depth > 0) { 13345 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13346 SDValue Offset = 13347 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13348 isPPC64 ? MVT::i64 : MVT::i32); 13349 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13350 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13351 MachinePointerInfo()); 13352 } 13353 13354 // Just load the return address off the stack. 13355 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13356 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13357 MachinePointerInfo()); 13358 } 13359 13360 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13361 SelectionDAG &DAG) const { 13362 SDLoc dl(Op); 13363 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13364 13365 MachineFunction &MF = DAG.getMachineFunction(); 13366 MachineFrameInfo &MFI = MF.getFrameInfo(); 13367 MFI.setFrameAddressIsTaken(true); 13368 13369 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13370 bool isPPC64 = PtrVT == MVT::i64; 13371 13372 // Naked functions never have a frame pointer, and so we use r1. For all 13373 // other functions, this decision must be delayed until during PEI. 13374 unsigned FrameReg; 13375 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13376 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13377 else 13378 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13379 13380 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13381 PtrVT); 13382 while (Depth--) 13383 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13384 FrameAddr, MachinePointerInfo()); 13385 return FrameAddr; 13386 } 13387 13388 // FIXME? Maybe this could be a TableGen attribute on some registers and 13389 // this table could be generated automatically from RegInfo. 13390 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13391 SelectionDAG &DAG) const { 13392 bool isPPC64 = Subtarget.isPPC64(); 13393 bool isDarwinABI = Subtarget.isDarwinABI(); 13394 13395 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13396 (!isPPC64 && VT != MVT::i32)) 13397 report_fatal_error("Invalid register global variable type"); 13398 13399 bool is64Bit = isPPC64 && VT == MVT::i64; 13400 unsigned Reg = StringSwitch<unsigned>(RegName) 13401 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13402 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13403 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13404 (is64Bit ? PPC::X13 : PPC::R13)) 13405 .Default(0); 13406 13407 if (Reg) 13408 return Reg; 13409 report_fatal_error("Invalid register name global variable"); 13410 } 13411 13412 bool 13413 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13414 // The PowerPC target isn't yet aware of offsets. 13415 return false; 13416 } 13417 13418 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13419 const CallInst &I, 13420 MachineFunction &MF, 13421 unsigned Intrinsic) const { 13422 switch (Intrinsic) { 13423 case Intrinsic::ppc_qpx_qvlfd: 13424 case Intrinsic::ppc_qpx_qvlfs: 13425 case Intrinsic::ppc_qpx_qvlfcd: 13426 case Intrinsic::ppc_qpx_qvlfcs: 13427 case Intrinsic::ppc_qpx_qvlfiwa: 13428 case Intrinsic::ppc_qpx_qvlfiwz: 13429 case Intrinsic::ppc_altivec_lvx: 13430 case Intrinsic::ppc_altivec_lvxl: 13431 case Intrinsic::ppc_altivec_lvebx: 13432 case Intrinsic::ppc_altivec_lvehx: 13433 case Intrinsic::ppc_altivec_lvewx: 13434 case Intrinsic::ppc_vsx_lxvd2x: 13435 case Intrinsic::ppc_vsx_lxvw4x: { 13436 EVT VT; 13437 switch (Intrinsic) { 13438 case Intrinsic::ppc_altivec_lvebx: 13439 VT = MVT::i8; 13440 break; 13441 case Intrinsic::ppc_altivec_lvehx: 13442 VT = MVT::i16; 13443 break; 13444 case Intrinsic::ppc_altivec_lvewx: 13445 VT = MVT::i32; 13446 break; 13447 case Intrinsic::ppc_vsx_lxvd2x: 13448 VT = MVT::v2f64; 13449 break; 13450 case Intrinsic::ppc_qpx_qvlfd: 13451 VT = MVT::v4f64; 13452 break; 13453 case Intrinsic::ppc_qpx_qvlfs: 13454 VT = MVT::v4f32; 13455 break; 13456 case Intrinsic::ppc_qpx_qvlfcd: 13457 VT = MVT::v2f64; 13458 break; 13459 case Intrinsic::ppc_qpx_qvlfcs: 13460 VT = MVT::v2f32; 13461 break; 13462 default: 13463 VT = MVT::v4i32; 13464 break; 13465 } 13466 13467 Info.opc = ISD::INTRINSIC_W_CHAIN; 13468 Info.memVT = VT; 13469 Info.ptrVal = I.getArgOperand(0); 13470 Info.offset = -VT.getStoreSize()+1; 13471 Info.size = 2*VT.getStoreSize()-1; 13472 Info.align = 1; 13473 Info.flags = MachineMemOperand::MOLoad; 13474 return true; 13475 } 13476 case Intrinsic::ppc_qpx_qvlfda: 13477 case Intrinsic::ppc_qpx_qvlfsa: 13478 case Intrinsic::ppc_qpx_qvlfcda: 13479 case Intrinsic::ppc_qpx_qvlfcsa: 13480 case Intrinsic::ppc_qpx_qvlfiwaa: 13481 case Intrinsic::ppc_qpx_qvlfiwza: { 13482 EVT VT; 13483 switch (Intrinsic) { 13484 case Intrinsic::ppc_qpx_qvlfda: 13485 VT = MVT::v4f64; 13486 break; 13487 case Intrinsic::ppc_qpx_qvlfsa: 13488 VT = MVT::v4f32; 13489 break; 13490 case Intrinsic::ppc_qpx_qvlfcda: 13491 VT = MVT::v2f64; 13492 break; 13493 case Intrinsic::ppc_qpx_qvlfcsa: 13494 VT = MVT::v2f32; 13495 break; 13496 default: 13497 VT = MVT::v4i32; 13498 break; 13499 } 13500 13501 Info.opc = ISD::INTRINSIC_W_CHAIN; 13502 Info.memVT = VT; 13503 Info.ptrVal = I.getArgOperand(0); 13504 Info.offset = 0; 13505 Info.size = VT.getStoreSize(); 13506 Info.align = 1; 13507 Info.flags = MachineMemOperand::MOLoad; 13508 return true; 13509 } 13510 case Intrinsic::ppc_qpx_qvstfd: 13511 case Intrinsic::ppc_qpx_qvstfs: 13512 case Intrinsic::ppc_qpx_qvstfcd: 13513 case Intrinsic::ppc_qpx_qvstfcs: 13514 case Intrinsic::ppc_qpx_qvstfiw: 13515 case Intrinsic::ppc_altivec_stvx: 13516 case Intrinsic::ppc_altivec_stvxl: 13517 case Intrinsic::ppc_altivec_stvebx: 13518 case Intrinsic::ppc_altivec_stvehx: 13519 case Intrinsic::ppc_altivec_stvewx: 13520 case Intrinsic::ppc_vsx_stxvd2x: 13521 case Intrinsic::ppc_vsx_stxvw4x: { 13522 EVT VT; 13523 switch (Intrinsic) { 13524 case Intrinsic::ppc_altivec_stvebx: 13525 VT = MVT::i8; 13526 break; 13527 case Intrinsic::ppc_altivec_stvehx: 13528 VT = MVT::i16; 13529 break; 13530 case Intrinsic::ppc_altivec_stvewx: 13531 VT = MVT::i32; 13532 break; 13533 case Intrinsic::ppc_vsx_stxvd2x: 13534 VT = MVT::v2f64; 13535 break; 13536 case Intrinsic::ppc_qpx_qvstfd: 13537 VT = MVT::v4f64; 13538 break; 13539 case Intrinsic::ppc_qpx_qvstfs: 13540 VT = MVT::v4f32; 13541 break; 13542 case Intrinsic::ppc_qpx_qvstfcd: 13543 VT = MVT::v2f64; 13544 break; 13545 case Intrinsic::ppc_qpx_qvstfcs: 13546 VT = MVT::v2f32; 13547 break; 13548 default: 13549 VT = MVT::v4i32; 13550 break; 13551 } 13552 13553 Info.opc = ISD::INTRINSIC_VOID; 13554 Info.memVT = VT; 13555 Info.ptrVal = I.getArgOperand(1); 13556 Info.offset = -VT.getStoreSize()+1; 13557 Info.size = 2*VT.getStoreSize()-1; 13558 Info.align = 1; 13559 Info.flags = MachineMemOperand::MOStore; 13560 return true; 13561 } 13562 case Intrinsic::ppc_qpx_qvstfda: 13563 case Intrinsic::ppc_qpx_qvstfsa: 13564 case Intrinsic::ppc_qpx_qvstfcda: 13565 case Intrinsic::ppc_qpx_qvstfcsa: 13566 case Intrinsic::ppc_qpx_qvstfiwa: { 13567 EVT VT; 13568 switch (Intrinsic) { 13569 case Intrinsic::ppc_qpx_qvstfda: 13570 VT = MVT::v4f64; 13571 break; 13572 case Intrinsic::ppc_qpx_qvstfsa: 13573 VT = MVT::v4f32; 13574 break; 13575 case Intrinsic::ppc_qpx_qvstfcda: 13576 VT = MVT::v2f64; 13577 break; 13578 case Intrinsic::ppc_qpx_qvstfcsa: 13579 VT = MVT::v2f32; 13580 break; 13581 default: 13582 VT = MVT::v4i32; 13583 break; 13584 } 13585 13586 Info.opc = ISD::INTRINSIC_VOID; 13587 Info.memVT = VT; 13588 Info.ptrVal = I.getArgOperand(1); 13589 Info.offset = 0; 13590 Info.size = VT.getStoreSize(); 13591 Info.align = 1; 13592 Info.flags = MachineMemOperand::MOStore; 13593 return true; 13594 } 13595 default: 13596 break; 13597 } 13598 13599 return false; 13600 } 13601 13602 /// getOptimalMemOpType - Returns the target specific optimal type for load 13603 /// and store operations as a result of memset, memcpy, and memmove 13604 /// lowering. If DstAlign is zero that means it's safe to destination 13605 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13606 /// means there isn't a need to check it against alignment requirement, 13607 /// probably because the source does not need to be loaded. If 'IsMemset' is 13608 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13609 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13610 /// source is constant so it does not need to be loaded. 13611 /// It returns EVT::Other if the type should be determined using generic 13612 /// target-independent logic. 13613 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13614 unsigned DstAlign, unsigned SrcAlign, 13615 bool IsMemset, bool ZeroMemset, 13616 bool MemcpyStrSrc, 13617 MachineFunction &MF) const { 13618 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13619 const Function &F = MF.getFunction(); 13620 // When expanding a memset, require at least two QPX instructions to cover 13621 // the cost of loading the value to be stored from the constant pool. 13622 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13623 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13624 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13625 return MVT::v4f64; 13626 } 13627 13628 // We should use Altivec/VSX loads and stores when available. For unaligned 13629 // addresses, unaligned VSX loads are only fast starting with the P8. 13630 if (Subtarget.hasAltivec() && Size >= 16 && 13631 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13632 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13633 return MVT::v4i32; 13634 } 13635 13636 if (Subtarget.isPPC64()) { 13637 return MVT::i64; 13638 } 13639 13640 return MVT::i32; 13641 } 13642 13643 /// \brief Returns true if it is beneficial to convert a load of a constant 13644 /// to just the constant itself. 13645 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13646 Type *Ty) const { 13647 assert(Ty->isIntegerTy()); 13648 13649 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13650 return !(BitSize == 0 || BitSize > 64); 13651 } 13652 13653 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13654 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13655 return false; 13656 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13657 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13658 return NumBits1 == 64 && NumBits2 == 32; 13659 } 13660 13661 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13662 if (!VT1.isInteger() || !VT2.isInteger()) 13663 return false; 13664 unsigned NumBits1 = VT1.getSizeInBits(); 13665 unsigned NumBits2 = VT2.getSizeInBits(); 13666 return NumBits1 == 64 && NumBits2 == 32; 13667 } 13668 13669 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13670 // Generally speaking, zexts are not free, but they are free when they can be 13671 // folded with other operations. 13672 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13673 EVT MemVT = LD->getMemoryVT(); 13674 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13675 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13676 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13677 LD->getExtensionType() == ISD::ZEXTLOAD)) 13678 return true; 13679 } 13680 13681 // FIXME: Add other cases... 13682 // - 32-bit shifts with a zext to i64 13683 // - zext after ctlz, bswap, etc. 13684 // - zext after and by a constant mask 13685 13686 return TargetLowering::isZExtFree(Val, VT2); 13687 } 13688 13689 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13690 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13691 "invalid fpext types"); 13692 return true; 13693 } 13694 13695 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13696 return isInt<16>(Imm) || isUInt<16>(Imm); 13697 } 13698 13699 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13700 return isInt<16>(Imm) || isUInt<16>(Imm); 13701 } 13702 13703 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13704 unsigned, 13705 unsigned, 13706 bool *Fast) const { 13707 if (DisablePPCUnaligned) 13708 return false; 13709 13710 // PowerPC supports unaligned memory access for simple non-vector types. 13711 // Although accessing unaligned addresses is not as efficient as accessing 13712 // aligned addresses, it is generally more efficient than manual expansion, 13713 // and generally only traps for software emulation when crossing page 13714 // boundaries. 13715 13716 if (!VT.isSimple()) 13717 return false; 13718 13719 if (VT.getSimpleVT().isVector()) { 13720 if (Subtarget.hasVSX()) { 13721 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13722 VT != MVT::v4f32 && VT != MVT::v4i32) 13723 return false; 13724 } else { 13725 return false; 13726 } 13727 } 13728 13729 if (VT == MVT::ppcf128) 13730 return false; 13731 13732 if (Fast) 13733 *Fast = true; 13734 13735 return true; 13736 } 13737 13738 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13739 VT = VT.getScalarType(); 13740 13741 if (!VT.isSimple()) 13742 return false; 13743 13744 switch (VT.getSimpleVT().SimpleTy) { 13745 case MVT::f32: 13746 case MVT::f64: 13747 return true; 13748 default: 13749 break; 13750 } 13751 13752 return false; 13753 } 13754 13755 const MCPhysReg * 13756 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13757 // LR is a callee-save register, but we must treat it as clobbered by any call 13758 // site. Hence we include LR in the scratch registers, which are in turn added 13759 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13760 // to CTR, which is used by any indirect call. 13761 static const MCPhysReg ScratchRegs[] = { 13762 PPC::X12, PPC::LR8, PPC::CTR8, 0 13763 }; 13764 13765 return ScratchRegs; 13766 } 13767 13768 unsigned PPCTargetLowering::getExceptionPointerRegister( 13769 const Constant *PersonalityFn) const { 13770 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13771 } 13772 13773 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13774 const Constant *PersonalityFn) const { 13775 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13776 } 13777 13778 bool 13779 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13780 EVT VT , unsigned DefinedValues) const { 13781 if (VT == MVT::v2i64) 13782 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13783 13784 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13785 return true; 13786 13787 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13788 } 13789 13790 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13791 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13792 return TargetLowering::getSchedulingPreference(N); 13793 13794 return Sched::ILP; 13795 } 13796 13797 // Create a fast isel object. 13798 FastISel * 13799 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13800 const TargetLibraryInfo *LibInfo) const { 13801 return PPC::createFastISel(FuncInfo, LibInfo); 13802 } 13803 13804 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13805 if (Subtarget.isDarwinABI()) return; 13806 if (!Subtarget.isPPC64()) return; 13807 13808 // Update IsSplitCSR in PPCFunctionInfo 13809 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13810 PFI->setIsSplitCSR(true); 13811 } 13812 13813 void PPCTargetLowering::insertCopiesSplitCSR( 13814 MachineBasicBlock *Entry, 13815 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13816 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13817 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13818 if (!IStart) 13819 return; 13820 13821 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13822 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13823 MachineBasicBlock::iterator MBBI = Entry->begin(); 13824 for (const MCPhysReg *I = IStart; *I; ++I) { 13825 const TargetRegisterClass *RC = nullptr; 13826 if (PPC::G8RCRegClass.contains(*I)) 13827 RC = &PPC::G8RCRegClass; 13828 else if (PPC::F8RCRegClass.contains(*I)) 13829 RC = &PPC::F8RCRegClass; 13830 else if (PPC::CRRCRegClass.contains(*I)) 13831 RC = &PPC::CRRCRegClass; 13832 else if (PPC::VRRCRegClass.contains(*I)) 13833 RC = &PPC::VRRCRegClass; 13834 else 13835 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13836 13837 unsigned NewVR = MRI->createVirtualRegister(RC); 13838 // Create copy from CSR to a virtual register. 13839 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13840 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13841 // nounwind. If we want to generalize this later, we may need to emit 13842 // CFI pseudo-instructions. 13843 assert(Entry->getParent()->getFunction().hasFnAttribute( 13844 Attribute::NoUnwind) && 13845 "Function should be nounwind in insertCopiesSplitCSR!"); 13846 Entry->addLiveIn(*I); 13847 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13848 .addReg(*I); 13849 13850 // Insert the copy-back instructions right before the terminator 13851 for (auto *Exit : Exits) 13852 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13853 TII->get(TargetOpcode::COPY), *I) 13854 .addReg(NewVR); 13855 } 13856 } 13857 13858 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13859 bool PPCTargetLowering::useLoadStackGuardNode() const { 13860 if (!Subtarget.isTargetLinux()) 13861 return TargetLowering::useLoadStackGuardNode(); 13862 return true; 13863 } 13864 13865 // Override to disable global variable loading on Linux. 13866 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13867 if (!Subtarget.isTargetLinux()) 13868 return TargetLowering::insertSSPDeclarations(M); 13869 } 13870 13871 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13872 if (!VT.isSimple() || !Subtarget.hasVSX()) 13873 return false; 13874 13875 switch(VT.getSimpleVT().SimpleTy) { 13876 default: 13877 // For FP types that are currently not supported by PPC backend, return 13878 // false. Examples: f16, f80. 13879 return false; 13880 case MVT::f32: 13881 case MVT::f64: 13882 case MVT::ppcf128: 13883 return Imm.isPosZero(); 13884 } 13885 } 13886 13887 // For vector shift operation op, fold 13888 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13889 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13890 SelectionDAG &DAG) { 13891 SDValue N0 = N->getOperand(0); 13892 SDValue N1 = N->getOperand(1); 13893 EVT VT = N0.getValueType(); 13894 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13895 unsigned Opcode = N->getOpcode(); 13896 unsigned TargetOpcode; 13897 13898 switch (Opcode) { 13899 default: 13900 llvm_unreachable("Unexpected shift operation"); 13901 case ISD::SHL: 13902 TargetOpcode = PPCISD::SHL; 13903 break; 13904 case ISD::SRL: 13905 TargetOpcode = PPCISD::SRL; 13906 break; 13907 case ISD::SRA: 13908 TargetOpcode = PPCISD::SRA; 13909 break; 13910 } 13911 13912 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13913 N1->getOpcode() == ISD::AND) 13914 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13915 if (Mask->getZExtValue() == OpSizeInBits - 1) 13916 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13917 13918 return SDValue(); 13919 } 13920 13921 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13922 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13923 return Value; 13924 13925 return SDValue(); 13926 } 13927 13928 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13929 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13930 return Value; 13931 13932 return SDValue(); 13933 } 13934 13935 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13936 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13937 return Value; 13938 13939 return SDValue(); 13940 } 13941 13942 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13943 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 13944 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 13945 return false; 13946 13947 // If not a tail call then no need to proceed. 13948 if (!CI->isTailCall()) 13949 return false; 13950 13951 // If tail calls are disabled for the caller then we are done. 13952 const Function *Caller = CI->getParent()->getParent(); 13953 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 13954 if (Attr.getValueAsString() == "true") 13955 return false; 13956 13957 // If sibling calls have been disabled and tail-calls aren't guaranteed 13958 // there is no reason to duplicate. 13959 auto &TM = getTargetMachine(); 13960 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 13961 return false; 13962 13963 // Can't tail call a function called indirectly, or if it has variadic args. 13964 const Function *Callee = CI->getCalledFunction(); 13965 if (!Callee || Callee->isVarArg()) 13966 return false; 13967 13968 // Make sure the callee and caller calling conventions are eligible for tco. 13969 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 13970 CI->getCallingConv())) 13971 return false; 13972 13973 // If the function is local then we have a good chance at tail-calling it 13974 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 13975 } 13976