1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 } else { 238 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 242 } 243 244 // PowerPC does not support direct load/store of condition registers. 245 setOperationAction(ISD::LOAD, MVT::i1, Custom); 246 setOperationAction(ISD::STORE, MVT::i1, Custom); 247 248 // FIXME: Remove this once the ANDI glue bug is fixed: 249 if (ANDIGlueBug) 250 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 251 252 for (MVT VT : MVT::integer_valuetypes()) { 253 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 254 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 255 setTruncStoreAction(VT, MVT::i1, Expand); 256 } 257 258 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 259 } 260 261 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 262 // PPC (the libcall is not available). 263 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 265 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 266 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 267 268 // We do not currently implement these libm ops for PowerPC. 269 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 270 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 271 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 272 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 273 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 274 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 275 276 // PowerPC has no SREM/UREM instructions unless we are on P9 277 // On P9 we may use a hardware instruction to compute the remainder. 278 // When the result of both the remainder and the division is required it is 279 // more efficient to compute the remainder from the result of the division 280 // rather than use the remainder instruction. The instructions are legalized 281 // directly because the DivRemPairsPass performs the transformation at the IR 282 // level. 283 if (Subtarget.isISA3_0()) { 284 setOperationAction(ISD::SREM, MVT::i32, Legal); 285 setOperationAction(ISD::UREM, MVT::i32, Legal); 286 setOperationAction(ISD::SREM, MVT::i64, Legal); 287 setOperationAction(ISD::UREM, MVT::i64, Legal); 288 } else { 289 setOperationAction(ISD::SREM, MVT::i32, Expand); 290 setOperationAction(ISD::UREM, MVT::i32, Expand); 291 setOperationAction(ISD::SREM, MVT::i64, Expand); 292 setOperationAction(ISD::UREM, MVT::i64, Expand); 293 } 294 295 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 296 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 297 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 298 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 299 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 300 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 301 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 302 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 303 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 304 305 // Handle constrained floating-point operations of scalar. 306 // TODO: Handle SPE specific operation. 307 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 309 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 310 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 311 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 312 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 313 314 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 315 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 316 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 317 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 319 if (Subtarget.hasVSX()) 320 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 321 322 if (Subtarget.hasFSQRT()) { 323 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 324 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 325 } 326 327 if (Subtarget.hasFPRND()) { 328 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 329 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 330 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 331 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 332 333 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 334 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 335 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 336 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 337 } 338 339 // We don't support sin/cos/sqrt/fmod/pow 340 setOperationAction(ISD::FSIN , MVT::f64, Expand); 341 setOperationAction(ISD::FCOS , MVT::f64, Expand); 342 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 343 setOperationAction(ISD::FREM , MVT::f64, Expand); 344 setOperationAction(ISD::FPOW , MVT::f64, Expand); 345 setOperationAction(ISD::FSIN , MVT::f32, Expand); 346 setOperationAction(ISD::FCOS , MVT::f32, Expand); 347 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 348 setOperationAction(ISD::FREM , MVT::f32, Expand); 349 setOperationAction(ISD::FPOW , MVT::f32, Expand); 350 if (Subtarget.hasSPE()) { 351 setOperationAction(ISD::FMA , MVT::f64, Expand); 352 setOperationAction(ISD::FMA , MVT::f32, Expand); 353 } else { 354 setOperationAction(ISD::FMA , MVT::f64, Legal); 355 setOperationAction(ISD::FMA , MVT::f32, Legal); 356 } 357 358 if (Subtarget.hasSPE()) 359 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 360 361 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 362 363 // If we're enabling GP optimizations, use hardware square root 364 if (!Subtarget.hasFSQRT() && 365 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 366 Subtarget.hasFRE())) 367 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 368 369 if (!Subtarget.hasFSQRT() && 370 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 371 Subtarget.hasFRES())) 372 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 373 374 if (Subtarget.hasFCPSGN()) { 375 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 376 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 377 } else { 378 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 379 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 380 } 381 382 if (Subtarget.hasFPRND()) { 383 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 384 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 385 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 386 setOperationAction(ISD::FROUND, MVT::f64, Legal); 387 388 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 389 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 390 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 391 setOperationAction(ISD::FROUND, MVT::f32, Legal); 392 } 393 394 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 395 // to speed up scalar BSWAP64. 396 // CTPOP or CTTZ were introduced in P8/P9 respectively 397 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 398 if (Subtarget.hasP9Vector()) 399 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 400 else 401 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 402 if (Subtarget.isISA3_0()) { 403 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 404 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 405 } else { 406 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 407 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 408 } 409 410 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 411 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 412 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 413 } else { 414 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 415 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 416 } 417 418 // PowerPC does not have ROTR 419 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 420 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 421 422 if (!Subtarget.useCRBits()) { 423 // PowerPC does not have Select 424 setOperationAction(ISD::SELECT, MVT::i32, Expand); 425 setOperationAction(ISD::SELECT, MVT::i64, Expand); 426 setOperationAction(ISD::SELECT, MVT::f32, Expand); 427 setOperationAction(ISD::SELECT, MVT::f64, Expand); 428 } 429 430 // PowerPC wants to turn select_cc of FP into fsel when possible. 431 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 432 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 433 434 // PowerPC wants to optimize integer setcc a bit 435 if (!Subtarget.useCRBits()) 436 setOperationAction(ISD::SETCC, MVT::i32, Custom); 437 438 if (Subtarget.hasFPU()) { 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 440 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 441 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 442 443 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 444 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 445 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 446 } 447 448 // PowerPC does not have BRCOND which requires SetCC 449 if (!Subtarget.useCRBits()) 450 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 451 452 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 453 454 if (Subtarget.hasSPE()) { 455 // SPE has built-in conversions 456 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 457 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 458 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 459 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 460 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 461 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 462 } else { 463 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 464 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 465 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 466 467 // PowerPC does not have [U|S]INT_TO_FP 468 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 469 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 470 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 471 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 472 } 473 474 if (Subtarget.hasDirectMove() && isPPC64) { 475 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 476 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 477 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 478 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 479 if (TM.Options.UnsafeFPMath) { 480 setOperationAction(ISD::LRINT, MVT::f64, Legal); 481 setOperationAction(ISD::LRINT, MVT::f32, Legal); 482 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 483 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 484 setOperationAction(ISD::LROUND, MVT::f64, Legal); 485 setOperationAction(ISD::LROUND, MVT::f32, Legal); 486 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 487 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 488 } 489 } else { 490 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 491 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 492 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 493 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 494 } 495 496 // We cannot sextinreg(i1). Expand to shifts. 497 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 498 499 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 500 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 501 // support continuation, user-level threading, and etc.. As a result, no 502 // other SjLj exception interfaces are implemented and please don't build 503 // your own exception handling based on them. 504 // LLVM/Clang supports zero-cost DWARF exception handling. 505 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 506 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 507 508 // We want to legalize GlobalAddress and ConstantPool nodes into the 509 // appropriate instructions to materialize the address. 510 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 511 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 512 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 513 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 514 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 515 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 516 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 517 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 518 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 519 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 520 521 // TRAP is legal. 522 setOperationAction(ISD::TRAP, MVT::Other, Legal); 523 524 // TRAMPOLINE is custom lowered. 525 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 526 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 527 528 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 529 setOperationAction(ISD::VASTART , MVT::Other, Custom); 530 531 if (Subtarget.is64BitELFABI()) { 532 // VAARG always uses double-word chunks, so promote anything smaller. 533 setOperationAction(ISD::VAARG, MVT::i1, Promote); 534 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 535 setOperationAction(ISD::VAARG, MVT::i8, Promote); 536 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 537 setOperationAction(ISD::VAARG, MVT::i16, Promote); 538 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 539 setOperationAction(ISD::VAARG, MVT::i32, Promote); 540 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 541 setOperationAction(ISD::VAARG, MVT::Other, Expand); 542 } else if (Subtarget.is32BitELFABI()) { 543 // VAARG is custom lowered with the 32-bit SVR4 ABI. 544 setOperationAction(ISD::VAARG, MVT::Other, Custom); 545 setOperationAction(ISD::VAARG, MVT::i64, Custom); 546 } else 547 setOperationAction(ISD::VAARG, MVT::Other, Expand); 548 549 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 550 if (Subtarget.is32BitELFABI()) 551 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 552 else 553 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 554 555 // Use the default implementation. 556 setOperationAction(ISD::VAEND , MVT::Other, Expand); 557 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 558 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 559 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 560 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 561 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 562 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 563 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 564 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 565 566 // We want to custom lower some of our intrinsics. 567 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 568 569 // To handle counter-based loop conditions. 570 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 571 572 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 573 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 574 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 575 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 576 577 // Comparisons that require checking two conditions. 578 if (Subtarget.hasSPE()) { 579 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 580 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 581 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 582 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 583 } 584 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 585 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 586 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 587 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 588 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 589 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 590 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 591 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 592 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 594 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 595 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 596 597 if (Subtarget.has64BitSupport()) { 598 // They also have instructions for converting between i64 and fp. 599 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 600 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 601 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 602 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 603 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 604 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 605 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 606 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 607 // This is just the low 32 bits of a (signed) fp->i64 conversion. 608 // We cannot do this with Promote because i64 is not a legal type. 609 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 610 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 611 612 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 613 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 614 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 615 } 616 } else { 617 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 618 if (Subtarget.hasSPE()) { 619 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 620 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 621 } else { 622 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 623 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 624 } 625 } 626 627 // With the instructions enabled under FPCVT, we can do everything. 628 if (Subtarget.hasFPCVT()) { 629 if (Subtarget.has64BitSupport()) { 630 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 631 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 632 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 633 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 634 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 635 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 636 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 637 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 638 } 639 640 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 641 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 642 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 643 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 644 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 645 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 646 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 647 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 648 } 649 650 if (Subtarget.use64BitRegs()) { 651 // 64-bit PowerPC implementations can support i64 types directly 652 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 653 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 654 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 655 // 64-bit PowerPC wants to expand i128 shifts itself. 656 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 657 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 658 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 659 } else { 660 // 32-bit PowerPC wants to expand i64 shifts itself. 661 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 662 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 663 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 664 } 665 666 // PowerPC has better expansions for funnel shifts than the generic 667 // TargetLowering::expandFunnelShift. 668 if (Subtarget.has64BitSupport()) { 669 setOperationAction(ISD::FSHL, MVT::i64, Custom); 670 setOperationAction(ISD::FSHR, MVT::i64, Custom); 671 } 672 setOperationAction(ISD::FSHL, MVT::i32, Custom); 673 setOperationAction(ISD::FSHR, MVT::i32, Custom); 674 675 if (Subtarget.hasVSX()) { 676 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 677 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 678 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 679 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 680 } 681 682 if (Subtarget.hasAltivec()) { 683 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 684 setOperationAction(ISD::SADDSAT, VT, Legal); 685 setOperationAction(ISD::SSUBSAT, VT, Legal); 686 setOperationAction(ISD::UADDSAT, VT, Legal); 687 setOperationAction(ISD::USUBSAT, VT, Legal); 688 } 689 // First set operation action for all vector types to expand. Then we 690 // will selectively turn on ones that can be effectively codegen'd. 691 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 692 // add/sub are legal for all supported vector VT's. 693 setOperationAction(ISD::ADD, VT, Legal); 694 setOperationAction(ISD::SUB, VT, Legal); 695 696 // For v2i64, these are only valid with P8Vector. This is corrected after 697 // the loop. 698 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 699 setOperationAction(ISD::SMAX, VT, Legal); 700 setOperationAction(ISD::SMIN, VT, Legal); 701 setOperationAction(ISD::UMAX, VT, Legal); 702 setOperationAction(ISD::UMIN, VT, Legal); 703 } 704 else { 705 setOperationAction(ISD::SMAX, VT, Expand); 706 setOperationAction(ISD::SMIN, VT, Expand); 707 setOperationAction(ISD::UMAX, VT, Expand); 708 setOperationAction(ISD::UMIN, VT, Expand); 709 } 710 711 if (Subtarget.hasVSX()) { 712 setOperationAction(ISD::FMAXNUM, VT, Legal); 713 setOperationAction(ISD::FMINNUM, VT, Legal); 714 } 715 716 // Vector instructions introduced in P8 717 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 718 setOperationAction(ISD::CTPOP, VT, Legal); 719 setOperationAction(ISD::CTLZ, VT, Legal); 720 } 721 else { 722 setOperationAction(ISD::CTPOP, VT, Expand); 723 setOperationAction(ISD::CTLZ, VT, Expand); 724 } 725 726 // Vector instructions introduced in P9 727 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 728 setOperationAction(ISD::CTTZ, VT, Legal); 729 else 730 setOperationAction(ISD::CTTZ, VT, Expand); 731 732 // We promote all shuffles to v16i8. 733 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 734 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 735 736 // We promote all non-typed operations to v4i32. 737 setOperationAction(ISD::AND , VT, Promote); 738 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 739 setOperationAction(ISD::OR , VT, Promote); 740 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 741 setOperationAction(ISD::XOR , VT, Promote); 742 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 743 setOperationAction(ISD::LOAD , VT, Promote); 744 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 745 setOperationAction(ISD::SELECT, VT, Promote); 746 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 747 setOperationAction(ISD::VSELECT, VT, Legal); 748 setOperationAction(ISD::SELECT_CC, VT, Promote); 749 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 750 setOperationAction(ISD::STORE, VT, Promote); 751 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 752 753 // No other operations are legal. 754 setOperationAction(ISD::MUL , VT, Expand); 755 setOperationAction(ISD::SDIV, VT, Expand); 756 setOperationAction(ISD::SREM, VT, Expand); 757 setOperationAction(ISD::UDIV, VT, Expand); 758 setOperationAction(ISD::UREM, VT, Expand); 759 setOperationAction(ISD::FDIV, VT, Expand); 760 setOperationAction(ISD::FREM, VT, Expand); 761 setOperationAction(ISD::FNEG, VT, Expand); 762 setOperationAction(ISD::FSQRT, VT, Expand); 763 setOperationAction(ISD::FLOG, VT, Expand); 764 setOperationAction(ISD::FLOG10, VT, Expand); 765 setOperationAction(ISD::FLOG2, VT, Expand); 766 setOperationAction(ISD::FEXP, VT, Expand); 767 setOperationAction(ISD::FEXP2, VT, Expand); 768 setOperationAction(ISD::FSIN, VT, Expand); 769 setOperationAction(ISD::FCOS, VT, Expand); 770 setOperationAction(ISD::FABS, VT, Expand); 771 setOperationAction(ISD::FFLOOR, VT, Expand); 772 setOperationAction(ISD::FCEIL, VT, Expand); 773 setOperationAction(ISD::FTRUNC, VT, Expand); 774 setOperationAction(ISD::FRINT, VT, Expand); 775 setOperationAction(ISD::FNEARBYINT, VT, Expand); 776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 777 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 778 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 779 setOperationAction(ISD::MULHU, VT, Expand); 780 setOperationAction(ISD::MULHS, VT, Expand); 781 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 782 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 783 setOperationAction(ISD::UDIVREM, VT, Expand); 784 setOperationAction(ISD::SDIVREM, VT, Expand); 785 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 786 setOperationAction(ISD::FPOW, VT, Expand); 787 setOperationAction(ISD::BSWAP, VT, Expand); 788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 789 setOperationAction(ISD::ROTL, VT, Expand); 790 setOperationAction(ISD::ROTR, VT, Expand); 791 792 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 793 setTruncStoreAction(VT, InnerVT, Expand); 794 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 795 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 796 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 797 } 798 } 799 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 800 if (!Subtarget.hasP8Vector()) { 801 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 802 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 803 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 804 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 805 } 806 807 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 808 setOperationAction(ISD::ABS, VT, Custom); 809 810 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 811 // with merges, splats, etc. 812 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 813 814 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 815 // are cheap, so handle them before they get expanded to scalar. 816 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 817 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 818 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 819 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 820 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 821 822 setOperationAction(ISD::AND , MVT::v4i32, Legal); 823 setOperationAction(ISD::OR , MVT::v4i32, Legal); 824 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 825 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 826 setOperationAction(ISD::SELECT, MVT::v4i32, 827 Subtarget.useCRBits() ? Legal : Expand); 828 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 829 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 830 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 831 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 832 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 833 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 834 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 835 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 836 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 837 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 838 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 839 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 840 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 841 842 // Without hasP8Altivec set, v2i64 SMAX isn't available. 843 // But ABS custom lowering requires SMAX support. 844 if (!Subtarget.hasP8Altivec()) 845 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 846 847 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 848 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 849 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 850 if (Subtarget.hasAltivec()) 851 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 852 setOperationAction(ISD::ROTL, VT, Legal); 853 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 854 if (Subtarget.hasP8Altivec()) 855 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 856 857 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 858 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 859 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 860 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 861 862 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 863 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 864 865 if (Subtarget.hasVSX()) { 866 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 867 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 868 } 869 870 if (Subtarget.hasP8Altivec()) 871 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 872 else 873 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 874 875 if (Subtarget.isISA3_1()) { 876 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 877 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 878 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 879 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 880 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 881 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 882 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 883 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 884 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 885 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 886 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 887 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 888 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 889 } 890 891 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 892 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 893 894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 896 897 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 898 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 900 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 901 902 // Altivec does not contain unordered floating-point compare instructions 903 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 904 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 905 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 906 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 907 908 if (Subtarget.hasVSX()) { 909 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 911 if (Subtarget.hasP8Vector()) { 912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 914 } 915 if (Subtarget.hasDirectMove() && isPPC64) { 916 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 917 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 918 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 919 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 920 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 924 } 925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 926 927 // The nearbyint variants are not allowed to raise the inexact exception 928 // so we can only code-gen them with unsafe math. 929 if (TM.Options.UnsafeFPMath) { 930 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 931 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 932 } 933 934 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 935 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 936 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 937 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 938 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 939 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 940 setOperationAction(ISD::FROUND, MVT::f64, Legal); 941 setOperationAction(ISD::FRINT, MVT::f64, Legal); 942 943 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 944 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 945 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 946 setOperationAction(ISD::FROUND, MVT::f32, Legal); 947 setOperationAction(ISD::FRINT, MVT::f32, Legal); 948 949 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 950 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 951 952 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 953 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 954 955 // Share the Altivec comparison restrictions. 956 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 957 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 958 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 959 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 960 961 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 962 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 963 964 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 965 966 if (Subtarget.hasP8Vector()) 967 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 968 969 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 970 971 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 972 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 973 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 974 975 if (Subtarget.hasP8Altivec()) { 976 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 977 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 978 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 979 980 // 128 bit shifts can be accomplished via 3 instructions for SHL and 981 // SRL, but not for SRA because of the instructions available: 982 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 983 // doing 984 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 985 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 986 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 987 988 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 989 } 990 else { 991 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 992 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 993 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 994 995 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 996 997 // VSX v2i64 only supports non-arithmetic operations. 998 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 999 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1000 } 1001 1002 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1003 1004 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1005 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1006 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1007 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1008 1009 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1010 1011 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1012 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1013 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1014 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1015 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1016 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1017 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1018 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1019 1020 // Custom handling for partial vectors of integers converted to 1021 // floating point. We already have optimal handling for v2i32 through 1022 // the DAG combine, so those aren't necessary. 1023 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1024 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1025 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1026 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1027 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1028 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1029 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1030 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1031 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1032 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1035 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1036 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1037 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1038 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1039 1040 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1041 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1042 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1043 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1044 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1046 1047 if (Subtarget.hasDirectMove()) 1048 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1049 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1050 1051 // Handle constrained floating-point operations of vector. 1052 // The predictor is `hasVSX` because altivec instruction has 1053 // no exception but VSX vector instruction has. 1054 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1055 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1056 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1057 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1058 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1059 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1060 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1061 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1062 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 1063 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1064 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1065 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1066 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1067 1068 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1069 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1070 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1071 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1072 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1073 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1074 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1075 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1076 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1077 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1078 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1079 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1080 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1081 1082 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1083 } 1084 1085 if (Subtarget.hasP8Altivec()) { 1086 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1087 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1088 } 1089 1090 if (Subtarget.hasP9Vector()) { 1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1093 1094 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1095 // SRL, but not for SRA because of the instructions available: 1096 // VS{RL} and VS{RL}O. 1097 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1098 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1099 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1100 1101 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1102 setOperationAction(ISD::FADD, MVT::f128, Legal); 1103 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1104 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1105 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1106 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1107 // No extending loads to f128 on PPC. 1108 for (MVT FPT : MVT::fp_valuetypes()) 1109 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1110 setOperationAction(ISD::FMA, MVT::f128, Legal); 1111 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1112 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1113 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1114 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1115 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1116 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1117 1118 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1119 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1120 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1121 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1122 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1123 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1124 1125 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1126 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1127 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1128 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1129 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1130 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1131 // No implementation for these ops for PowerPC. 1132 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1133 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1134 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1135 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1136 setOperationAction(ISD::FREM, MVT::f128, Expand); 1137 1138 // Handle constrained floating-point operations of fp128 1139 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1140 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1141 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1142 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1143 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1144 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1145 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1146 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1147 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1148 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1149 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1150 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1151 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1152 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1153 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1154 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1155 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1156 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1157 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1158 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1159 } 1160 1161 if (Subtarget.hasP9Altivec()) { 1162 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1163 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1164 1165 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1166 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1168 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1169 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1170 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1171 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1172 } 1173 } 1174 1175 if (Subtarget.has64BitSupport()) 1176 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1177 1178 if (Subtarget.isISA3_1()) 1179 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1180 1181 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1182 1183 if (!isPPC64) { 1184 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1185 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1186 } 1187 1188 setBooleanContents(ZeroOrOneBooleanContent); 1189 1190 if (Subtarget.hasAltivec()) { 1191 // Altivec instructions set fields to all zeros or all ones. 1192 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1193 } 1194 1195 if (!isPPC64) { 1196 // These libcalls are not available in 32-bit. 1197 setLibcallName(RTLIB::SHL_I128, nullptr); 1198 setLibcallName(RTLIB::SRL_I128, nullptr); 1199 setLibcallName(RTLIB::SRA_I128, nullptr); 1200 } 1201 1202 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1203 1204 // We have target-specific dag combine patterns for the following nodes: 1205 setTargetDAGCombine(ISD::ADD); 1206 setTargetDAGCombine(ISD::SHL); 1207 setTargetDAGCombine(ISD::SRA); 1208 setTargetDAGCombine(ISD::SRL); 1209 setTargetDAGCombine(ISD::MUL); 1210 setTargetDAGCombine(ISD::FMA); 1211 setTargetDAGCombine(ISD::SINT_TO_FP); 1212 setTargetDAGCombine(ISD::BUILD_VECTOR); 1213 if (Subtarget.hasFPCVT()) 1214 setTargetDAGCombine(ISD::UINT_TO_FP); 1215 setTargetDAGCombine(ISD::LOAD); 1216 setTargetDAGCombine(ISD::STORE); 1217 setTargetDAGCombine(ISD::BR_CC); 1218 if (Subtarget.useCRBits()) 1219 setTargetDAGCombine(ISD::BRCOND); 1220 setTargetDAGCombine(ISD::BSWAP); 1221 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1222 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1223 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1224 1225 setTargetDAGCombine(ISD::SIGN_EXTEND); 1226 setTargetDAGCombine(ISD::ZERO_EXTEND); 1227 setTargetDAGCombine(ISD::ANY_EXTEND); 1228 1229 setTargetDAGCombine(ISD::TRUNCATE); 1230 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1231 1232 1233 if (Subtarget.useCRBits()) { 1234 setTargetDAGCombine(ISD::TRUNCATE); 1235 setTargetDAGCombine(ISD::SETCC); 1236 setTargetDAGCombine(ISD::SELECT_CC); 1237 } 1238 1239 if (Subtarget.hasP9Altivec()) { 1240 setTargetDAGCombine(ISD::ABS); 1241 setTargetDAGCombine(ISD::VSELECT); 1242 } 1243 1244 setLibcallName(RTLIB::LOG_F128, "logf128"); 1245 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1246 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1247 setLibcallName(RTLIB::EXP_F128, "expf128"); 1248 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1249 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1250 setLibcallName(RTLIB::COS_F128, "cosf128"); 1251 setLibcallName(RTLIB::POW_F128, "powf128"); 1252 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1253 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1254 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1255 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1256 1257 // With 32 condition bits, we don't need to sink (and duplicate) compares 1258 // aggressively in CodeGenPrep. 1259 if (Subtarget.useCRBits()) { 1260 setHasMultipleConditionRegisters(); 1261 setJumpIsExpensive(); 1262 } 1263 1264 setMinFunctionAlignment(Align(4)); 1265 1266 switch (Subtarget.getCPUDirective()) { 1267 default: break; 1268 case PPC::DIR_970: 1269 case PPC::DIR_A2: 1270 case PPC::DIR_E500: 1271 case PPC::DIR_E500mc: 1272 case PPC::DIR_E5500: 1273 case PPC::DIR_PWR4: 1274 case PPC::DIR_PWR5: 1275 case PPC::DIR_PWR5X: 1276 case PPC::DIR_PWR6: 1277 case PPC::DIR_PWR6X: 1278 case PPC::DIR_PWR7: 1279 case PPC::DIR_PWR8: 1280 case PPC::DIR_PWR9: 1281 case PPC::DIR_PWR10: 1282 case PPC::DIR_PWR_FUTURE: 1283 setPrefLoopAlignment(Align(16)); 1284 setPrefFunctionAlignment(Align(16)); 1285 break; 1286 } 1287 1288 if (Subtarget.enableMachineScheduler()) 1289 setSchedulingPreference(Sched::Source); 1290 else 1291 setSchedulingPreference(Sched::Hybrid); 1292 1293 computeRegisterProperties(STI.getRegisterInfo()); 1294 1295 // The Freescale cores do better with aggressive inlining of memcpy and 1296 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1297 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1298 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1299 MaxStoresPerMemset = 32; 1300 MaxStoresPerMemsetOptSize = 16; 1301 MaxStoresPerMemcpy = 32; 1302 MaxStoresPerMemcpyOptSize = 8; 1303 MaxStoresPerMemmove = 32; 1304 MaxStoresPerMemmoveOptSize = 8; 1305 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1306 // The A2 also benefits from (very) aggressive inlining of memcpy and 1307 // friends. The overhead of a the function call, even when warm, can be 1308 // over one hundred cycles. 1309 MaxStoresPerMemset = 128; 1310 MaxStoresPerMemcpy = 128; 1311 MaxStoresPerMemmove = 128; 1312 MaxLoadsPerMemcmp = 128; 1313 } else { 1314 MaxLoadsPerMemcmp = 8; 1315 MaxLoadsPerMemcmpOptSize = 4; 1316 } 1317 1318 // Let the subtarget (CPU) decide if a predictable select is more expensive 1319 // than the corresponding branch. This information is used in CGP to decide 1320 // when to convert selects into branches. 1321 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1322 } 1323 1324 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1325 /// the desired ByVal argument alignment. 1326 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1327 if (MaxAlign == MaxMaxAlign) 1328 return; 1329 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1330 if (MaxMaxAlign >= 32 && 1331 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1332 MaxAlign = Align(32); 1333 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1334 MaxAlign < 16) 1335 MaxAlign = Align(16); 1336 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1337 Align EltAlign; 1338 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1339 if (EltAlign > MaxAlign) 1340 MaxAlign = EltAlign; 1341 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1342 for (auto *EltTy : STy->elements()) { 1343 Align EltAlign; 1344 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1345 if (EltAlign > MaxAlign) 1346 MaxAlign = EltAlign; 1347 if (MaxAlign == MaxMaxAlign) 1348 break; 1349 } 1350 } 1351 } 1352 1353 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1354 /// function arguments in the caller parameter area. 1355 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1356 const DataLayout &DL) const { 1357 // 16byte and wider vectors are passed on 16byte boundary. 1358 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1359 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1360 if (Subtarget.hasAltivec()) 1361 getMaxByValAlign(Ty, Alignment, Align(16)); 1362 return Alignment.value(); 1363 } 1364 1365 bool PPCTargetLowering::useSoftFloat() const { 1366 return Subtarget.useSoftFloat(); 1367 } 1368 1369 bool PPCTargetLowering::hasSPE() const { 1370 return Subtarget.hasSPE(); 1371 } 1372 1373 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1374 return VT.isScalarInteger(); 1375 } 1376 1377 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1378 /// type is cheaper than a multiply followed by a shift. 1379 /// This is true for words and doublewords on 64-bit PowerPC. 1380 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1381 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1382 isOperationLegal(ISD::MULHU, Type))) 1383 return true; 1384 return TargetLowering::isMulhCheaperThanMulShift(Type); 1385 } 1386 1387 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1388 switch ((PPCISD::NodeType)Opcode) { 1389 case PPCISD::FIRST_NUMBER: break; 1390 case PPCISD::FSEL: return "PPCISD::FSEL"; 1391 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1392 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1393 case PPCISD::FCFID: return "PPCISD::FCFID"; 1394 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1395 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1396 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1397 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1398 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1399 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1400 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1401 case PPCISD::FP_TO_UINT_IN_VSR: 1402 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1403 case PPCISD::FP_TO_SINT_IN_VSR: 1404 return "PPCISD::FP_TO_SINT_IN_VSR"; 1405 case PPCISD::FRE: return "PPCISD::FRE"; 1406 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1407 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1408 case PPCISD::VPERM: return "PPCISD::VPERM"; 1409 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1410 case PPCISD::XXSPLTI_SP_TO_DP: 1411 return "PPCISD::XXSPLTI_SP_TO_DP"; 1412 case PPCISD::XXSPLTI32DX: 1413 return "PPCISD::XXSPLTI32DX"; 1414 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1415 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1416 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1417 case PPCISD::CMPB: return "PPCISD::CMPB"; 1418 case PPCISD::Hi: return "PPCISD::Hi"; 1419 case PPCISD::Lo: return "PPCISD::Lo"; 1420 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1421 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1422 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1423 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1424 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1425 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1426 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1427 case PPCISD::SRL: return "PPCISD::SRL"; 1428 case PPCISD::SRA: return "PPCISD::SRA"; 1429 case PPCISD::SHL: return "PPCISD::SHL"; 1430 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1431 case PPCISD::CALL: return "PPCISD::CALL"; 1432 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1433 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1434 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1435 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1436 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1437 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1438 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1439 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1440 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1441 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1442 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1443 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1444 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1445 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1446 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1447 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1448 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1449 case PPCISD::ANDI_rec_1_EQ_BIT: 1450 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1451 case PPCISD::ANDI_rec_1_GT_BIT: 1452 return "PPCISD::ANDI_rec_1_GT_BIT"; 1453 case PPCISD::VCMP: return "PPCISD::VCMP"; 1454 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1455 case PPCISD::LBRX: return "PPCISD::LBRX"; 1456 case PPCISD::STBRX: return "PPCISD::STBRX"; 1457 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1458 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1459 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1460 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1461 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1462 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1463 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1464 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1465 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1466 case PPCISD::ST_VSR_SCAL_INT: 1467 return "PPCISD::ST_VSR_SCAL_INT"; 1468 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1469 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1470 case PPCISD::BDZ: return "PPCISD::BDZ"; 1471 case PPCISD::MFFS: return "PPCISD::MFFS"; 1472 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1473 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1474 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1475 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1476 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1477 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1478 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1479 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1480 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1481 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1482 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1483 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1484 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1485 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1486 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1487 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1488 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1489 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1490 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1491 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1492 case PPCISD::SC: return "PPCISD::SC"; 1493 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1494 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1495 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1496 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1497 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1498 case PPCISD::VABSD: return "PPCISD::VABSD"; 1499 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1500 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1501 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1502 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1503 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1504 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1505 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1506 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1507 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1508 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1509 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1510 case PPCISD::STRICT_FADDRTZ: 1511 return "PPCISD::STRICT_FADDRTZ"; 1512 case PPCISD::STRICT_FCTIDZ: 1513 return "PPCISD::STRICT_FCTIDZ"; 1514 case PPCISD::STRICT_FCTIWZ: 1515 return "PPCISD::STRICT_FCTIWZ"; 1516 case PPCISD::STRICT_FCTIDUZ: 1517 return "PPCISD::STRICT_FCTIDUZ"; 1518 case PPCISD::STRICT_FCTIWUZ: 1519 return "PPCISD::STRICT_FCTIWUZ"; 1520 case PPCISD::STRICT_FCFID: 1521 return "PPCISD::STRICT_FCFID"; 1522 case PPCISD::STRICT_FCFIDU: 1523 return "PPCISD::STRICT_FCFIDU"; 1524 case PPCISD::STRICT_FCFIDS: 1525 return "PPCISD::STRICT_FCFIDS"; 1526 case PPCISD::STRICT_FCFIDUS: 1527 return "PPCISD::STRICT_FCFIDUS"; 1528 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1529 } 1530 return nullptr; 1531 } 1532 1533 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1534 EVT VT) const { 1535 if (!VT.isVector()) 1536 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1537 1538 return VT.changeVectorElementTypeToInteger(); 1539 } 1540 1541 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1542 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1543 return true; 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // Node matching predicates, for use by the tblgen matching code. 1548 //===----------------------------------------------------------------------===// 1549 1550 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1551 static bool isFloatingPointZero(SDValue Op) { 1552 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1553 return CFP->getValueAPF().isZero(); 1554 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1555 // Maybe this has already been legalized into the constant pool? 1556 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1557 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1558 return CFP->getValueAPF().isZero(); 1559 } 1560 return false; 1561 } 1562 1563 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1564 /// true if Op is undef or if it matches the specified value. 1565 static bool isConstantOrUndef(int Op, int Val) { 1566 return Op < 0 || Op == Val; 1567 } 1568 1569 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1570 /// VPKUHUM instruction. 1571 /// The ShuffleKind distinguishes between big-endian operations with 1572 /// two different inputs (0), either-endian operations with two identical 1573 /// inputs (1), and little-endian operations with two different inputs (2). 1574 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1575 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1576 SelectionDAG &DAG) { 1577 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1578 if (ShuffleKind == 0) { 1579 if (IsLE) 1580 return false; 1581 for (unsigned i = 0; i != 16; ++i) 1582 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1583 return false; 1584 } else if (ShuffleKind == 2) { 1585 if (!IsLE) 1586 return false; 1587 for (unsigned i = 0; i != 16; ++i) 1588 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1589 return false; 1590 } else if (ShuffleKind == 1) { 1591 unsigned j = IsLE ? 0 : 1; 1592 for (unsigned i = 0; i != 8; ++i) 1593 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1594 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1595 return false; 1596 } 1597 return true; 1598 } 1599 1600 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1601 /// VPKUWUM instruction. 1602 /// The ShuffleKind distinguishes between big-endian operations with 1603 /// two different inputs (0), either-endian operations with two identical 1604 /// inputs (1), and little-endian operations with two different inputs (2). 1605 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1606 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1607 SelectionDAG &DAG) { 1608 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1609 if (ShuffleKind == 0) { 1610 if (IsLE) 1611 return false; 1612 for (unsigned i = 0; i != 16; i += 2) 1613 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1614 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1615 return false; 1616 } else if (ShuffleKind == 2) { 1617 if (!IsLE) 1618 return false; 1619 for (unsigned i = 0; i != 16; i += 2) 1620 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1621 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1622 return false; 1623 } else if (ShuffleKind == 1) { 1624 unsigned j = IsLE ? 0 : 2; 1625 for (unsigned i = 0; i != 8; i += 2) 1626 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1627 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1628 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1629 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1630 return false; 1631 } 1632 return true; 1633 } 1634 1635 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1636 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1637 /// current subtarget. 1638 /// 1639 /// The ShuffleKind distinguishes between big-endian operations with 1640 /// two different inputs (0), either-endian operations with two identical 1641 /// inputs (1), and little-endian operations with two different inputs (2). 1642 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1643 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1644 SelectionDAG &DAG) { 1645 const PPCSubtarget& Subtarget = 1646 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1647 if (!Subtarget.hasP8Vector()) 1648 return false; 1649 1650 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1651 if (ShuffleKind == 0) { 1652 if (IsLE) 1653 return false; 1654 for (unsigned i = 0; i != 16; i += 4) 1655 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1656 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1657 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1658 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1659 return false; 1660 } else if (ShuffleKind == 2) { 1661 if (!IsLE) 1662 return false; 1663 for (unsigned i = 0; i != 16; i += 4) 1664 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1665 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1666 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1667 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1668 return false; 1669 } else if (ShuffleKind == 1) { 1670 unsigned j = IsLE ? 0 : 4; 1671 for (unsigned i = 0; i != 8; i += 4) 1672 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1673 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1674 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1675 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1676 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1677 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1678 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1679 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1680 return false; 1681 } 1682 return true; 1683 } 1684 1685 /// isVMerge - Common function, used to match vmrg* shuffles. 1686 /// 1687 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1688 unsigned LHSStart, unsigned RHSStart) { 1689 if (N->getValueType(0) != MVT::v16i8) 1690 return false; 1691 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1692 "Unsupported merge size!"); 1693 1694 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1695 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1696 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1697 LHSStart+j+i*UnitSize) || 1698 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1699 RHSStart+j+i*UnitSize)) 1700 return false; 1701 } 1702 return true; 1703 } 1704 1705 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1706 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1707 /// The ShuffleKind distinguishes between big-endian merges with two 1708 /// different inputs (0), either-endian merges with two identical inputs (1), 1709 /// and little-endian merges with two different inputs (2). For the latter, 1710 /// the input operands are swapped (see PPCInstrAltivec.td). 1711 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1712 unsigned ShuffleKind, SelectionDAG &DAG) { 1713 if (DAG.getDataLayout().isLittleEndian()) { 1714 if (ShuffleKind == 1) // unary 1715 return isVMerge(N, UnitSize, 0, 0); 1716 else if (ShuffleKind == 2) // swapped 1717 return isVMerge(N, UnitSize, 0, 16); 1718 else 1719 return false; 1720 } else { 1721 if (ShuffleKind == 1) // unary 1722 return isVMerge(N, UnitSize, 8, 8); 1723 else if (ShuffleKind == 0) // normal 1724 return isVMerge(N, UnitSize, 8, 24); 1725 else 1726 return false; 1727 } 1728 } 1729 1730 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1731 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1732 /// The ShuffleKind distinguishes between big-endian merges with two 1733 /// different inputs (0), either-endian merges with two identical inputs (1), 1734 /// and little-endian merges with two different inputs (2). For the latter, 1735 /// the input operands are swapped (see PPCInstrAltivec.td). 1736 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1737 unsigned ShuffleKind, SelectionDAG &DAG) { 1738 if (DAG.getDataLayout().isLittleEndian()) { 1739 if (ShuffleKind == 1) // unary 1740 return isVMerge(N, UnitSize, 8, 8); 1741 else if (ShuffleKind == 2) // swapped 1742 return isVMerge(N, UnitSize, 8, 24); 1743 else 1744 return false; 1745 } else { 1746 if (ShuffleKind == 1) // unary 1747 return isVMerge(N, UnitSize, 0, 0); 1748 else if (ShuffleKind == 0) // normal 1749 return isVMerge(N, UnitSize, 0, 16); 1750 else 1751 return false; 1752 } 1753 } 1754 1755 /** 1756 * Common function used to match vmrgew and vmrgow shuffles 1757 * 1758 * The indexOffset determines whether to look for even or odd words in 1759 * the shuffle mask. This is based on the of the endianness of the target 1760 * machine. 1761 * - Little Endian: 1762 * - Use offset of 0 to check for odd elements 1763 * - Use offset of 4 to check for even elements 1764 * - Big Endian: 1765 * - Use offset of 0 to check for even elements 1766 * - Use offset of 4 to check for odd elements 1767 * A detailed description of the vector element ordering for little endian and 1768 * big endian can be found at 1769 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1770 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1771 * compiler differences mean to you 1772 * 1773 * The mask to the shuffle vector instruction specifies the indices of the 1774 * elements from the two input vectors to place in the result. The elements are 1775 * numbered in array-access order, starting with the first vector. These vectors 1776 * are always of type v16i8, thus each vector will contain 16 elements of size 1777 * 8. More info on the shuffle vector can be found in the 1778 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1779 * Language Reference. 1780 * 1781 * The RHSStartValue indicates whether the same input vectors are used (unary) 1782 * or two different input vectors are used, based on the following: 1783 * - If the instruction uses the same vector for both inputs, the range of the 1784 * indices will be 0 to 15. In this case, the RHSStart value passed should 1785 * be 0. 1786 * - If the instruction has two different vectors then the range of the 1787 * indices will be 0 to 31. In this case, the RHSStart value passed should 1788 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1789 * to 31 specify elements in the second vector). 1790 * 1791 * \param[in] N The shuffle vector SD Node to analyze 1792 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1793 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1794 * vector to the shuffle_vector instruction 1795 * \return true iff this shuffle vector represents an even or odd word merge 1796 */ 1797 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1798 unsigned RHSStartValue) { 1799 if (N->getValueType(0) != MVT::v16i8) 1800 return false; 1801 1802 for (unsigned i = 0; i < 2; ++i) 1803 for (unsigned j = 0; j < 4; ++j) 1804 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1805 i*RHSStartValue+j+IndexOffset) || 1806 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1807 i*RHSStartValue+j+IndexOffset+8)) 1808 return false; 1809 return true; 1810 } 1811 1812 /** 1813 * Determine if the specified shuffle mask is suitable for the vmrgew or 1814 * vmrgow instructions. 1815 * 1816 * \param[in] N The shuffle vector SD Node to analyze 1817 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1818 * \param[in] ShuffleKind Identify the type of merge: 1819 * - 0 = big-endian merge with two different inputs; 1820 * - 1 = either-endian merge with two identical inputs; 1821 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1822 * little-endian merges). 1823 * \param[in] DAG The current SelectionDAG 1824 * \return true iff this shuffle mask 1825 */ 1826 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1827 unsigned ShuffleKind, SelectionDAG &DAG) { 1828 if (DAG.getDataLayout().isLittleEndian()) { 1829 unsigned indexOffset = CheckEven ? 4 : 0; 1830 if (ShuffleKind == 1) // Unary 1831 return isVMerge(N, indexOffset, 0); 1832 else if (ShuffleKind == 2) // swapped 1833 return isVMerge(N, indexOffset, 16); 1834 else 1835 return false; 1836 } 1837 else { 1838 unsigned indexOffset = CheckEven ? 0 : 4; 1839 if (ShuffleKind == 1) // Unary 1840 return isVMerge(N, indexOffset, 0); 1841 else if (ShuffleKind == 0) // Normal 1842 return isVMerge(N, indexOffset, 16); 1843 else 1844 return false; 1845 } 1846 return false; 1847 } 1848 1849 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1850 /// amount, otherwise return -1. 1851 /// The ShuffleKind distinguishes between big-endian operations with two 1852 /// different inputs (0), either-endian operations with two identical inputs 1853 /// (1), and little-endian operations with two different inputs (2). For the 1854 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1855 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1856 SelectionDAG &DAG) { 1857 if (N->getValueType(0) != MVT::v16i8) 1858 return -1; 1859 1860 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1861 1862 // Find the first non-undef value in the shuffle mask. 1863 unsigned i; 1864 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1865 /*search*/; 1866 1867 if (i == 16) return -1; // all undef. 1868 1869 // Otherwise, check to see if the rest of the elements are consecutively 1870 // numbered from this value. 1871 unsigned ShiftAmt = SVOp->getMaskElt(i); 1872 if (ShiftAmt < i) return -1; 1873 1874 ShiftAmt -= i; 1875 bool isLE = DAG.getDataLayout().isLittleEndian(); 1876 1877 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1878 // Check the rest of the elements to see if they are consecutive. 1879 for (++i; i != 16; ++i) 1880 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1881 return -1; 1882 } else if (ShuffleKind == 1) { 1883 // Check the rest of the elements to see if they are consecutive. 1884 for (++i; i != 16; ++i) 1885 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1886 return -1; 1887 } else 1888 return -1; 1889 1890 if (isLE) 1891 ShiftAmt = 16 - ShiftAmt; 1892 1893 return ShiftAmt; 1894 } 1895 1896 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1897 /// specifies a splat of a single element that is suitable for input to 1898 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1899 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1900 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1901 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1902 1903 // The consecutive indices need to specify an element, not part of two 1904 // different elements. So abandon ship early if this isn't the case. 1905 if (N->getMaskElt(0) % EltSize != 0) 1906 return false; 1907 1908 // This is a splat operation if each element of the permute is the same, and 1909 // if the value doesn't reference the second vector. 1910 unsigned ElementBase = N->getMaskElt(0); 1911 1912 // FIXME: Handle UNDEF elements too! 1913 if (ElementBase >= 16) 1914 return false; 1915 1916 // Check that the indices are consecutive, in the case of a multi-byte element 1917 // splatted with a v16i8 mask. 1918 for (unsigned i = 1; i != EltSize; ++i) 1919 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1920 return false; 1921 1922 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1923 if (N->getMaskElt(i) < 0) continue; 1924 for (unsigned j = 0; j != EltSize; ++j) 1925 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1926 return false; 1927 } 1928 return true; 1929 } 1930 1931 /// Check that the mask is shuffling N byte elements. Within each N byte 1932 /// element of the mask, the indices could be either in increasing or 1933 /// decreasing order as long as they are consecutive. 1934 /// \param[in] N the shuffle vector SD Node to analyze 1935 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1936 /// Word/DoubleWord/QuadWord). 1937 /// \param[in] StepLen the delta indices number among the N byte element, if 1938 /// the mask is in increasing/decreasing order then it is 1/-1. 1939 /// \return true iff the mask is shuffling N byte elements. 1940 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1941 int StepLen) { 1942 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1943 "Unexpected element width."); 1944 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1945 1946 unsigned NumOfElem = 16 / Width; 1947 unsigned MaskVal[16]; // Width is never greater than 16 1948 for (unsigned i = 0; i < NumOfElem; ++i) { 1949 MaskVal[0] = N->getMaskElt(i * Width); 1950 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1951 return false; 1952 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1953 return false; 1954 } 1955 1956 for (unsigned int j = 1; j < Width; ++j) { 1957 MaskVal[j] = N->getMaskElt(i * Width + j); 1958 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1959 return false; 1960 } 1961 } 1962 } 1963 1964 return true; 1965 } 1966 1967 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1968 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1969 if (!isNByteElemShuffleMask(N, 4, 1)) 1970 return false; 1971 1972 // Now we look at mask elements 0,4,8,12 1973 unsigned M0 = N->getMaskElt(0) / 4; 1974 unsigned M1 = N->getMaskElt(4) / 4; 1975 unsigned M2 = N->getMaskElt(8) / 4; 1976 unsigned M3 = N->getMaskElt(12) / 4; 1977 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1978 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1979 1980 // Below, let H and L be arbitrary elements of the shuffle mask 1981 // where H is in the range [4,7] and L is in the range [0,3]. 1982 // H, 1, 2, 3 or L, 5, 6, 7 1983 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1984 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1985 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1986 InsertAtByte = IsLE ? 12 : 0; 1987 Swap = M0 < 4; 1988 return true; 1989 } 1990 // 0, H, 2, 3 or 4, L, 6, 7 1991 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1992 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1993 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1994 InsertAtByte = IsLE ? 8 : 4; 1995 Swap = M1 < 4; 1996 return true; 1997 } 1998 // 0, 1, H, 3 or 4, 5, L, 7 1999 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2000 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2001 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2002 InsertAtByte = IsLE ? 4 : 8; 2003 Swap = M2 < 4; 2004 return true; 2005 } 2006 // 0, 1, 2, H or 4, 5, 6, L 2007 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2008 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2009 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2010 InsertAtByte = IsLE ? 0 : 12; 2011 Swap = M3 < 4; 2012 return true; 2013 } 2014 2015 // If both vector operands for the shuffle are the same vector, the mask will 2016 // contain only elements from the first one and the second one will be undef. 2017 if (N->getOperand(1).isUndef()) { 2018 ShiftElts = 0; 2019 Swap = true; 2020 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2021 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2022 InsertAtByte = IsLE ? 12 : 0; 2023 return true; 2024 } 2025 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2026 InsertAtByte = IsLE ? 8 : 4; 2027 return true; 2028 } 2029 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2030 InsertAtByte = IsLE ? 4 : 8; 2031 return true; 2032 } 2033 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2034 InsertAtByte = IsLE ? 0 : 12; 2035 return true; 2036 } 2037 } 2038 2039 return false; 2040 } 2041 2042 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2043 bool &Swap, bool IsLE) { 2044 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2045 // Ensure each byte index of the word is consecutive. 2046 if (!isNByteElemShuffleMask(N, 4, 1)) 2047 return false; 2048 2049 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2050 unsigned M0 = N->getMaskElt(0) / 4; 2051 unsigned M1 = N->getMaskElt(4) / 4; 2052 unsigned M2 = N->getMaskElt(8) / 4; 2053 unsigned M3 = N->getMaskElt(12) / 4; 2054 2055 // If both vector operands for the shuffle are the same vector, the mask will 2056 // contain only elements from the first one and the second one will be undef. 2057 if (N->getOperand(1).isUndef()) { 2058 assert(M0 < 4 && "Indexing into an undef vector?"); 2059 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2060 return false; 2061 2062 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2063 Swap = false; 2064 return true; 2065 } 2066 2067 // Ensure each word index of the ShuffleVector Mask is consecutive. 2068 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2069 return false; 2070 2071 if (IsLE) { 2072 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2073 // Input vectors don't need to be swapped if the leading element 2074 // of the result is one of the 3 left elements of the second vector 2075 // (or if there is no shift to be done at all). 2076 Swap = false; 2077 ShiftElts = (8 - M0) % 8; 2078 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2079 // Input vectors need to be swapped if the leading element 2080 // of the result is one of the 3 left elements of the first vector 2081 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2082 Swap = true; 2083 ShiftElts = (4 - M0) % 4; 2084 } 2085 2086 return true; 2087 } else { // BE 2088 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2089 // Input vectors don't need to be swapped if the leading element 2090 // of the result is one of the 4 elements of the first vector. 2091 Swap = false; 2092 ShiftElts = M0; 2093 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2094 // Input vectors need to be swapped if the leading element 2095 // of the result is one of the 4 elements of the right vector. 2096 Swap = true; 2097 ShiftElts = M0 - 4; 2098 } 2099 2100 return true; 2101 } 2102 } 2103 2104 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2105 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2106 2107 if (!isNByteElemShuffleMask(N, Width, -1)) 2108 return false; 2109 2110 for (int i = 0; i < 16; i += Width) 2111 if (N->getMaskElt(i) != i + Width - 1) 2112 return false; 2113 2114 return true; 2115 } 2116 2117 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2118 return isXXBRShuffleMaskHelper(N, 2); 2119 } 2120 2121 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2122 return isXXBRShuffleMaskHelper(N, 4); 2123 } 2124 2125 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2126 return isXXBRShuffleMaskHelper(N, 8); 2127 } 2128 2129 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2130 return isXXBRShuffleMaskHelper(N, 16); 2131 } 2132 2133 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2134 /// if the inputs to the instruction should be swapped and set \p DM to the 2135 /// value for the immediate. 2136 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2137 /// AND element 0 of the result comes from the first input (LE) or second input 2138 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2139 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2140 /// mask. 2141 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2142 bool &Swap, bool IsLE) { 2143 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2144 2145 // Ensure each byte index of the double word is consecutive. 2146 if (!isNByteElemShuffleMask(N, 8, 1)) 2147 return false; 2148 2149 unsigned M0 = N->getMaskElt(0) / 8; 2150 unsigned M1 = N->getMaskElt(8) / 8; 2151 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2152 2153 // If both vector operands for the shuffle are the same vector, the mask will 2154 // contain only elements from the first one and the second one will be undef. 2155 if (N->getOperand(1).isUndef()) { 2156 if ((M0 | M1) < 2) { 2157 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2158 Swap = false; 2159 return true; 2160 } else 2161 return false; 2162 } 2163 2164 if (IsLE) { 2165 if (M0 > 1 && M1 < 2) { 2166 Swap = false; 2167 } else if (M0 < 2 && M1 > 1) { 2168 M0 = (M0 + 2) % 4; 2169 M1 = (M1 + 2) % 4; 2170 Swap = true; 2171 } else 2172 return false; 2173 2174 // Note: if control flow comes here that means Swap is already set above 2175 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2176 return true; 2177 } else { // BE 2178 if (M0 < 2 && M1 > 1) { 2179 Swap = false; 2180 } else if (M0 > 1 && M1 < 2) { 2181 M0 = (M0 + 2) % 4; 2182 M1 = (M1 + 2) % 4; 2183 Swap = true; 2184 } else 2185 return false; 2186 2187 // Note: if control flow comes here that means Swap is already set above 2188 DM = (M0 << 1) + (M1 & 1); 2189 return true; 2190 } 2191 } 2192 2193 2194 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2195 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2196 /// elements are counted from the left of the vector register). 2197 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2198 SelectionDAG &DAG) { 2199 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2200 assert(isSplatShuffleMask(SVOp, EltSize)); 2201 if (DAG.getDataLayout().isLittleEndian()) 2202 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2203 else 2204 return SVOp->getMaskElt(0) / EltSize; 2205 } 2206 2207 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2208 /// by using a vspltis[bhw] instruction of the specified element size, return 2209 /// the constant being splatted. The ByteSize field indicates the number of 2210 /// bytes of each element [124] -> [bhw]. 2211 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2212 SDValue OpVal(nullptr, 0); 2213 2214 // If ByteSize of the splat is bigger than the element size of the 2215 // build_vector, then we have a case where we are checking for a splat where 2216 // multiple elements of the buildvector are folded together into a single 2217 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2218 unsigned EltSize = 16/N->getNumOperands(); 2219 if (EltSize < ByteSize) { 2220 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2221 SDValue UniquedVals[4]; 2222 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2223 2224 // See if all of the elements in the buildvector agree across. 2225 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2226 if (N->getOperand(i).isUndef()) continue; 2227 // If the element isn't a constant, bail fully out. 2228 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2229 2230 if (!UniquedVals[i&(Multiple-1)].getNode()) 2231 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2232 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2233 return SDValue(); // no match. 2234 } 2235 2236 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2237 // either constant or undef values that are identical for each chunk. See 2238 // if these chunks can form into a larger vspltis*. 2239 2240 // Check to see if all of the leading entries are either 0 or -1. If 2241 // neither, then this won't fit into the immediate field. 2242 bool LeadingZero = true; 2243 bool LeadingOnes = true; 2244 for (unsigned i = 0; i != Multiple-1; ++i) { 2245 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2246 2247 LeadingZero &= isNullConstant(UniquedVals[i]); 2248 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2249 } 2250 // Finally, check the least significant entry. 2251 if (LeadingZero) { 2252 if (!UniquedVals[Multiple-1].getNode()) 2253 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2254 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2255 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2256 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2257 } 2258 if (LeadingOnes) { 2259 if (!UniquedVals[Multiple-1].getNode()) 2260 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2261 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2262 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2263 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2264 } 2265 2266 return SDValue(); 2267 } 2268 2269 // Check to see if this buildvec has a single non-undef value in its elements. 2270 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2271 if (N->getOperand(i).isUndef()) continue; 2272 if (!OpVal.getNode()) 2273 OpVal = N->getOperand(i); 2274 else if (OpVal != N->getOperand(i)) 2275 return SDValue(); 2276 } 2277 2278 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2279 2280 unsigned ValSizeInBytes = EltSize; 2281 uint64_t Value = 0; 2282 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2283 Value = CN->getZExtValue(); 2284 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2285 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2286 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2287 } 2288 2289 // If the splat value is larger than the element value, then we can never do 2290 // this splat. The only case that we could fit the replicated bits into our 2291 // immediate field for would be zero, and we prefer to use vxor for it. 2292 if (ValSizeInBytes < ByteSize) return SDValue(); 2293 2294 // If the element value is larger than the splat value, check if it consists 2295 // of a repeated bit pattern of size ByteSize. 2296 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2297 return SDValue(); 2298 2299 // Properly sign extend the value. 2300 int MaskVal = SignExtend32(Value, ByteSize * 8); 2301 2302 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2303 if (MaskVal == 0) return SDValue(); 2304 2305 // Finally, if this value fits in a 5 bit sext field, return it 2306 if (SignExtend32<5>(MaskVal) == MaskVal) 2307 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2308 return SDValue(); 2309 } 2310 2311 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2312 /// amount, otherwise return -1. 2313 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2314 EVT VT = N->getValueType(0); 2315 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2316 return -1; 2317 2318 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2319 2320 // Find the first non-undef value in the shuffle mask. 2321 unsigned i; 2322 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2323 /*search*/; 2324 2325 if (i == 4) return -1; // all undef. 2326 2327 // Otherwise, check to see if the rest of the elements are consecutively 2328 // numbered from this value. 2329 unsigned ShiftAmt = SVOp->getMaskElt(i); 2330 if (ShiftAmt < i) return -1; 2331 ShiftAmt -= i; 2332 2333 // Check the rest of the elements to see if they are consecutive. 2334 for (++i; i != 4; ++i) 2335 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2336 return -1; 2337 2338 return ShiftAmt; 2339 } 2340 2341 //===----------------------------------------------------------------------===// 2342 // Addressing Mode Selection 2343 //===----------------------------------------------------------------------===// 2344 2345 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2346 /// or 64-bit immediate, and if the value can be accurately represented as a 2347 /// sign extension from a 16-bit value. If so, this returns true and the 2348 /// immediate. 2349 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2350 if (!isa<ConstantSDNode>(N)) 2351 return false; 2352 2353 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2354 if (N->getValueType(0) == MVT::i32) 2355 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2356 else 2357 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2358 } 2359 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2360 return isIntS16Immediate(Op.getNode(), Imm); 2361 } 2362 2363 2364 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2365 /// be represented as an indexed [r+r] operation. 2366 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2367 SDValue &Index, 2368 SelectionDAG &DAG) const { 2369 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2370 UI != E; ++UI) { 2371 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2372 if (Memop->getMemoryVT() == MVT::f64) { 2373 Base = N.getOperand(0); 2374 Index = N.getOperand(1); 2375 return true; 2376 } 2377 } 2378 } 2379 return false; 2380 } 2381 2382 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2383 /// can be represented as an indexed [r+r] operation. Returns false if it 2384 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2385 /// non-zero and N can be represented by a base register plus a signed 16-bit 2386 /// displacement, make a more precise judgement by checking (displacement % \p 2387 /// EncodingAlignment). 2388 bool PPCTargetLowering::SelectAddressRegReg( 2389 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2390 MaybeAlign EncodingAlignment) const { 2391 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2392 // a [pc+imm]. 2393 if (SelectAddressPCRel(N, Base)) 2394 return false; 2395 2396 int16_t Imm = 0; 2397 if (N.getOpcode() == ISD::ADD) { 2398 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2399 // SPE load/store can only handle 8-bit offsets. 2400 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2401 return true; 2402 if (isIntS16Immediate(N.getOperand(1), Imm) && 2403 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2404 return false; // r+i 2405 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2406 return false; // r+i 2407 2408 Base = N.getOperand(0); 2409 Index = N.getOperand(1); 2410 return true; 2411 } else if (N.getOpcode() == ISD::OR) { 2412 if (isIntS16Immediate(N.getOperand(1), Imm) && 2413 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2414 return false; // r+i can fold it if we can. 2415 2416 // If this is an or of disjoint bitfields, we can codegen this as an add 2417 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2418 // disjoint. 2419 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2420 2421 if (LHSKnown.Zero.getBoolValue()) { 2422 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2423 // If all of the bits are known zero on the LHS or RHS, the add won't 2424 // carry. 2425 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2426 Base = N.getOperand(0); 2427 Index = N.getOperand(1); 2428 return true; 2429 } 2430 } 2431 } 2432 2433 return false; 2434 } 2435 2436 // If we happen to be doing an i64 load or store into a stack slot that has 2437 // less than a 4-byte alignment, then the frame-index elimination may need to 2438 // use an indexed load or store instruction (because the offset may not be a 2439 // multiple of 4). The extra register needed to hold the offset comes from the 2440 // register scavenger, and it is possible that the scavenger will need to use 2441 // an emergency spill slot. As a result, we need to make sure that a spill slot 2442 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2443 // stack slot. 2444 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2445 // FIXME: This does not handle the LWA case. 2446 if (VT != MVT::i64) 2447 return; 2448 2449 // NOTE: We'll exclude negative FIs here, which come from argument 2450 // lowering, because there are no known test cases triggering this problem 2451 // using packed structures (or similar). We can remove this exclusion if 2452 // we find such a test case. The reason why this is so test-case driven is 2453 // because this entire 'fixup' is only to prevent crashes (from the 2454 // register scavenger) on not-really-valid inputs. For example, if we have: 2455 // %a = alloca i1 2456 // %b = bitcast i1* %a to i64* 2457 // store i64* a, i64 b 2458 // then the store should really be marked as 'align 1', but is not. If it 2459 // were marked as 'align 1' then the indexed form would have been 2460 // instruction-selected initially, and the problem this 'fixup' is preventing 2461 // won't happen regardless. 2462 if (FrameIdx < 0) 2463 return; 2464 2465 MachineFunction &MF = DAG.getMachineFunction(); 2466 MachineFrameInfo &MFI = MF.getFrameInfo(); 2467 2468 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2469 return; 2470 2471 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2472 FuncInfo->setHasNonRISpills(); 2473 } 2474 2475 /// Returns true if the address N can be represented by a base register plus 2476 /// a signed 16-bit displacement [r+imm], and if it is not better 2477 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2478 /// displacements that are multiples of that value. 2479 bool PPCTargetLowering::SelectAddressRegImm( 2480 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2481 MaybeAlign EncodingAlignment) const { 2482 // FIXME dl should come from parent load or store, not from address 2483 SDLoc dl(N); 2484 2485 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2486 // a [pc+imm]. 2487 if (SelectAddressPCRel(N, Base)) 2488 return false; 2489 2490 // If this can be more profitably realized as r+r, fail. 2491 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2492 return false; 2493 2494 if (N.getOpcode() == ISD::ADD) { 2495 int16_t imm = 0; 2496 if (isIntS16Immediate(N.getOperand(1), imm) && 2497 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2498 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2499 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2500 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2501 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2502 } else { 2503 Base = N.getOperand(0); 2504 } 2505 return true; // [r+i] 2506 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2507 // Match LOAD (ADD (X, Lo(G))). 2508 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2509 && "Cannot handle constant offsets yet!"); 2510 Disp = N.getOperand(1).getOperand(0); // The global address. 2511 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2512 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2513 Disp.getOpcode() == ISD::TargetConstantPool || 2514 Disp.getOpcode() == ISD::TargetJumpTable); 2515 Base = N.getOperand(0); 2516 return true; // [&g+r] 2517 } 2518 } else if (N.getOpcode() == ISD::OR) { 2519 int16_t imm = 0; 2520 if (isIntS16Immediate(N.getOperand(1), imm) && 2521 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2522 // If this is an or of disjoint bitfields, we can codegen this as an add 2523 // (for better address arithmetic) if the LHS and RHS of the OR are 2524 // provably disjoint. 2525 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2526 2527 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2528 // If all of the bits are known zero on the LHS or RHS, the add won't 2529 // carry. 2530 if (FrameIndexSDNode *FI = 2531 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2532 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2533 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2534 } else { 2535 Base = N.getOperand(0); 2536 } 2537 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2538 return true; 2539 } 2540 } 2541 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2542 // Loading from a constant address. 2543 2544 // If this address fits entirely in a 16-bit sext immediate field, codegen 2545 // this as "d, 0" 2546 int16_t Imm; 2547 if (isIntS16Immediate(CN, Imm) && 2548 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2549 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2550 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2551 CN->getValueType(0)); 2552 return true; 2553 } 2554 2555 // Handle 32-bit sext immediates with LIS + addr mode. 2556 if ((CN->getValueType(0) == MVT::i32 || 2557 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2558 (!EncodingAlignment || 2559 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2560 int Addr = (int)CN->getZExtValue(); 2561 2562 // Otherwise, break this down into an LIS + disp. 2563 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2564 2565 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2566 MVT::i32); 2567 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2568 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2569 return true; 2570 } 2571 } 2572 2573 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2574 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2575 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2576 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2577 } else 2578 Base = N; 2579 return true; // [r+0] 2580 } 2581 2582 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2583 /// represented as an indexed [r+r] operation. 2584 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2585 SDValue &Index, 2586 SelectionDAG &DAG) const { 2587 // Check to see if we can easily represent this as an [r+r] address. This 2588 // will fail if it thinks that the address is more profitably represented as 2589 // reg+imm, e.g. where imm = 0. 2590 if (SelectAddressRegReg(N, Base, Index, DAG)) 2591 return true; 2592 2593 // If the address is the result of an add, we will utilize the fact that the 2594 // address calculation includes an implicit add. However, we can reduce 2595 // register pressure if we do not materialize a constant just for use as the 2596 // index register. We only get rid of the add if it is not an add of a 2597 // value and a 16-bit signed constant and both have a single use. 2598 int16_t imm = 0; 2599 if (N.getOpcode() == ISD::ADD && 2600 (!isIntS16Immediate(N.getOperand(1), imm) || 2601 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2602 Base = N.getOperand(0); 2603 Index = N.getOperand(1); 2604 return true; 2605 } 2606 2607 // Otherwise, do it the hard way, using R0 as the base register. 2608 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2609 N.getValueType()); 2610 Index = N; 2611 return true; 2612 } 2613 2614 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2615 Ty *PCRelCand = dyn_cast<Ty>(N); 2616 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2617 } 2618 2619 /// Returns true if this address is a PC Relative address. 2620 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2621 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2622 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2623 // This is a materialize PC Relative node. Always select this as PC Relative. 2624 Base = N; 2625 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2626 return true; 2627 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2628 isValidPCRelNode<GlobalAddressSDNode>(N) || 2629 isValidPCRelNode<JumpTableSDNode>(N) || 2630 isValidPCRelNode<BlockAddressSDNode>(N)) 2631 return true; 2632 return false; 2633 } 2634 2635 /// Returns true if we should use a direct load into vector instruction 2636 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2637 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2638 2639 // If there are any other uses other than scalar to vector, then we should 2640 // keep it as a scalar load -> direct move pattern to prevent multiple 2641 // loads. 2642 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2643 if (!LD) 2644 return false; 2645 2646 EVT MemVT = LD->getMemoryVT(); 2647 if (!MemVT.isSimple()) 2648 return false; 2649 switch(MemVT.getSimpleVT().SimpleTy) { 2650 case MVT::i64: 2651 break; 2652 case MVT::i32: 2653 if (!ST.hasP8Vector()) 2654 return false; 2655 break; 2656 case MVT::i16: 2657 case MVT::i8: 2658 if (!ST.hasP9Vector()) 2659 return false; 2660 break; 2661 default: 2662 return false; 2663 } 2664 2665 SDValue LoadedVal(N, 0); 2666 if (!LoadedVal.hasOneUse()) 2667 return false; 2668 2669 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2670 UI != UE; ++UI) 2671 if (UI.getUse().get().getResNo() == 0 && 2672 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2673 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2674 return false; 2675 2676 return true; 2677 } 2678 2679 /// getPreIndexedAddressParts - returns true by value, base pointer and 2680 /// offset pointer and addressing mode by reference if the node's address 2681 /// can be legally represented as pre-indexed load / store address. 2682 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2683 SDValue &Offset, 2684 ISD::MemIndexedMode &AM, 2685 SelectionDAG &DAG) const { 2686 if (DisablePPCPreinc) return false; 2687 2688 bool isLoad = true; 2689 SDValue Ptr; 2690 EVT VT; 2691 unsigned Alignment; 2692 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2693 Ptr = LD->getBasePtr(); 2694 VT = LD->getMemoryVT(); 2695 Alignment = LD->getAlignment(); 2696 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2697 Ptr = ST->getBasePtr(); 2698 VT = ST->getMemoryVT(); 2699 Alignment = ST->getAlignment(); 2700 isLoad = false; 2701 } else 2702 return false; 2703 2704 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2705 // instructions because we can fold these into a more efficient instruction 2706 // instead, (such as LXSD). 2707 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2708 return false; 2709 } 2710 2711 // PowerPC doesn't have preinc load/store instructions for vectors 2712 if (VT.isVector()) 2713 return false; 2714 2715 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2716 // Common code will reject creating a pre-inc form if the base pointer 2717 // is a frame index, or if N is a store and the base pointer is either 2718 // the same as or a predecessor of the value being stored. Check for 2719 // those situations here, and try with swapped Base/Offset instead. 2720 bool Swap = false; 2721 2722 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2723 Swap = true; 2724 else if (!isLoad) { 2725 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2726 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2727 Swap = true; 2728 } 2729 2730 if (Swap) 2731 std::swap(Base, Offset); 2732 2733 AM = ISD::PRE_INC; 2734 return true; 2735 } 2736 2737 // LDU/STU can only handle immediates that are a multiple of 4. 2738 if (VT != MVT::i64) { 2739 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2740 return false; 2741 } else { 2742 // LDU/STU need an address with at least 4-byte alignment. 2743 if (Alignment < 4) 2744 return false; 2745 2746 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2747 return false; 2748 } 2749 2750 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2751 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2752 // sext i32 to i64 when addr mode is r+i. 2753 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2754 LD->getExtensionType() == ISD::SEXTLOAD && 2755 isa<ConstantSDNode>(Offset)) 2756 return false; 2757 } 2758 2759 AM = ISD::PRE_INC; 2760 return true; 2761 } 2762 2763 //===----------------------------------------------------------------------===// 2764 // LowerOperation implementation 2765 //===----------------------------------------------------------------------===// 2766 2767 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2768 /// and LoOpFlags to the target MO flags. 2769 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2770 unsigned &HiOpFlags, unsigned &LoOpFlags, 2771 const GlobalValue *GV = nullptr) { 2772 HiOpFlags = PPCII::MO_HA; 2773 LoOpFlags = PPCII::MO_LO; 2774 2775 // Don't use the pic base if not in PIC relocation model. 2776 if (IsPIC) { 2777 HiOpFlags |= PPCII::MO_PIC_FLAG; 2778 LoOpFlags |= PPCII::MO_PIC_FLAG; 2779 } 2780 } 2781 2782 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2783 SelectionDAG &DAG) { 2784 SDLoc DL(HiPart); 2785 EVT PtrVT = HiPart.getValueType(); 2786 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2787 2788 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2789 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2790 2791 // With PIC, the first instruction is actually "GR+hi(&G)". 2792 if (isPIC) 2793 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2794 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2795 2796 // Generate non-pic code that has direct accesses to the constant pool. 2797 // The address of the global is just (hi(&g)+lo(&g)). 2798 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2799 } 2800 2801 static void setUsesTOCBasePtr(MachineFunction &MF) { 2802 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2803 FuncInfo->setUsesTOCBasePtr(); 2804 } 2805 2806 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2807 setUsesTOCBasePtr(DAG.getMachineFunction()); 2808 } 2809 2810 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2811 SDValue GA) const { 2812 const bool Is64Bit = Subtarget.isPPC64(); 2813 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2814 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2815 : Subtarget.isAIXABI() 2816 ? DAG.getRegister(PPC::R2, VT) 2817 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2818 SDValue Ops[] = { GA, Reg }; 2819 return DAG.getMemIntrinsicNode( 2820 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2821 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2822 MachineMemOperand::MOLoad); 2823 } 2824 2825 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2826 SelectionDAG &DAG) const { 2827 EVT PtrVT = Op.getValueType(); 2828 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2829 const Constant *C = CP->getConstVal(); 2830 2831 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2832 // The actual address of the GlobalValue is stored in the TOC. 2833 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2834 if (Subtarget.isUsingPCRelativeCalls()) { 2835 SDLoc DL(CP); 2836 EVT Ty = getPointerTy(DAG.getDataLayout()); 2837 SDValue ConstPool = DAG.getTargetConstantPool( 2838 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2839 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2840 } 2841 setUsesTOCBasePtr(DAG); 2842 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2843 return getTOCEntry(DAG, SDLoc(CP), GA); 2844 } 2845 2846 unsigned MOHiFlag, MOLoFlag; 2847 bool IsPIC = isPositionIndependent(); 2848 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2849 2850 if (IsPIC && Subtarget.isSVR4ABI()) { 2851 SDValue GA = 2852 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2853 return getTOCEntry(DAG, SDLoc(CP), GA); 2854 } 2855 2856 SDValue CPIHi = 2857 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2858 SDValue CPILo = 2859 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2860 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2861 } 2862 2863 // For 64-bit PowerPC, prefer the more compact relative encodings. 2864 // This trades 32 bits per jump table entry for one or two instructions 2865 // on the jump site. 2866 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2867 if (isJumpTableRelative()) 2868 return MachineJumpTableInfo::EK_LabelDifference32; 2869 2870 return TargetLowering::getJumpTableEncoding(); 2871 } 2872 2873 bool PPCTargetLowering::isJumpTableRelative() const { 2874 if (UseAbsoluteJumpTables) 2875 return false; 2876 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2877 return true; 2878 return TargetLowering::isJumpTableRelative(); 2879 } 2880 2881 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2882 SelectionDAG &DAG) const { 2883 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2884 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2885 2886 switch (getTargetMachine().getCodeModel()) { 2887 case CodeModel::Small: 2888 case CodeModel::Medium: 2889 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2890 default: 2891 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2892 getPointerTy(DAG.getDataLayout())); 2893 } 2894 } 2895 2896 const MCExpr * 2897 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2898 unsigned JTI, 2899 MCContext &Ctx) const { 2900 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2901 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2902 2903 switch (getTargetMachine().getCodeModel()) { 2904 case CodeModel::Small: 2905 case CodeModel::Medium: 2906 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2907 default: 2908 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2909 } 2910 } 2911 2912 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2913 EVT PtrVT = Op.getValueType(); 2914 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2915 2916 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2917 if (Subtarget.isUsingPCRelativeCalls()) { 2918 SDLoc DL(JT); 2919 EVT Ty = getPointerTy(DAG.getDataLayout()); 2920 SDValue GA = 2921 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2922 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2923 return MatAddr; 2924 } 2925 2926 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2927 // The actual address of the GlobalValue is stored in the TOC. 2928 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2929 setUsesTOCBasePtr(DAG); 2930 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2931 return getTOCEntry(DAG, SDLoc(JT), GA); 2932 } 2933 2934 unsigned MOHiFlag, MOLoFlag; 2935 bool IsPIC = isPositionIndependent(); 2936 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2937 2938 if (IsPIC && Subtarget.isSVR4ABI()) { 2939 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2940 PPCII::MO_PIC_FLAG); 2941 return getTOCEntry(DAG, SDLoc(GA), GA); 2942 } 2943 2944 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2945 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2946 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2947 } 2948 2949 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2950 SelectionDAG &DAG) const { 2951 EVT PtrVT = Op.getValueType(); 2952 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2953 const BlockAddress *BA = BASDN->getBlockAddress(); 2954 2955 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2956 if (Subtarget.isUsingPCRelativeCalls()) { 2957 SDLoc DL(BASDN); 2958 EVT Ty = getPointerTy(DAG.getDataLayout()); 2959 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2960 PPCII::MO_PCREL_FLAG); 2961 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2962 return MatAddr; 2963 } 2964 2965 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2966 // The actual BlockAddress is stored in the TOC. 2967 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2968 setUsesTOCBasePtr(DAG); 2969 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2970 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2971 } 2972 2973 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2974 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2975 return getTOCEntry( 2976 DAG, SDLoc(BASDN), 2977 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2978 2979 unsigned MOHiFlag, MOLoFlag; 2980 bool IsPIC = isPositionIndependent(); 2981 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2982 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2983 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2984 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2985 } 2986 2987 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2988 SelectionDAG &DAG) const { 2989 // FIXME: TLS addresses currently use medium model code sequences, 2990 // which is the most useful form. Eventually support for small and 2991 // large models could be added if users need it, at the cost of 2992 // additional complexity. 2993 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 2994 report_fatal_error("Thread local storage is not supported with pc-relative" 2995 " addressing - please compile with -mno-pcrel"); 2996 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2997 if (DAG.getTarget().useEmulatedTLS()) 2998 return LowerToTLSEmulatedModel(GA, DAG); 2999 3000 SDLoc dl(GA); 3001 const GlobalValue *GV = GA->getGlobal(); 3002 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3003 bool is64bit = Subtarget.isPPC64(); 3004 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3005 PICLevel::Level picLevel = M->getPICLevel(); 3006 3007 const TargetMachine &TM = getTargetMachine(); 3008 TLSModel::Model Model = TM.getTLSModel(GV); 3009 3010 if (Model == TLSModel::LocalExec) { 3011 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3012 PPCII::MO_TPREL_HA); 3013 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3014 PPCII::MO_TPREL_LO); 3015 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3016 : DAG.getRegister(PPC::R2, MVT::i32); 3017 3018 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3019 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3020 } 3021 3022 if (Model == TLSModel::InitialExec) { 3023 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3024 SDValue TGA = DAG.getTargetGlobalAddress( 3025 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3026 SDValue TGATLS = DAG.getTargetGlobalAddress( 3027 GV, dl, PtrVT, 0, 3028 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3029 SDValue TPOffset; 3030 if (IsPCRel) { 3031 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3032 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3033 MachinePointerInfo()); 3034 } else { 3035 SDValue GOTPtr; 3036 if (is64bit) { 3037 setUsesTOCBasePtr(DAG); 3038 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3039 GOTPtr = 3040 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3041 } else { 3042 if (!TM.isPositionIndependent()) 3043 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3044 else if (picLevel == PICLevel::SmallPIC) 3045 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3046 else 3047 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3048 } 3049 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3050 } 3051 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3052 } 3053 3054 if (Model == TLSModel::GeneralDynamic) { 3055 if (Subtarget.isUsingPCRelativeCalls()) { 3056 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3057 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3058 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3059 } 3060 3061 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3062 SDValue GOTPtr; 3063 if (is64bit) { 3064 setUsesTOCBasePtr(DAG); 3065 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3066 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3067 GOTReg, TGA); 3068 } else { 3069 if (picLevel == PICLevel::SmallPIC) 3070 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3071 else 3072 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3073 } 3074 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3075 GOTPtr, TGA, TGA); 3076 } 3077 3078 if (Model == TLSModel::LocalDynamic) { 3079 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3080 SDValue GOTPtr; 3081 if (is64bit) { 3082 setUsesTOCBasePtr(DAG); 3083 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3084 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3085 GOTReg, TGA); 3086 } else { 3087 if (picLevel == PICLevel::SmallPIC) 3088 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3089 else 3090 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3091 } 3092 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3093 PtrVT, GOTPtr, TGA, TGA); 3094 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3095 PtrVT, TLSAddr, TGA); 3096 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3097 } 3098 3099 llvm_unreachable("Unknown TLS model!"); 3100 } 3101 3102 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3103 SelectionDAG &DAG) const { 3104 EVT PtrVT = Op.getValueType(); 3105 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3106 SDLoc DL(GSDN); 3107 const GlobalValue *GV = GSDN->getGlobal(); 3108 3109 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3110 // The actual address of the GlobalValue is stored in the TOC. 3111 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3112 if (Subtarget.isUsingPCRelativeCalls()) { 3113 EVT Ty = getPointerTy(DAG.getDataLayout()); 3114 if (isAccessedAsGotIndirect(Op)) { 3115 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3116 PPCII::MO_PCREL_FLAG | 3117 PPCII::MO_GOT_FLAG); 3118 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3119 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3120 MachinePointerInfo()); 3121 return Load; 3122 } else { 3123 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3124 PPCII::MO_PCREL_FLAG); 3125 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3126 } 3127 } 3128 setUsesTOCBasePtr(DAG); 3129 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3130 return getTOCEntry(DAG, DL, GA); 3131 } 3132 3133 unsigned MOHiFlag, MOLoFlag; 3134 bool IsPIC = isPositionIndependent(); 3135 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3136 3137 if (IsPIC && Subtarget.isSVR4ABI()) { 3138 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3139 GSDN->getOffset(), 3140 PPCII::MO_PIC_FLAG); 3141 return getTOCEntry(DAG, DL, GA); 3142 } 3143 3144 SDValue GAHi = 3145 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3146 SDValue GALo = 3147 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3148 3149 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3150 } 3151 3152 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3153 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3154 SDLoc dl(Op); 3155 3156 if (Op.getValueType() == MVT::v2i64) { 3157 // When the operands themselves are v2i64 values, we need to do something 3158 // special because VSX has no underlying comparison operations for these. 3159 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3160 // Equality can be handled by casting to the legal type for Altivec 3161 // comparisons, everything else needs to be expanded. 3162 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3163 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3164 DAG.getSetCC(dl, MVT::v4i32, 3165 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3166 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3167 CC)); 3168 } 3169 3170 return SDValue(); 3171 } 3172 3173 // We handle most of these in the usual way. 3174 return Op; 3175 } 3176 3177 // If we're comparing for equality to zero, expose the fact that this is 3178 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3179 // fold the new nodes. 3180 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3181 return V; 3182 3183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3184 // Leave comparisons against 0 and -1 alone for now, since they're usually 3185 // optimized. FIXME: revisit this when we can custom lower all setcc 3186 // optimizations. 3187 if (C->isAllOnesValue() || C->isNullValue()) 3188 return SDValue(); 3189 } 3190 3191 // If we have an integer seteq/setne, turn it into a compare against zero 3192 // by xor'ing the rhs with the lhs, which is faster than setting a 3193 // condition register, reading it back out, and masking the correct bit. The 3194 // normal approach here uses sub to do this instead of xor. Using xor exposes 3195 // the result to other bit-twiddling opportunities. 3196 EVT LHSVT = Op.getOperand(0).getValueType(); 3197 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3198 EVT VT = Op.getValueType(); 3199 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3200 Op.getOperand(1)); 3201 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3202 } 3203 return SDValue(); 3204 } 3205 3206 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3207 SDNode *Node = Op.getNode(); 3208 EVT VT = Node->getValueType(0); 3209 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3210 SDValue InChain = Node->getOperand(0); 3211 SDValue VAListPtr = Node->getOperand(1); 3212 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3213 SDLoc dl(Node); 3214 3215 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3216 3217 // gpr_index 3218 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3219 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3220 InChain = GprIndex.getValue(1); 3221 3222 if (VT == MVT::i64) { 3223 // Check if GprIndex is even 3224 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3225 DAG.getConstant(1, dl, MVT::i32)); 3226 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3227 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3228 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3229 DAG.getConstant(1, dl, MVT::i32)); 3230 // Align GprIndex to be even if it isn't 3231 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3232 GprIndex); 3233 } 3234 3235 // fpr index is 1 byte after gpr 3236 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3237 DAG.getConstant(1, dl, MVT::i32)); 3238 3239 // fpr 3240 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3241 FprPtr, MachinePointerInfo(SV), MVT::i8); 3242 InChain = FprIndex.getValue(1); 3243 3244 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3245 DAG.getConstant(8, dl, MVT::i32)); 3246 3247 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3248 DAG.getConstant(4, dl, MVT::i32)); 3249 3250 // areas 3251 SDValue OverflowArea = 3252 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3253 InChain = OverflowArea.getValue(1); 3254 3255 SDValue RegSaveArea = 3256 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3257 InChain = RegSaveArea.getValue(1); 3258 3259 // select overflow_area if index > 8 3260 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3261 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3262 3263 // adjustment constant gpr_index * 4/8 3264 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3265 VT.isInteger() ? GprIndex : FprIndex, 3266 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3267 MVT::i32)); 3268 3269 // OurReg = RegSaveArea + RegConstant 3270 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3271 RegConstant); 3272 3273 // Floating types are 32 bytes into RegSaveArea 3274 if (VT.isFloatingPoint()) 3275 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3276 DAG.getConstant(32, dl, MVT::i32)); 3277 3278 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3279 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3280 VT.isInteger() ? GprIndex : FprIndex, 3281 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3282 MVT::i32)); 3283 3284 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3285 VT.isInteger() ? VAListPtr : FprPtr, 3286 MachinePointerInfo(SV), MVT::i8); 3287 3288 // determine if we should load from reg_save_area or overflow_area 3289 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3290 3291 // increase overflow_area by 4/8 if gpr/fpr > 8 3292 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3293 DAG.getConstant(VT.isInteger() ? 4 : 8, 3294 dl, MVT::i32)); 3295 3296 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3297 OverflowAreaPlusN); 3298 3299 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3300 MachinePointerInfo(), MVT::i32); 3301 3302 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3303 } 3304 3305 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3306 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3307 3308 // We have to copy the entire va_list struct: 3309 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3310 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3311 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3312 false, true, false, MachinePointerInfo(), 3313 MachinePointerInfo()); 3314 } 3315 3316 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3317 SelectionDAG &DAG) const { 3318 if (Subtarget.isAIXABI()) 3319 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3320 3321 return Op.getOperand(0); 3322 } 3323 3324 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3325 SelectionDAG &DAG) const { 3326 if (Subtarget.isAIXABI()) 3327 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3328 3329 SDValue Chain = Op.getOperand(0); 3330 SDValue Trmp = Op.getOperand(1); // trampoline 3331 SDValue FPtr = Op.getOperand(2); // nested function 3332 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3333 SDLoc dl(Op); 3334 3335 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3336 bool isPPC64 = (PtrVT == MVT::i64); 3337 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3338 3339 TargetLowering::ArgListTy Args; 3340 TargetLowering::ArgListEntry Entry; 3341 3342 Entry.Ty = IntPtrTy; 3343 Entry.Node = Trmp; Args.push_back(Entry); 3344 3345 // TrampSize == (isPPC64 ? 48 : 40); 3346 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3347 isPPC64 ? MVT::i64 : MVT::i32); 3348 Args.push_back(Entry); 3349 3350 Entry.Node = FPtr; Args.push_back(Entry); 3351 Entry.Node = Nest; Args.push_back(Entry); 3352 3353 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3354 TargetLowering::CallLoweringInfo CLI(DAG); 3355 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3356 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3357 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3358 3359 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3360 return CallResult.second; 3361 } 3362 3363 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3364 MachineFunction &MF = DAG.getMachineFunction(); 3365 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3366 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3367 3368 SDLoc dl(Op); 3369 3370 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3371 // vastart just stores the address of the VarArgsFrameIndex slot into the 3372 // memory location argument. 3373 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3374 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3375 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3376 MachinePointerInfo(SV)); 3377 } 3378 3379 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3380 // We suppose the given va_list is already allocated. 3381 // 3382 // typedef struct { 3383 // char gpr; /* index into the array of 8 GPRs 3384 // * stored in the register save area 3385 // * gpr=0 corresponds to r3, 3386 // * gpr=1 to r4, etc. 3387 // */ 3388 // char fpr; /* index into the array of 8 FPRs 3389 // * stored in the register save area 3390 // * fpr=0 corresponds to f1, 3391 // * fpr=1 to f2, etc. 3392 // */ 3393 // char *overflow_arg_area; 3394 // /* location on stack that holds 3395 // * the next overflow argument 3396 // */ 3397 // char *reg_save_area; 3398 // /* where r3:r10 and f1:f8 (if saved) 3399 // * are stored 3400 // */ 3401 // } va_list[1]; 3402 3403 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3404 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3405 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3406 PtrVT); 3407 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3408 PtrVT); 3409 3410 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3411 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3412 3413 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3414 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3415 3416 uint64_t FPROffset = 1; 3417 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3418 3419 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3420 3421 // Store first byte : number of int regs 3422 SDValue firstStore = 3423 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3424 MachinePointerInfo(SV), MVT::i8); 3425 uint64_t nextOffset = FPROffset; 3426 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3427 ConstFPROffset); 3428 3429 // Store second byte : number of float regs 3430 SDValue secondStore = 3431 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3432 MachinePointerInfo(SV, nextOffset), MVT::i8); 3433 nextOffset += StackOffset; 3434 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3435 3436 // Store second word : arguments given on stack 3437 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3438 MachinePointerInfo(SV, nextOffset)); 3439 nextOffset += FrameOffset; 3440 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3441 3442 // Store third word : arguments given in registers 3443 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3444 MachinePointerInfo(SV, nextOffset)); 3445 } 3446 3447 /// FPR - The set of FP registers that should be allocated for arguments 3448 /// on Darwin and AIX. 3449 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3450 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3451 PPC::F11, PPC::F12, PPC::F13}; 3452 3453 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3454 /// the stack. 3455 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3456 unsigned PtrByteSize) { 3457 unsigned ArgSize = ArgVT.getStoreSize(); 3458 if (Flags.isByVal()) 3459 ArgSize = Flags.getByValSize(); 3460 3461 // Round up to multiples of the pointer size, except for array members, 3462 // which are always packed. 3463 if (!Flags.isInConsecutiveRegs()) 3464 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3465 3466 return ArgSize; 3467 } 3468 3469 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3470 /// on the stack. 3471 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3472 ISD::ArgFlagsTy Flags, 3473 unsigned PtrByteSize) { 3474 Align Alignment(PtrByteSize); 3475 3476 // Altivec parameters are padded to a 16 byte boundary. 3477 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3478 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3479 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3480 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3481 Alignment = Align(16); 3482 3483 // ByVal parameters are aligned as requested. 3484 if (Flags.isByVal()) { 3485 auto BVAlign = Flags.getNonZeroByValAlign(); 3486 if (BVAlign > PtrByteSize) { 3487 if (BVAlign.value() % PtrByteSize != 0) 3488 llvm_unreachable( 3489 "ByVal alignment is not a multiple of the pointer size"); 3490 3491 Alignment = BVAlign; 3492 } 3493 } 3494 3495 // Array members are always packed to their original alignment. 3496 if (Flags.isInConsecutiveRegs()) { 3497 // If the array member was split into multiple registers, the first 3498 // needs to be aligned to the size of the full type. (Except for 3499 // ppcf128, which is only aligned as its f64 components.) 3500 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3501 Alignment = Align(OrigVT.getStoreSize()); 3502 else 3503 Alignment = Align(ArgVT.getStoreSize()); 3504 } 3505 3506 return Alignment; 3507 } 3508 3509 /// CalculateStackSlotUsed - Return whether this argument will use its 3510 /// stack slot (instead of being passed in registers). ArgOffset, 3511 /// AvailableFPRs, and AvailableVRs must hold the current argument 3512 /// position, and will be updated to account for this argument. 3513 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3514 unsigned PtrByteSize, unsigned LinkageSize, 3515 unsigned ParamAreaSize, unsigned &ArgOffset, 3516 unsigned &AvailableFPRs, 3517 unsigned &AvailableVRs) { 3518 bool UseMemory = false; 3519 3520 // Respect alignment of argument on the stack. 3521 Align Alignment = 3522 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3523 ArgOffset = alignTo(ArgOffset, Alignment); 3524 // If there's no space left in the argument save area, we must 3525 // use memory (this check also catches zero-sized arguments). 3526 if (ArgOffset >= LinkageSize + ParamAreaSize) 3527 UseMemory = true; 3528 3529 // Allocate argument on the stack. 3530 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3531 if (Flags.isInConsecutiveRegsLast()) 3532 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3533 // If we overran the argument save area, we must use memory 3534 // (this check catches arguments passed partially in memory) 3535 if (ArgOffset > LinkageSize + ParamAreaSize) 3536 UseMemory = true; 3537 3538 // However, if the argument is actually passed in an FPR or a VR, 3539 // we don't use memory after all. 3540 if (!Flags.isByVal()) { 3541 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3542 if (AvailableFPRs > 0) { 3543 --AvailableFPRs; 3544 return false; 3545 } 3546 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3547 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3548 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3549 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3550 if (AvailableVRs > 0) { 3551 --AvailableVRs; 3552 return false; 3553 } 3554 } 3555 3556 return UseMemory; 3557 } 3558 3559 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3560 /// ensure minimum alignment required for target. 3561 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3562 unsigned NumBytes) { 3563 return alignTo(NumBytes, Lowering->getStackAlign()); 3564 } 3565 3566 SDValue PPCTargetLowering::LowerFormalArguments( 3567 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3568 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3569 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3570 if (Subtarget.isAIXABI()) 3571 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3572 InVals); 3573 if (Subtarget.is64BitELFABI()) 3574 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3575 InVals); 3576 if (Subtarget.is32BitELFABI()) 3577 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3578 InVals); 3579 3580 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3581 InVals); 3582 } 3583 3584 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3585 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3586 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3587 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3588 3589 // 32-bit SVR4 ABI Stack Frame Layout: 3590 // +-----------------------------------+ 3591 // +--> | Back chain | 3592 // | +-----------------------------------+ 3593 // | | Floating-point register save area | 3594 // | +-----------------------------------+ 3595 // | | General register save area | 3596 // | +-----------------------------------+ 3597 // | | CR save word | 3598 // | +-----------------------------------+ 3599 // | | VRSAVE save word | 3600 // | +-----------------------------------+ 3601 // | | Alignment padding | 3602 // | +-----------------------------------+ 3603 // | | Vector register save area | 3604 // | +-----------------------------------+ 3605 // | | Local variable space | 3606 // | +-----------------------------------+ 3607 // | | Parameter list area | 3608 // | +-----------------------------------+ 3609 // | | LR save word | 3610 // | +-----------------------------------+ 3611 // SP--> +--- | Back chain | 3612 // +-----------------------------------+ 3613 // 3614 // Specifications: 3615 // System V Application Binary Interface PowerPC Processor Supplement 3616 // AltiVec Technology Programming Interface Manual 3617 3618 MachineFunction &MF = DAG.getMachineFunction(); 3619 MachineFrameInfo &MFI = MF.getFrameInfo(); 3620 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3621 3622 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3623 // Potential tail calls could cause overwriting of argument stack slots. 3624 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3625 (CallConv == CallingConv::Fast)); 3626 const Align PtrAlign(4); 3627 3628 // Assign locations to all of the incoming arguments. 3629 SmallVector<CCValAssign, 16> ArgLocs; 3630 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3631 *DAG.getContext()); 3632 3633 // Reserve space for the linkage area on the stack. 3634 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3635 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3636 if (useSoftFloat()) 3637 CCInfo.PreAnalyzeFormalArguments(Ins); 3638 3639 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3640 CCInfo.clearWasPPCF128(); 3641 3642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3643 CCValAssign &VA = ArgLocs[i]; 3644 3645 // Arguments stored in registers. 3646 if (VA.isRegLoc()) { 3647 const TargetRegisterClass *RC; 3648 EVT ValVT = VA.getValVT(); 3649 3650 switch (ValVT.getSimpleVT().SimpleTy) { 3651 default: 3652 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3653 case MVT::i1: 3654 case MVT::i32: 3655 RC = &PPC::GPRCRegClass; 3656 break; 3657 case MVT::f32: 3658 if (Subtarget.hasP8Vector()) 3659 RC = &PPC::VSSRCRegClass; 3660 else if (Subtarget.hasSPE()) 3661 RC = &PPC::GPRCRegClass; 3662 else 3663 RC = &PPC::F4RCRegClass; 3664 break; 3665 case MVT::f64: 3666 if (Subtarget.hasVSX()) 3667 RC = &PPC::VSFRCRegClass; 3668 else if (Subtarget.hasSPE()) 3669 // SPE passes doubles in GPR pairs. 3670 RC = &PPC::GPRCRegClass; 3671 else 3672 RC = &PPC::F8RCRegClass; 3673 break; 3674 case MVT::v16i8: 3675 case MVT::v8i16: 3676 case MVT::v4i32: 3677 RC = &PPC::VRRCRegClass; 3678 break; 3679 case MVT::v4f32: 3680 RC = &PPC::VRRCRegClass; 3681 break; 3682 case MVT::v2f64: 3683 case MVT::v2i64: 3684 RC = &PPC::VRRCRegClass; 3685 break; 3686 } 3687 3688 SDValue ArgValue; 3689 // Transform the arguments stored in physical registers into 3690 // virtual ones. 3691 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3692 assert(i + 1 < e && "No second half of double precision argument"); 3693 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3694 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3695 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3696 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3697 if (!Subtarget.isLittleEndian()) 3698 std::swap (ArgValueLo, ArgValueHi); 3699 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3700 ArgValueHi); 3701 } else { 3702 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3703 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3704 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3705 if (ValVT == MVT::i1) 3706 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3707 } 3708 3709 InVals.push_back(ArgValue); 3710 } else { 3711 // Argument stored in memory. 3712 assert(VA.isMemLoc()); 3713 3714 // Get the extended size of the argument type in stack 3715 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3716 // Get the actual size of the argument type 3717 unsigned ObjSize = VA.getValVT().getStoreSize(); 3718 unsigned ArgOffset = VA.getLocMemOffset(); 3719 // Stack objects in PPC32 are right justified. 3720 ArgOffset += ArgSize - ObjSize; 3721 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3722 3723 // Create load nodes to retrieve arguments from the stack. 3724 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3725 InVals.push_back( 3726 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3727 } 3728 } 3729 3730 // Assign locations to all of the incoming aggregate by value arguments. 3731 // Aggregates passed by value are stored in the local variable space of the 3732 // caller's stack frame, right above the parameter list area. 3733 SmallVector<CCValAssign, 16> ByValArgLocs; 3734 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3735 ByValArgLocs, *DAG.getContext()); 3736 3737 // Reserve stack space for the allocations in CCInfo. 3738 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3739 3740 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3741 3742 // Area that is at least reserved in the caller of this function. 3743 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3744 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3745 3746 // Set the size that is at least reserved in caller of this function. Tail 3747 // call optimized function's reserved stack space needs to be aligned so that 3748 // taking the difference between two stack areas will result in an aligned 3749 // stack. 3750 MinReservedArea = 3751 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3752 FuncInfo->setMinReservedArea(MinReservedArea); 3753 3754 SmallVector<SDValue, 8> MemOps; 3755 3756 // If the function takes variable number of arguments, make a frame index for 3757 // the start of the first vararg value... for expansion of llvm.va_start. 3758 if (isVarArg) { 3759 static const MCPhysReg GPArgRegs[] = { 3760 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3761 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3762 }; 3763 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3764 3765 static const MCPhysReg FPArgRegs[] = { 3766 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3767 PPC::F8 3768 }; 3769 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3770 3771 if (useSoftFloat() || hasSPE()) 3772 NumFPArgRegs = 0; 3773 3774 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3775 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3776 3777 // Make room for NumGPArgRegs and NumFPArgRegs. 3778 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3779 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3780 3781 FuncInfo->setVarArgsStackOffset( 3782 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3783 CCInfo.getNextStackOffset(), true)); 3784 3785 FuncInfo->setVarArgsFrameIndex( 3786 MFI.CreateStackObject(Depth, Align(8), false)); 3787 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3788 3789 // The fixed integer arguments of a variadic function are stored to the 3790 // VarArgsFrameIndex on the stack so that they may be loaded by 3791 // dereferencing the result of va_next. 3792 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3793 // Get an existing live-in vreg, or add a new one. 3794 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3795 if (!VReg) 3796 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3797 3798 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3799 SDValue Store = 3800 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3801 MemOps.push_back(Store); 3802 // Increment the address by four for the next argument to store 3803 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3804 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3805 } 3806 3807 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3808 // is set. 3809 // The double arguments are stored to the VarArgsFrameIndex 3810 // on the stack. 3811 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3812 // Get an existing live-in vreg, or add a new one. 3813 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3814 if (!VReg) 3815 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3816 3817 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3818 SDValue Store = 3819 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3820 MemOps.push_back(Store); 3821 // Increment the address by eight for the next argument to store 3822 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3823 PtrVT); 3824 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3825 } 3826 } 3827 3828 if (!MemOps.empty()) 3829 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3830 3831 return Chain; 3832 } 3833 3834 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3835 // value to MVT::i64 and then truncate to the correct register size. 3836 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3837 EVT ObjectVT, SelectionDAG &DAG, 3838 SDValue ArgVal, 3839 const SDLoc &dl) const { 3840 if (Flags.isSExt()) 3841 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3842 DAG.getValueType(ObjectVT)); 3843 else if (Flags.isZExt()) 3844 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3845 DAG.getValueType(ObjectVT)); 3846 3847 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3848 } 3849 3850 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3851 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3852 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3853 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3854 // TODO: add description of PPC stack frame format, or at least some docs. 3855 // 3856 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3857 bool isLittleEndian = Subtarget.isLittleEndian(); 3858 MachineFunction &MF = DAG.getMachineFunction(); 3859 MachineFrameInfo &MFI = MF.getFrameInfo(); 3860 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3861 3862 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3863 "fastcc not supported on varargs functions"); 3864 3865 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3866 // Potential tail calls could cause overwriting of argument stack slots. 3867 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3868 (CallConv == CallingConv::Fast)); 3869 unsigned PtrByteSize = 8; 3870 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3871 3872 static const MCPhysReg GPR[] = { 3873 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3874 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3875 }; 3876 static const MCPhysReg VR[] = { 3877 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3878 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3879 }; 3880 3881 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3882 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3883 const unsigned Num_VR_Regs = array_lengthof(VR); 3884 3885 // Do a first pass over the arguments to determine whether the ABI 3886 // guarantees that our caller has allocated the parameter save area 3887 // on its stack frame. In the ELFv1 ABI, this is always the case; 3888 // in the ELFv2 ABI, it is true if this is a vararg function or if 3889 // any parameter is located in a stack slot. 3890 3891 bool HasParameterArea = !isELFv2ABI || isVarArg; 3892 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3893 unsigned NumBytes = LinkageSize; 3894 unsigned AvailableFPRs = Num_FPR_Regs; 3895 unsigned AvailableVRs = Num_VR_Regs; 3896 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3897 if (Ins[i].Flags.isNest()) 3898 continue; 3899 3900 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3901 PtrByteSize, LinkageSize, ParamAreaSize, 3902 NumBytes, AvailableFPRs, AvailableVRs)) 3903 HasParameterArea = true; 3904 } 3905 3906 // Add DAG nodes to load the arguments or copy them out of registers. On 3907 // entry to a function on PPC, the arguments start after the linkage area, 3908 // although the first ones are often in registers. 3909 3910 unsigned ArgOffset = LinkageSize; 3911 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3912 SmallVector<SDValue, 8> MemOps; 3913 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3914 unsigned CurArgIdx = 0; 3915 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3916 SDValue ArgVal; 3917 bool needsLoad = false; 3918 EVT ObjectVT = Ins[ArgNo].VT; 3919 EVT OrigVT = Ins[ArgNo].ArgVT; 3920 unsigned ObjSize = ObjectVT.getStoreSize(); 3921 unsigned ArgSize = ObjSize; 3922 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3923 if (Ins[ArgNo].isOrigArg()) { 3924 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3925 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3926 } 3927 // We re-align the argument offset for each argument, except when using the 3928 // fast calling convention, when we need to make sure we do that only when 3929 // we'll actually use a stack slot. 3930 unsigned CurArgOffset; 3931 Align Alignment; 3932 auto ComputeArgOffset = [&]() { 3933 /* Respect alignment of argument on the stack. */ 3934 Alignment = 3935 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3936 ArgOffset = alignTo(ArgOffset, Alignment); 3937 CurArgOffset = ArgOffset; 3938 }; 3939 3940 if (CallConv != CallingConv::Fast) { 3941 ComputeArgOffset(); 3942 3943 /* Compute GPR index associated with argument offset. */ 3944 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3945 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3946 } 3947 3948 // FIXME the codegen can be much improved in some cases. 3949 // We do not have to keep everything in memory. 3950 if (Flags.isByVal()) { 3951 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3952 3953 if (CallConv == CallingConv::Fast) 3954 ComputeArgOffset(); 3955 3956 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3957 ObjSize = Flags.getByValSize(); 3958 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3959 // Empty aggregate parameters do not take up registers. Examples: 3960 // struct { } a; 3961 // union { } b; 3962 // int c[0]; 3963 // etc. However, we have to provide a place-holder in InVals, so 3964 // pretend we have an 8-byte item at the current address for that 3965 // purpose. 3966 if (!ObjSize) { 3967 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3968 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3969 InVals.push_back(FIN); 3970 continue; 3971 } 3972 3973 // Create a stack object covering all stack doublewords occupied 3974 // by the argument. If the argument is (fully or partially) on 3975 // the stack, or if the argument is fully in registers but the 3976 // caller has allocated the parameter save anyway, we can refer 3977 // directly to the caller's stack frame. Otherwise, create a 3978 // local copy in our own frame. 3979 int FI; 3980 if (HasParameterArea || 3981 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3982 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3983 else 3984 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3985 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3986 3987 // Handle aggregates smaller than 8 bytes. 3988 if (ObjSize < PtrByteSize) { 3989 // The value of the object is its address, which differs from the 3990 // address of the enclosing doubleword on big-endian systems. 3991 SDValue Arg = FIN; 3992 if (!isLittleEndian) { 3993 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3994 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3995 } 3996 InVals.push_back(Arg); 3997 3998 if (GPR_idx != Num_GPR_Regs) { 3999 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4000 FuncInfo->addLiveInAttr(VReg, Flags); 4001 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4002 SDValue Store; 4003 4004 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4005 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4006 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4007 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4008 MachinePointerInfo(&*FuncArg), ObjType); 4009 } else { 4010 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4011 // store the whole register as-is to the parameter save area 4012 // slot. 4013 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4014 MachinePointerInfo(&*FuncArg)); 4015 } 4016 4017 MemOps.push_back(Store); 4018 } 4019 // Whether we copied from a register or not, advance the offset 4020 // into the parameter save area by a full doubleword. 4021 ArgOffset += PtrByteSize; 4022 continue; 4023 } 4024 4025 // The value of the object is its address, which is the address of 4026 // its first stack doubleword. 4027 InVals.push_back(FIN); 4028 4029 // Store whatever pieces of the object are in registers to memory. 4030 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4031 if (GPR_idx == Num_GPR_Regs) 4032 break; 4033 4034 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4035 FuncInfo->addLiveInAttr(VReg, Flags); 4036 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4037 SDValue Addr = FIN; 4038 if (j) { 4039 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4040 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4041 } 4042 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4043 MachinePointerInfo(&*FuncArg, j)); 4044 MemOps.push_back(Store); 4045 ++GPR_idx; 4046 } 4047 ArgOffset += ArgSize; 4048 continue; 4049 } 4050 4051 switch (ObjectVT.getSimpleVT().SimpleTy) { 4052 default: llvm_unreachable("Unhandled argument type!"); 4053 case MVT::i1: 4054 case MVT::i32: 4055 case MVT::i64: 4056 if (Flags.isNest()) { 4057 // The 'nest' parameter, if any, is passed in R11. 4058 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4059 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4060 4061 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4062 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4063 4064 break; 4065 } 4066 4067 // These can be scalar arguments or elements of an integer array type 4068 // passed directly. Clang may use those instead of "byval" aggregate 4069 // types to avoid forcing arguments to memory unnecessarily. 4070 if (GPR_idx != Num_GPR_Regs) { 4071 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4072 FuncInfo->addLiveInAttr(VReg, Flags); 4073 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4074 4075 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4076 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4077 // value to MVT::i64 and then truncate to the correct register size. 4078 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4079 } else { 4080 if (CallConv == CallingConv::Fast) 4081 ComputeArgOffset(); 4082 4083 needsLoad = true; 4084 ArgSize = PtrByteSize; 4085 } 4086 if (CallConv != CallingConv::Fast || needsLoad) 4087 ArgOffset += 8; 4088 break; 4089 4090 case MVT::f32: 4091 case MVT::f64: 4092 // These can be scalar arguments or elements of a float array type 4093 // passed directly. The latter are used to implement ELFv2 homogenous 4094 // float aggregates. 4095 if (FPR_idx != Num_FPR_Regs) { 4096 unsigned VReg; 4097 4098 if (ObjectVT == MVT::f32) 4099 VReg = MF.addLiveIn(FPR[FPR_idx], 4100 Subtarget.hasP8Vector() 4101 ? &PPC::VSSRCRegClass 4102 : &PPC::F4RCRegClass); 4103 else 4104 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4105 ? &PPC::VSFRCRegClass 4106 : &PPC::F8RCRegClass); 4107 4108 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4109 ++FPR_idx; 4110 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4111 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4112 // once we support fp <-> gpr moves. 4113 4114 // This can only ever happen in the presence of f32 array types, 4115 // since otherwise we never run out of FPRs before running out 4116 // of GPRs. 4117 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4118 FuncInfo->addLiveInAttr(VReg, Flags); 4119 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4120 4121 if (ObjectVT == MVT::f32) { 4122 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4123 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4124 DAG.getConstant(32, dl, MVT::i32)); 4125 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4126 } 4127 4128 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4129 } else { 4130 if (CallConv == CallingConv::Fast) 4131 ComputeArgOffset(); 4132 4133 needsLoad = true; 4134 } 4135 4136 // When passing an array of floats, the array occupies consecutive 4137 // space in the argument area; only round up to the next doubleword 4138 // at the end of the array. Otherwise, each float takes 8 bytes. 4139 if (CallConv != CallingConv::Fast || needsLoad) { 4140 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4141 ArgOffset += ArgSize; 4142 if (Flags.isInConsecutiveRegsLast()) 4143 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4144 } 4145 break; 4146 case MVT::v4f32: 4147 case MVT::v4i32: 4148 case MVT::v8i16: 4149 case MVT::v16i8: 4150 case MVT::v2f64: 4151 case MVT::v2i64: 4152 case MVT::v1i128: 4153 case MVT::f128: 4154 // These can be scalar arguments or elements of a vector array type 4155 // passed directly. The latter are used to implement ELFv2 homogenous 4156 // vector aggregates. 4157 if (VR_idx != Num_VR_Regs) { 4158 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4159 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4160 ++VR_idx; 4161 } else { 4162 if (CallConv == CallingConv::Fast) 4163 ComputeArgOffset(); 4164 needsLoad = true; 4165 } 4166 if (CallConv != CallingConv::Fast || needsLoad) 4167 ArgOffset += 16; 4168 break; 4169 } 4170 4171 // We need to load the argument to a virtual register if we determined 4172 // above that we ran out of physical registers of the appropriate type. 4173 if (needsLoad) { 4174 if (ObjSize < ArgSize && !isLittleEndian) 4175 CurArgOffset += ArgSize - ObjSize; 4176 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4177 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4178 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4179 } 4180 4181 InVals.push_back(ArgVal); 4182 } 4183 4184 // Area that is at least reserved in the caller of this function. 4185 unsigned MinReservedArea; 4186 if (HasParameterArea) 4187 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4188 else 4189 MinReservedArea = LinkageSize; 4190 4191 // Set the size that is at least reserved in caller of this function. Tail 4192 // call optimized functions' reserved stack space needs to be aligned so that 4193 // taking the difference between two stack areas will result in an aligned 4194 // stack. 4195 MinReservedArea = 4196 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4197 FuncInfo->setMinReservedArea(MinReservedArea); 4198 4199 // If the function takes variable number of arguments, make a frame index for 4200 // the start of the first vararg value... for expansion of llvm.va_start. 4201 // On ELFv2ABI spec, it writes: 4202 // C programs that are intended to be *portable* across different compilers 4203 // and architectures must use the header file <stdarg.h> to deal with variable 4204 // argument lists. 4205 if (isVarArg && MFI.hasVAStart()) { 4206 int Depth = ArgOffset; 4207 4208 FuncInfo->setVarArgsFrameIndex( 4209 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4210 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4211 4212 // If this function is vararg, store any remaining integer argument regs 4213 // to their spots on the stack so that they may be loaded by dereferencing 4214 // the result of va_next. 4215 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4216 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4217 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4218 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4219 SDValue Store = 4220 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4221 MemOps.push_back(Store); 4222 // Increment the address by four for the next argument to store 4223 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4224 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4225 } 4226 } 4227 4228 if (!MemOps.empty()) 4229 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4230 4231 return Chain; 4232 } 4233 4234 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4235 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4236 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4237 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4238 // TODO: add description of PPC stack frame format, or at least some docs. 4239 // 4240 MachineFunction &MF = DAG.getMachineFunction(); 4241 MachineFrameInfo &MFI = MF.getFrameInfo(); 4242 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4243 4244 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4245 bool isPPC64 = PtrVT == MVT::i64; 4246 // Potential tail calls could cause overwriting of argument stack slots. 4247 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4248 (CallConv == CallingConv::Fast)); 4249 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4250 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4251 unsigned ArgOffset = LinkageSize; 4252 // Area that is at least reserved in caller of this function. 4253 unsigned MinReservedArea = ArgOffset; 4254 4255 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4256 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4257 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4258 }; 4259 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4260 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4261 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4262 }; 4263 static const MCPhysReg VR[] = { 4264 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4265 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4266 }; 4267 4268 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4269 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4270 const unsigned Num_VR_Regs = array_lengthof( VR); 4271 4272 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4273 4274 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4275 4276 // In 32-bit non-varargs functions, the stack space for vectors is after the 4277 // stack space for non-vectors. We do not use this space unless we have 4278 // too many vectors to fit in registers, something that only occurs in 4279 // constructed examples:), but we have to walk the arglist to figure 4280 // that out...for the pathological case, compute VecArgOffset as the 4281 // start of the vector parameter area. Computing VecArgOffset is the 4282 // entire point of the following loop. 4283 unsigned VecArgOffset = ArgOffset; 4284 if (!isVarArg && !isPPC64) { 4285 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4286 ++ArgNo) { 4287 EVT ObjectVT = Ins[ArgNo].VT; 4288 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4289 4290 if (Flags.isByVal()) { 4291 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4292 unsigned ObjSize = Flags.getByValSize(); 4293 unsigned ArgSize = 4294 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4295 VecArgOffset += ArgSize; 4296 continue; 4297 } 4298 4299 switch(ObjectVT.getSimpleVT().SimpleTy) { 4300 default: llvm_unreachable("Unhandled argument type!"); 4301 case MVT::i1: 4302 case MVT::i32: 4303 case MVT::f32: 4304 VecArgOffset += 4; 4305 break; 4306 case MVT::i64: // PPC64 4307 case MVT::f64: 4308 // FIXME: We are guaranteed to be !isPPC64 at this point. 4309 // Does MVT::i64 apply? 4310 VecArgOffset += 8; 4311 break; 4312 case MVT::v4f32: 4313 case MVT::v4i32: 4314 case MVT::v8i16: 4315 case MVT::v16i8: 4316 // Nothing to do, we're only looking at Nonvector args here. 4317 break; 4318 } 4319 } 4320 } 4321 // We've found where the vector parameter area in memory is. Skip the 4322 // first 12 parameters; these don't use that memory. 4323 VecArgOffset = ((VecArgOffset+15)/16)*16; 4324 VecArgOffset += 12*16; 4325 4326 // Add DAG nodes to load the arguments or copy them out of registers. On 4327 // entry to a function on PPC, the arguments start after the linkage area, 4328 // although the first ones are often in registers. 4329 4330 SmallVector<SDValue, 8> MemOps; 4331 unsigned nAltivecParamsAtEnd = 0; 4332 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4333 unsigned CurArgIdx = 0; 4334 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4335 SDValue ArgVal; 4336 bool needsLoad = false; 4337 EVT ObjectVT = Ins[ArgNo].VT; 4338 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4339 unsigned ArgSize = ObjSize; 4340 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4341 if (Ins[ArgNo].isOrigArg()) { 4342 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4343 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4344 } 4345 unsigned CurArgOffset = ArgOffset; 4346 4347 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4348 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4349 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4350 if (isVarArg || isPPC64) { 4351 MinReservedArea = ((MinReservedArea+15)/16)*16; 4352 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4353 Flags, 4354 PtrByteSize); 4355 } else nAltivecParamsAtEnd++; 4356 } else 4357 // Calculate min reserved area. 4358 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4359 Flags, 4360 PtrByteSize); 4361 4362 // FIXME the codegen can be much improved in some cases. 4363 // We do not have to keep everything in memory. 4364 if (Flags.isByVal()) { 4365 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4366 4367 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4368 ObjSize = Flags.getByValSize(); 4369 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4370 // Objects of size 1 and 2 are right justified, everything else is 4371 // left justified. This means the memory address is adjusted forwards. 4372 if (ObjSize==1 || ObjSize==2) { 4373 CurArgOffset = CurArgOffset + (4 - ObjSize); 4374 } 4375 // The value of the object is its address. 4376 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4377 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4378 InVals.push_back(FIN); 4379 if (ObjSize==1 || ObjSize==2) { 4380 if (GPR_idx != Num_GPR_Regs) { 4381 unsigned VReg; 4382 if (isPPC64) 4383 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4384 else 4385 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4386 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4387 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4388 SDValue Store = 4389 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4390 MachinePointerInfo(&*FuncArg), ObjType); 4391 MemOps.push_back(Store); 4392 ++GPR_idx; 4393 } 4394 4395 ArgOffset += PtrByteSize; 4396 4397 continue; 4398 } 4399 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4400 // Store whatever pieces of the object are in registers 4401 // to memory. ArgOffset will be the address of the beginning 4402 // of the object. 4403 if (GPR_idx != Num_GPR_Regs) { 4404 unsigned VReg; 4405 if (isPPC64) 4406 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4407 else 4408 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4409 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4410 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4411 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4412 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4413 MachinePointerInfo(&*FuncArg, j)); 4414 MemOps.push_back(Store); 4415 ++GPR_idx; 4416 ArgOffset += PtrByteSize; 4417 } else { 4418 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4419 break; 4420 } 4421 } 4422 continue; 4423 } 4424 4425 switch (ObjectVT.getSimpleVT().SimpleTy) { 4426 default: llvm_unreachable("Unhandled argument type!"); 4427 case MVT::i1: 4428 case MVT::i32: 4429 if (!isPPC64) { 4430 if (GPR_idx != Num_GPR_Regs) { 4431 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4432 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4433 4434 if (ObjectVT == MVT::i1) 4435 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4436 4437 ++GPR_idx; 4438 } else { 4439 needsLoad = true; 4440 ArgSize = PtrByteSize; 4441 } 4442 // All int arguments reserve stack space in the Darwin ABI. 4443 ArgOffset += PtrByteSize; 4444 break; 4445 } 4446 LLVM_FALLTHROUGH; 4447 case MVT::i64: // PPC64 4448 if (GPR_idx != Num_GPR_Regs) { 4449 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4450 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4451 4452 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4453 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4454 // value to MVT::i64 and then truncate to the correct register size. 4455 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4456 4457 ++GPR_idx; 4458 } else { 4459 needsLoad = true; 4460 ArgSize = PtrByteSize; 4461 } 4462 // All int arguments reserve stack space in the Darwin ABI. 4463 ArgOffset += 8; 4464 break; 4465 4466 case MVT::f32: 4467 case MVT::f64: 4468 // Every 4 bytes of argument space consumes one of the GPRs available for 4469 // argument passing. 4470 if (GPR_idx != Num_GPR_Regs) { 4471 ++GPR_idx; 4472 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4473 ++GPR_idx; 4474 } 4475 if (FPR_idx != Num_FPR_Regs) { 4476 unsigned VReg; 4477 4478 if (ObjectVT == MVT::f32) 4479 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4480 else 4481 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4482 4483 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4484 ++FPR_idx; 4485 } else { 4486 needsLoad = true; 4487 } 4488 4489 // All FP arguments reserve stack space in the Darwin ABI. 4490 ArgOffset += isPPC64 ? 8 : ObjSize; 4491 break; 4492 case MVT::v4f32: 4493 case MVT::v4i32: 4494 case MVT::v8i16: 4495 case MVT::v16i8: 4496 // Note that vector arguments in registers don't reserve stack space, 4497 // except in varargs functions. 4498 if (VR_idx != Num_VR_Regs) { 4499 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4500 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4501 if (isVarArg) { 4502 while ((ArgOffset % 16) != 0) { 4503 ArgOffset += PtrByteSize; 4504 if (GPR_idx != Num_GPR_Regs) 4505 GPR_idx++; 4506 } 4507 ArgOffset += 16; 4508 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4509 } 4510 ++VR_idx; 4511 } else { 4512 if (!isVarArg && !isPPC64) { 4513 // Vectors go after all the nonvectors. 4514 CurArgOffset = VecArgOffset; 4515 VecArgOffset += 16; 4516 } else { 4517 // Vectors are aligned. 4518 ArgOffset = ((ArgOffset+15)/16)*16; 4519 CurArgOffset = ArgOffset; 4520 ArgOffset += 16; 4521 } 4522 needsLoad = true; 4523 } 4524 break; 4525 } 4526 4527 // We need to load the argument to a virtual register if we determined above 4528 // that we ran out of physical registers of the appropriate type. 4529 if (needsLoad) { 4530 int FI = MFI.CreateFixedObject(ObjSize, 4531 CurArgOffset + (ArgSize - ObjSize), 4532 isImmutable); 4533 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4534 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4535 } 4536 4537 InVals.push_back(ArgVal); 4538 } 4539 4540 // Allow for Altivec parameters at the end, if needed. 4541 if (nAltivecParamsAtEnd) { 4542 MinReservedArea = ((MinReservedArea+15)/16)*16; 4543 MinReservedArea += 16*nAltivecParamsAtEnd; 4544 } 4545 4546 // Area that is at least reserved in the caller of this function. 4547 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4548 4549 // Set the size that is at least reserved in caller of this function. Tail 4550 // call optimized functions' reserved stack space needs to be aligned so that 4551 // taking the difference between two stack areas will result in an aligned 4552 // stack. 4553 MinReservedArea = 4554 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4555 FuncInfo->setMinReservedArea(MinReservedArea); 4556 4557 // If the function takes variable number of arguments, make a frame index for 4558 // the start of the first vararg value... for expansion of llvm.va_start. 4559 if (isVarArg) { 4560 int Depth = ArgOffset; 4561 4562 FuncInfo->setVarArgsFrameIndex( 4563 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4564 Depth, true)); 4565 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4566 4567 // If this function is vararg, store any remaining integer argument regs 4568 // to their spots on the stack so that they may be loaded by dereferencing 4569 // the result of va_next. 4570 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4571 unsigned VReg; 4572 4573 if (isPPC64) 4574 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4575 else 4576 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4577 4578 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4579 SDValue Store = 4580 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4581 MemOps.push_back(Store); 4582 // Increment the address by four for the next argument to store 4583 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4584 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4585 } 4586 } 4587 4588 if (!MemOps.empty()) 4589 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4590 4591 return Chain; 4592 } 4593 4594 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4595 /// adjusted to accommodate the arguments for the tailcall. 4596 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4597 unsigned ParamSize) { 4598 4599 if (!isTailCall) return 0; 4600 4601 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4602 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4603 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4604 // Remember only if the new adjustment is bigger. 4605 if (SPDiff < FI->getTailCallSPDelta()) 4606 FI->setTailCallSPDelta(SPDiff); 4607 4608 return SPDiff; 4609 } 4610 4611 static bool isFunctionGlobalAddress(SDValue Callee); 4612 4613 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4614 const TargetMachine &TM) { 4615 // It does not make sense to call callsShareTOCBase() with a caller that 4616 // is PC Relative since PC Relative callers do not have a TOC. 4617 #ifndef NDEBUG 4618 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4619 assert(!STICaller->isUsingPCRelativeCalls() && 4620 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4621 #endif 4622 4623 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4624 // don't have enough information to determine if the caller and callee share 4625 // the same TOC base, so we have to pessimistically assume they don't for 4626 // correctness. 4627 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4628 if (!G) 4629 return false; 4630 4631 const GlobalValue *GV = G->getGlobal(); 4632 4633 // If the callee is preemptable, then the static linker will use a plt-stub 4634 // which saves the toc to the stack, and needs a nop after the call 4635 // instruction to convert to a toc-restore. 4636 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4637 return false; 4638 4639 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4640 // We may need a TOC restore in the situation where the caller requires a 4641 // valid TOC but the callee is PC Relative and does not. 4642 const Function *F = dyn_cast<Function>(GV); 4643 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4644 4645 // If we have an Alias we can try to get the function from there. 4646 if (Alias) { 4647 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4648 F = dyn_cast<Function>(GlobalObj); 4649 } 4650 4651 // If we still have no valid function pointer we do not have enough 4652 // information to determine if the callee uses PC Relative calls so we must 4653 // assume that it does. 4654 if (!F) 4655 return false; 4656 4657 // If the callee uses PC Relative we cannot guarantee that the callee won't 4658 // clobber the TOC of the caller and so we must assume that the two 4659 // functions do not share a TOC base. 4660 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4661 if (STICallee->isUsingPCRelativeCalls()) 4662 return false; 4663 4664 // The medium and large code models are expected to provide a sufficiently 4665 // large TOC to provide all data addressing needs of a module with a 4666 // single TOC. 4667 if (CodeModel::Medium == TM.getCodeModel() || 4668 CodeModel::Large == TM.getCodeModel()) 4669 return true; 4670 4671 // Otherwise we need to ensure callee and caller are in the same section, 4672 // since the linker may allocate multiple TOCs, and we don't know which 4673 // sections will belong to the same TOC base. 4674 if (!GV->isStrongDefinitionForLinker()) 4675 return false; 4676 4677 // Any explicitly-specified sections and section prefixes must also match. 4678 // Also, if we're using -ffunction-sections, then each function is always in 4679 // a different section (the same is true for COMDAT functions). 4680 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4681 GV->getSection() != Caller->getSection()) 4682 return false; 4683 if (const auto *F = dyn_cast<Function>(GV)) { 4684 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4685 return false; 4686 } 4687 4688 return true; 4689 } 4690 4691 static bool 4692 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4693 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4694 assert(Subtarget.is64BitELFABI()); 4695 4696 const unsigned PtrByteSize = 8; 4697 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4698 4699 static const MCPhysReg GPR[] = { 4700 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4701 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4702 }; 4703 static const MCPhysReg VR[] = { 4704 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4705 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4706 }; 4707 4708 const unsigned NumGPRs = array_lengthof(GPR); 4709 const unsigned NumFPRs = 13; 4710 const unsigned NumVRs = array_lengthof(VR); 4711 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4712 4713 unsigned NumBytes = LinkageSize; 4714 unsigned AvailableFPRs = NumFPRs; 4715 unsigned AvailableVRs = NumVRs; 4716 4717 for (const ISD::OutputArg& Param : Outs) { 4718 if (Param.Flags.isNest()) continue; 4719 4720 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4721 LinkageSize, ParamAreaSize, NumBytes, 4722 AvailableFPRs, AvailableVRs)) 4723 return true; 4724 } 4725 return false; 4726 } 4727 4728 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4729 if (CB.arg_size() != CallerFn->arg_size()) 4730 return false; 4731 4732 auto CalleeArgIter = CB.arg_begin(); 4733 auto CalleeArgEnd = CB.arg_end(); 4734 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4735 4736 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4737 const Value* CalleeArg = *CalleeArgIter; 4738 const Value* CallerArg = &(*CallerArgIter); 4739 if (CalleeArg == CallerArg) 4740 continue; 4741 4742 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4743 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4744 // } 4745 // 1st argument of callee is undef and has the same type as caller. 4746 if (CalleeArg->getType() == CallerArg->getType() && 4747 isa<UndefValue>(CalleeArg)) 4748 continue; 4749 4750 return false; 4751 } 4752 4753 return true; 4754 } 4755 4756 // Returns true if TCO is possible between the callers and callees 4757 // calling conventions. 4758 static bool 4759 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4760 CallingConv::ID CalleeCC) { 4761 // Tail calls are possible with fastcc and ccc. 4762 auto isTailCallableCC = [] (CallingConv::ID CC){ 4763 return CC == CallingConv::C || CC == CallingConv::Fast; 4764 }; 4765 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4766 return false; 4767 4768 // We can safely tail call both fastcc and ccc callees from a c calling 4769 // convention caller. If the caller is fastcc, we may have less stack space 4770 // than a non-fastcc caller with the same signature so disable tail-calls in 4771 // that case. 4772 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4773 } 4774 4775 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4776 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4777 const SmallVectorImpl<ISD::OutputArg> &Outs, 4778 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4779 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4780 4781 if (DisableSCO && !TailCallOpt) return false; 4782 4783 // Variadic argument functions are not supported. 4784 if (isVarArg) return false; 4785 4786 auto &Caller = DAG.getMachineFunction().getFunction(); 4787 // Check that the calling conventions are compatible for tco. 4788 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4789 return false; 4790 4791 // Caller contains any byval parameter is not supported. 4792 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4793 return false; 4794 4795 // Callee contains any byval parameter is not supported, too. 4796 // Note: This is a quick work around, because in some cases, e.g. 4797 // caller's stack size > callee's stack size, we are still able to apply 4798 // sibling call optimization. For example, gcc is able to do SCO for caller1 4799 // in the following example, but not for caller2. 4800 // struct test { 4801 // long int a; 4802 // char ary[56]; 4803 // } gTest; 4804 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4805 // b->a = v.a; 4806 // return 0; 4807 // } 4808 // void caller1(struct test a, struct test c, struct test *b) { 4809 // callee(gTest, b); } 4810 // void caller2(struct test *b) { callee(gTest, b); } 4811 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4812 return false; 4813 4814 // If callee and caller use different calling conventions, we cannot pass 4815 // parameters on stack since offsets for the parameter area may be different. 4816 if (Caller.getCallingConv() != CalleeCC && 4817 needStackSlotPassParameters(Subtarget, Outs)) 4818 return false; 4819 4820 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4821 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4822 // callee potentially have different TOC bases then we cannot tail call since 4823 // we need to restore the TOC pointer after the call. 4824 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4825 // We cannot guarantee this for indirect calls or calls to external functions. 4826 // When PC-Relative addressing is used, the concept of the TOC is no longer 4827 // applicable so this check is not required. 4828 // Check first for indirect calls. 4829 if (!Subtarget.isUsingPCRelativeCalls() && 4830 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4831 return false; 4832 4833 // Check if we share the TOC base. 4834 if (!Subtarget.isUsingPCRelativeCalls() && 4835 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4836 return false; 4837 4838 // TCO allows altering callee ABI, so we don't have to check further. 4839 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4840 return true; 4841 4842 if (DisableSCO) return false; 4843 4844 // If callee use the same argument list that caller is using, then we can 4845 // apply SCO on this case. If it is not, then we need to check if callee needs 4846 // stack for passing arguments. 4847 // PC Relative tail calls may not have a CallBase. 4848 // If there is no CallBase we cannot verify if we have the same argument 4849 // list so assume that we don't have the same argument list. 4850 if (CB && !hasSameArgumentList(&Caller, *CB) && 4851 needStackSlotPassParameters(Subtarget, Outs)) 4852 return false; 4853 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4854 return false; 4855 4856 return true; 4857 } 4858 4859 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4860 /// for tail call optimization. Targets which want to do tail call 4861 /// optimization should implement this function. 4862 bool 4863 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4864 CallingConv::ID CalleeCC, 4865 bool isVarArg, 4866 const SmallVectorImpl<ISD::InputArg> &Ins, 4867 SelectionDAG& DAG) const { 4868 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4869 return false; 4870 4871 // Variable argument functions are not supported. 4872 if (isVarArg) 4873 return false; 4874 4875 MachineFunction &MF = DAG.getMachineFunction(); 4876 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4877 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4878 // Functions containing by val parameters are not supported. 4879 for (unsigned i = 0; i != Ins.size(); i++) { 4880 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4881 if (Flags.isByVal()) return false; 4882 } 4883 4884 // Non-PIC/GOT tail calls are supported. 4885 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4886 return true; 4887 4888 // At the moment we can only do local tail calls (in same module, hidden 4889 // or protected) if we are generating PIC. 4890 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4891 return G->getGlobal()->hasHiddenVisibility() 4892 || G->getGlobal()->hasProtectedVisibility(); 4893 } 4894 4895 return false; 4896 } 4897 4898 /// isCallCompatibleAddress - Return the immediate to use if the specified 4899 /// 32-bit value is representable in the immediate field of a BxA instruction. 4900 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4901 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4902 if (!C) return nullptr; 4903 4904 int Addr = C->getZExtValue(); 4905 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4906 SignExtend32<26>(Addr) != Addr) 4907 return nullptr; // Top 6 bits have to be sext of immediate. 4908 4909 return DAG 4910 .getConstant( 4911 (int)C->getZExtValue() >> 2, SDLoc(Op), 4912 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4913 .getNode(); 4914 } 4915 4916 namespace { 4917 4918 struct TailCallArgumentInfo { 4919 SDValue Arg; 4920 SDValue FrameIdxOp; 4921 int FrameIdx = 0; 4922 4923 TailCallArgumentInfo() = default; 4924 }; 4925 4926 } // end anonymous namespace 4927 4928 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4929 static void StoreTailCallArgumentsToStackSlot( 4930 SelectionDAG &DAG, SDValue Chain, 4931 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4932 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4933 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4934 SDValue Arg = TailCallArgs[i].Arg; 4935 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4936 int FI = TailCallArgs[i].FrameIdx; 4937 // Store relative to framepointer. 4938 MemOpChains.push_back(DAG.getStore( 4939 Chain, dl, Arg, FIN, 4940 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4941 } 4942 } 4943 4944 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4945 /// the appropriate stack slot for the tail call optimized function call. 4946 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4947 SDValue OldRetAddr, SDValue OldFP, 4948 int SPDiff, const SDLoc &dl) { 4949 if (SPDiff) { 4950 // Calculate the new stack slot for the return address. 4951 MachineFunction &MF = DAG.getMachineFunction(); 4952 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4953 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4954 bool isPPC64 = Subtarget.isPPC64(); 4955 int SlotSize = isPPC64 ? 8 : 4; 4956 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4957 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4958 NewRetAddrLoc, true); 4959 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4960 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4961 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4962 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4963 } 4964 return Chain; 4965 } 4966 4967 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4968 /// the position of the argument. 4969 static void 4970 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4971 SDValue Arg, int SPDiff, unsigned ArgOffset, 4972 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4973 int Offset = ArgOffset + SPDiff; 4974 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4975 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4976 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4977 SDValue FIN = DAG.getFrameIndex(FI, VT); 4978 TailCallArgumentInfo Info; 4979 Info.Arg = Arg; 4980 Info.FrameIdxOp = FIN; 4981 Info.FrameIdx = FI; 4982 TailCallArguments.push_back(Info); 4983 } 4984 4985 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4986 /// stack slot. Returns the chain as result and the loaded frame pointers in 4987 /// LROpOut/FPOpout. Used when tail calling. 4988 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4989 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4990 SDValue &FPOpOut, const SDLoc &dl) const { 4991 if (SPDiff) { 4992 // Load the LR and FP stack slot for later adjusting. 4993 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4994 LROpOut = getReturnAddrFrameIndex(DAG); 4995 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4996 Chain = SDValue(LROpOut.getNode(), 1); 4997 } 4998 return Chain; 4999 } 5000 5001 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5002 /// by "Src" to address "Dst" of size "Size". Alignment information is 5003 /// specified by the specific parameter attribute. The copy will be passed as 5004 /// a byval function parameter. 5005 /// Sometimes what we are copying is the end of a larger object, the part that 5006 /// does not fit in registers. 5007 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5008 SDValue Chain, ISD::ArgFlagsTy Flags, 5009 SelectionDAG &DAG, const SDLoc &dl) { 5010 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5011 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5012 Flags.getNonZeroByValAlign(), false, false, false, 5013 MachinePointerInfo(), MachinePointerInfo()); 5014 } 5015 5016 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5017 /// tail calls. 5018 static void LowerMemOpCallTo( 5019 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5020 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5021 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5022 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5023 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5024 if (!isTailCall) { 5025 if (isVector) { 5026 SDValue StackPtr; 5027 if (isPPC64) 5028 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5029 else 5030 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5031 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5032 DAG.getConstant(ArgOffset, dl, PtrVT)); 5033 } 5034 MemOpChains.push_back( 5035 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5036 // Calculate and remember argument location. 5037 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5038 TailCallArguments); 5039 } 5040 5041 static void 5042 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5043 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5044 SDValue FPOp, 5045 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5046 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5047 // might overwrite each other in case of tail call optimization. 5048 SmallVector<SDValue, 8> MemOpChains2; 5049 // Do not flag preceding copytoreg stuff together with the following stuff. 5050 InFlag = SDValue(); 5051 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5052 MemOpChains2, dl); 5053 if (!MemOpChains2.empty()) 5054 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5055 5056 // Store the return address to the appropriate stack slot. 5057 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5058 5059 // Emit callseq_end just before tailcall node. 5060 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5061 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5062 InFlag = Chain.getValue(1); 5063 } 5064 5065 // Is this global address that of a function that can be called by name? (as 5066 // opposed to something that must hold a descriptor for an indirect call). 5067 static bool isFunctionGlobalAddress(SDValue Callee) { 5068 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5069 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5070 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5071 return false; 5072 5073 return G->getGlobal()->getValueType()->isFunctionTy(); 5074 } 5075 5076 return false; 5077 } 5078 5079 SDValue PPCTargetLowering::LowerCallResult( 5080 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5081 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5082 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5083 SmallVector<CCValAssign, 16> RVLocs; 5084 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5085 *DAG.getContext()); 5086 5087 CCRetInfo.AnalyzeCallResult( 5088 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5089 ? RetCC_PPC_Cold 5090 : RetCC_PPC); 5091 5092 // Copy all of the result registers out of their specified physreg. 5093 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5094 CCValAssign &VA = RVLocs[i]; 5095 assert(VA.isRegLoc() && "Can only return in registers!"); 5096 5097 SDValue Val; 5098 5099 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5100 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5101 InFlag); 5102 Chain = Lo.getValue(1); 5103 InFlag = Lo.getValue(2); 5104 VA = RVLocs[++i]; // skip ahead to next loc 5105 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5106 InFlag); 5107 Chain = Hi.getValue(1); 5108 InFlag = Hi.getValue(2); 5109 if (!Subtarget.isLittleEndian()) 5110 std::swap (Lo, Hi); 5111 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5112 } else { 5113 Val = DAG.getCopyFromReg(Chain, dl, 5114 VA.getLocReg(), VA.getLocVT(), InFlag); 5115 Chain = Val.getValue(1); 5116 InFlag = Val.getValue(2); 5117 } 5118 5119 switch (VA.getLocInfo()) { 5120 default: llvm_unreachable("Unknown loc info!"); 5121 case CCValAssign::Full: break; 5122 case CCValAssign::AExt: 5123 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5124 break; 5125 case CCValAssign::ZExt: 5126 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5127 DAG.getValueType(VA.getValVT())); 5128 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5129 break; 5130 case CCValAssign::SExt: 5131 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5132 DAG.getValueType(VA.getValVT())); 5133 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5134 break; 5135 } 5136 5137 InVals.push_back(Val); 5138 } 5139 5140 return Chain; 5141 } 5142 5143 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5144 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5145 // PatchPoint calls are not indirect. 5146 if (isPatchPoint) 5147 return false; 5148 5149 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5150 return false; 5151 5152 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5153 // becuase the immediate function pointer points to a descriptor instead of 5154 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5155 // pointer immediate points to the global entry point, while the BLA would 5156 // need to jump to the local entry point (see rL211174). 5157 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5158 isBLACompatibleAddress(Callee, DAG)) 5159 return false; 5160 5161 return true; 5162 } 5163 5164 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5165 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5166 return Subtarget.isAIXABI() || 5167 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5168 } 5169 5170 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5171 const Function &Caller, 5172 const SDValue &Callee, 5173 const PPCSubtarget &Subtarget, 5174 const TargetMachine &TM) { 5175 if (CFlags.IsTailCall) 5176 return PPCISD::TC_RETURN; 5177 5178 // This is a call through a function pointer. 5179 if (CFlags.IsIndirect) { 5180 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5181 // indirect calls. The save of the caller's TOC pointer to the stack will be 5182 // inserted into the DAG as part of call lowering. The restore of the TOC 5183 // pointer is modeled by using a pseudo instruction for the call opcode that 5184 // represents the 2 instruction sequence of an indirect branch and link, 5185 // immediately followed by a load of the TOC pointer from the the stack save 5186 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5187 // as it is not saved or used. 5188 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5189 : PPCISD::BCTRL; 5190 } 5191 5192 if (Subtarget.isUsingPCRelativeCalls()) { 5193 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5194 return PPCISD::CALL_NOTOC; 5195 } 5196 5197 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5198 // immediately following the call instruction if the caller and callee may 5199 // have different TOC bases. At link time if the linker determines the calls 5200 // may not share a TOC base, the call is redirected to a trampoline inserted 5201 // by the linker. The trampoline will (among other things) save the callers 5202 // TOC pointer at an ABI designated offset in the linkage area and the linker 5203 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5204 // into gpr2. 5205 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5206 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5207 : PPCISD::CALL_NOP; 5208 5209 return PPCISD::CALL; 5210 } 5211 5212 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5213 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5214 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5215 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5216 return SDValue(Dest, 0); 5217 5218 // Returns true if the callee is local, and false otherwise. 5219 auto isLocalCallee = [&]() { 5220 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5221 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5222 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5223 5224 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5225 !dyn_cast_or_null<GlobalIFunc>(GV); 5226 }; 5227 5228 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5229 // a static relocation model causes some versions of GNU LD (2.17.50, at 5230 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5231 // built with secure-PLT. 5232 bool UsePlt = 5233 Subtarget.is32BitELFABI() && !isLocalCallee() && 5234 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5235 5236 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5237 const TargetMachine &TM = Subtarget.getTargetMachine(); 5238 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5239 MCSymbolXCOFF *S = 5240 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5241 5242 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5243 return DAG.getMCSymbol(S, PtrVT); 5244 }; 5245 5246 if (isFunctionGlobalAddress(Callee)) { 5247 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5248 5249 if (Subtarget.isAIXABI()) { 5250 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5251 return getAIXFuncEntryPointSymbolSDNode(GV); 5252 } 5253 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5254 UsePlt ? PPCII::MO_PLT : 0); 5255 } 5256 5257 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5258 const char *SymName = S->getSymbol(); 5259 if (Subtarget.isAIXABI()) { 5260 // If there exists a user-declared function whose name is the same as the 5261 // ExternalSymbol's, then we pick up the user-declared version. 5262 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5263 if (const Function *F = 5264 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5265 return getAIXFuncEntryPointSymbolSDNode(F); 5266 5267 // On AIX, direct function calls reference the symbol for the function's 5268 // entry point, which is named by prepending a "." before the function's 5269 // C-linkage name. A Qualname is returned here because an external 5270 // function entry point is a csect with XTY_ER property. 5271 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5272 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5273 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5274 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5275 SectionKind::getMetadata()); 5276 return Sec->getQualNameSymbol(); 5277 }; 5278 5279 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5280 } 5281 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5282 UsePlt ? PPCII::MO_PLT : 0); 5283 } 5284 5285 // No transformation needed. 5286 assert(Callee.getNode() && "What no callee?"); 5287 return Callee; 5288 } 5289 5290 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5291 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5292 "Expected a CALLSEQ_STARTSDNode."); 5293 5294 // The last operand is the chain, except when the node has glue. If the node 5295 // has glue, then the last operand is the glue, and the chain is the second 5296 // last operand. 5297 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5298 if (LastValue.getValueType() != MVT::Glue) 5299 return LastValue; 5300 5301 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5302 } 5303 5304 // Creates the node that moves a functions address into the count register 5305 // to prepare for an indirect call instruction. 5306 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5307 SDValue &Glue, SDValue &Chain, 5308 const SDLoc &dl) { 5309 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5310 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5311 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5312 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5313 // The glue is the second value produced. 5314 Glue = Chain.getValue(1); 5315 } 5316 5317 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5318 SDValue &Glue, SDValue &Chain, 5319 SDValue CallSeqStart, 5320 const CallBase *CB, const SDLoc &dl, 5321 bool hasNest, 5322 const PPCSubtarget &Subtarget) { 5323 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5324 // entry point, but to the function descriptor (the function entry point 5325 // address is part of the function descriptor though). 5326 // The function descriptor is a three doubleword structure with the 5327 // following fields: function entry point, TOC base address and 5328 // environment pointer. 5329 // Thus for a call through a function pointer, the following actions need 5330 // to be performed: 5331 // 1. Save the TOC of the caller in the TOC save area of its stack 5332 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5333 // 2. Load the address of the function entry point from the function 5334 // descriptor. 5335 // 3. Load the TOC of the callee from the function descriptor into r2. 5336 // 4. Load the environment pointer from the function descriptor into 5337 // r11. 5338 // 5. Branch to the function entry point address. 5339 // 6. On return of the callee, the TOC of the caller needs to be 5340 // restored (this is done in FinishCall()). 5341 // 5342 // The loads are scheduled at the beginning of the call sequence, and the 5343 // register copies are flagged together to ensure that no other 5344 // operations can be scheduled in between. E.g. without flagging the 5345 // copies together, a TOC access in the caller could be scheduled between 5346 // the assignment of the callee TOC and the branch to the callee, which leads 5347 // to incorrect code. 5348 5349 // Start by loading the function address from the descriptor. 5350 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5351 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5352 ? (MachineMemOperand::MODereferenceable | 5353 MachineMemOperand::MOInvariant) 5354 : MachineMemOperand::MONone; 5355 5356 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5357 5358 // Registers used in building the DAG. 5359 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5360 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5361 5362 // Offsets of descriptor members. 5363 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5364 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5365 5366 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5367 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5368 5369 // One load for the functions entry point address. 5370 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5371 Alignment, MMOFlags); 5372 5373 // One for loading the TOC anchor for the module that contains the called 5374 // function. 5375 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5376 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5377 SDValue TOCPtr = 5378 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5379 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5380 5381 // One for loading the environment pointer. 5382 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5383 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5384 SDValue LoadEnvPtr = 5385 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5386 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5387 5388 5389 // Then copy the newly loaded TOC anchor to the TOC pointer. 5390 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5391 Chain = TOCVal.getValue(0); 5392 Glue = TOCVal.getValue(1); 5393 5394 // If the function call has an explicit 'nest' parameter, it takes the 5395 // place of the environment pointer. 5396 assert((!hasNest || !Subtarget.isAIXABI()) && 5397 "Nest parameter is not supported on AIX."); 5398 if (!hasNest) { 5399 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5400 Chain = EnvVal.getValue(0); 5401 Glue = EnvVal.getValue(1); 5402 } 5403 5404 // The rest of the indirect call sequence is the same as the non-descriptor 5405 // DAG. 5406 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5407 } 5408 5409 static void 5410 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5411 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5412 SelectionDAG &DAG, 5413 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5414 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5415 const PPCSubtarget &Subtarget) { 5416 const bool IsPPC64 = Subtarget.isPPC64(); 5417 // MVT for a general purpose register. 5418 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5419 5420 // First operand is always the chain. 5421 Ops.push_back(Chain); 5422 5423 // If it's a direct call pass the callee as the second operand. 5424 if (!CFlags.IsIndirect) 5425 Ops.push_back(Callee); 5426 else { 5427 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5428 5429 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5430 // on the stack (this would have been done in `LowerCall_64SVR4` or 5431 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5432 // represents both the indirect branch and a load that restores the TOC 5433 // pointer from the linkage area. The operand for the TOC restore is an add 5434 // of the TOC save offset to the stack pointer. This must be the second 5435 // operand: after the chain input but before any other variadic arguments. 5436 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5437 // saved or used. 5438 if (isTOCSaveRestoreRequired(Subtarget)) { 5439 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5440 5441 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5442 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5443 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5444 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5445 Ops.push_back(AddTOC); 5446 } 5447 5448 // Add the register used for the environment pointer. 5449 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5450 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5451 RegVT)); 5452 5453 5454 // Add CTR register as callee so a bctr can be emitted later. 5455 if (CFlags.IsTailCall) 5456 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5457 } 5458 5459 // If this is a tail call add stack pointer delta. 5460 if (CFlags.IsTailCall) 5461 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5462 5463 // Add argument registers to the end of the list so that they are known live 5464 // into the call. 5465 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5466 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5467 RegsToPass[i].second.getValueType())); 5468 5469 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5470 // no way to mark dependencies as implicit here. 5471 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5472 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5473 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5474 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5475 5476 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5477 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5478 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5479 5480 // Add a register mask operand representing the call-preserved registers. 5481 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5482 const uint32_t *Mask = 5483 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5484 assert(Mask && "Missing call preserved mask for calling convention"); 5485 Ops.push_back(DAG.getRegisterMask(Mask)); 5486 5487 // If the glue is valid, it is the last operand. 5488 if (Glue.getNode()) 5489 Ops.push_back(Glue); 5490 } 5491 5492 SDValue PPCTargetLowering::FinishCall( 5493 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5494 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5495 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5496 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5497 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5498 5499 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5500 Subtarget.isAIXABI()) 5501 setUsesTOCBasePtr(DAG); 5502 5503 unsigned CallOpc = 5504 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5505 Subtarget, DAG.getTarget()); 5506 5507 if (!CFlags.IsIndirect) 5508 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5509 else if (Subtarget.usesFunctionDescriptors()) 5510 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5511 dl, CFlags.HasNest, Subtarget); 5512 else 5513 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5514 5515 // Build the operand list for the call instruction. 5516 SmallVector<SDValue, 8> Ops; 5517 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5518 SPDiff, Subtarget); 5519 5520 // Emit tail call. 5521 if (CFlags.IsTailCall) { 5522 // Indirect tail call when using PC Relative calls do not have the same 5523 // constraints. 5524 assert(((Callee.getOpcode() == ISD::Register && 5525 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5526 Callee.getOpcode() == ISD::TargetExternalSymbol || 5527 Callee.getOpcode() == ISD::TargetGlobalAddress || 5528 isa<ConstantSDNode>(Callee) || 5529 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5530 "Expecting a global address, external symbol, absolute value, " 5531 "register or an indirect tail call when PC Relative calls are " 5532 "used."); 5533 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5534 assert(CallOpc == PPCISD::TC_RETURN && 5535 "Unexpected call opcode for a tail call."); 5536 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5537 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5538 } 5539 5540 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5541 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5542 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5543 Glue = Chain.getValue(1); 5544 5545 // When performing tail call optimization the callee pops its arguments off 5546 // the stack. Account for this here so these bytes can be pushed back on in 5547 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5548 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5549 getTargetMachine().Options.GuaranteedTailCallOpt) 5550 ? NumBytes 5551 : 0; 5552 5553 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5554 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5555 Glue, dl); 5556 Glue = Chain.getValue(1); 5557 5558 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5559 DAG, InVals); 5560 } 5561 5562 SDValue 5563 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5564 SmallVectorImpl<SDValue> &InVals) const { 5565 SelectionDAG &DAG = CLI.DAG; 5566 SDLoc &dl = CLI.DL; 5567 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5568 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5569 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5570 SDValue Chain = CLI.Chain; 5571 SDValue Callee = CLI.Callee; 5572 bool &isTailCall = CLI.IsTailCall; 5573 CallingConv::ID CallConv = CLI.CallConv; 5574 bool isVarArg = CLI.IsVarArg; 5575 bool isPatchPoint = CLI.IsPatchPoint; 5576 const CallBase *CB = CLI.CB; 5577 5578 if (isTailCall) { 5579 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5580 isTailCall = false; 5581 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5582 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5583 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5584 else 5585 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5586 Ins, DAG); 5587 if (isTailCall) { 5588 ++NumTailCalls; 5589 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5590 ++NumSiblingCalls; 5591 5592 // PC Relative calls no longer guarantee that the callee is a Global 5593 // Address Node. The callee could be an indirect tail call in which 5594 // case the SDValue for the callee could be a load (to load the address 5595 // of a function pointer) or it may be a register copy (to move the 5596 // address of the callee from a function parameter into a virtual 5597 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5598 assert((Subtarget.isUsingPCRelativeCalls() || 5599 isa<GlobalAddressSDNode>(Callee)) && 5600 "Callee should be an llvm::Function object."); 5601 5602 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5603 << "\nTCO callee: "); 5604 LLVM_DEBUG(Callee.dump()); 5605 } 5606 } 5607 5608 if (!isTailCall && CB && CB->isMustTailCall()) 5609 report_fatal_error("failed to perform tail call elimination on a call " 5610 "site marked musttail"); 5611 5612 // When long calls (i.e. indirect calls) are always used, calls are always 5613 // made via function pointer. If we have a function name, first translate it 5614 // into a pointer. 5615 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5616 !isTailCall) 5617 Callee = LowerGlobalAddress(Callee, DAG); 5618 5619 CallFlags CFlags( 5620 CallConv, isTailCall, isVarArg, isPatchPoint, 5621 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5622 // hasNest 5623 Subtarget.is64BitELFABI() && 5624 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5625 CLI.NoMerge); 5626 5627 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5628 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5629 InVals, CB); 5630 5631 if (Subtarget.isSVR4ABI()) 5632 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5633 InVals, CB); 5634 5635 if (Subtarget.isAIXABI()) 5636 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5637 InVals, CB); 5638 5639 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5640 InVals, CB); 5641 } 5642 5643 SDValue PPCTargetLowering::LowerCall_32SVR4( 5644 SDValue Chain, SDValue Callee, CallFlags CFlags, 5645 const SmallVectorImpl<ISD::OutputArg> &Outs, 5646 const SmallVectorImpl<SDValue> &OutVals, 5647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5649 const CallBase *CB) const { 5650 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5651 // of the 32-bit SVR4 ABI stack frame layout. 5652 5653 const CallingConv::ID CallConv = CFlags.CallConv; 5654 const bool IsVarArg = CFlags.IsVarArg; 5655 const bool IsTailCall = CFlags.IsTailCall; 5656 5657 assert((CallConv == CallingConv::C || 5658 CallConv == CallingConv::Cold || 5659 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5660 5661 const Align PtrAlign(4); 5662 5663 MachineFunction &MF = DAG.getMachineFunction(); 5664 5665 // Mark this function as potentially containing a function that contains a 5666 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5667 // and restoring the callers stack pointer in this functions epilog. This is 5668 // done because by tail calling the called function might overwrite the value 5669 // in this function's (MF) stack pointer stack slot 0(SP). 5670 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5671 CallConv == CallingConv::Fast) 5672 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5673 5674 // Count how many bytes are to be pushed on the stack, including the linkage 5675 // area, parameter list area and the part of the local variable space which 5676 // contains copies of aggregates which are passed by value. 5677 5678 // Assign locations to all of the outgoing arguments. 5679 SmallVector<CCValAssign, 16> ArgLocs; 5680 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5681 5682 // Reserve space for the linkage area on the stack. 5683 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5684 PtrAlign); 5685 if (useSoftFloat()) 5686 CCInfo.PreAnalyzeCallOperands(Outs); 5687 5688 if (IsVarArg) { 5689 // Handle fixed and variable vector arguments differently. 5690 // Fixed vector arguments go into registers as long as registers are 5691 // available. Variable vector arguments always go into memory. 5692 unsigned NumArgs = Outs.size(); 5693 5694 for (unsigned i = 0; i != NumArgs; ++i) { 5695 MVT ArgVT = Outs[i].VT; 5696 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5697 bool Result; 5698 5699 if (Outs[i].IsFixed) { 5700 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5701 CCInfo); 5702 } else { 5703 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5704 ArgFlags, CCInfo); 5705 } 5706 5707 if (Result) { 5708 #ifndef NDEBUG 5709 errs() << "Call operand #" << i << " has unhandled type " 5710 << EVT(ArgVT).getEVTString() << "\n"; 5711 #endif 5712 llvm_unreachable(nullptr); 5713 } 5714 } 5715 } else { 5716 // All arguments are treated the same. 5717 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5718 } 5719 CCInfo.clearWasPPCF128(); 5720 5721 // Assign locations to all of the outgoing aggregate by value arguments. 5722 SmallVector<CCValAssign, 16> ByValArgLocs; 5723 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5724 5725 // Reserve stack space for the allocations in CCInfo. 5726 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5727 5728 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5729 5730 // Size of the linkage area, parameter list area and the part of the local 5731 // space variable where copies of aggregates which are passed by value are 5732 // stored. 5733 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5734 5735 // Calculate by how many bytes the stack has to be adjusted in case of tail 5736 // call optimization. 5737 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5738 5739 // Adjust the stack pointer for the new arguments... 5740 // These operations are automatically eliminated by the prolog/epilog pass 5741 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5742 SDValue CallSeqStart = Chain; 5743 5744 // Load the return address and frame pointer so it can be moved somewhere else 5745 // later. 5746 SDValue LROp, FPOp; 5747 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5748 5749 // Set up a copy of the stack pointer for use loading and storing any 5750 // arguments that may not fit in the registers available for argument 5751 // passing. 5752 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5753 5754 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5755 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5756 SmallVector<SDValue, 8> MemOpChains; 5757 5758 bool seenFloatArg = false; 5759 // Walk the register/memloc assignments, inserting copies/loads. 5760 // i - Tracks the index into the list of registers allocated for the call 5761 // RealArgIdx - Tracks the index into the list of actual function arguments 5762 // j - Tracks the index into the list of byval arguments 5763 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5764 i != e; 5765 ++i, ++RealArgIdx) { 5766 CCValAssign &VA = ArgLocs[i]; 5767 SDValue Arg = OutVals[RealArgIdx]; 5768 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5769 5770 if (Flags.isByVal()) { 5771 // Argument is an aggregate which is passed by value, thus we need to 5772 // create a copy of it in the local variable space of the current stack 5773 // frame (which is the stack frame of the caller) and pass the address of 5774 // this copy to the callee. 5775 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5776 CCValAssign &ByValVA = ByValArgLocs[j++]; 5777 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5778 5779 // Memory reserved in the local variable space of the callers stack frame. 5780 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5781 5782 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5783 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5784 StackPtr, PtrOff); 5785 5786 // Create a copy of the argument in the local area of the current 5787 // stack frame. 5788 SDValue MemcpyCall = 5789 CreateCopyOfByValArgument(Arg, PtrOff, 5790 CallSeqStart.getNode()->getOperand(0), 5791 Flags, DAG, dl); 5792 5793 // This must go outside the CALLSEQ_START..END. 5794 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5795 SDLoc(MemcpyCall)); 5796 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5797 NewCallSeqStart.getNode()); 5798 Chain = CallSeqStart = NewCallSeqStart; 5799 5800 // Pass the address of the aggregate copy on the stack either in a 5801 // physical register or in the parameter list area of the current stack 5802 // frame to the callee. 5803 Arg = PtrOff; 5804 } 5805 5806 // When useCRBits() is true, there can be i1 arguments. 5807 // It is because getRegisterType(MVT::i1) => MVT::i1, 5808 // and for other integer types getRegisterType() => MVT::i32. 5809 // Extend i1 and ensure callee will get i32. 5810 if (Arg.getValueType() == MVT::i1) 5811 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5812 dl, MVT::i32, Arg); 5813 5814 if (VA.isRegLoc()) { 5815 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5816 // Put argument in a physical register. 5817 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5818 bool IsLE = Subtarget.isLittleEndian(); 5819 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5820 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5821 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5822 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5823 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5824 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5825 SVal.getValue(0))); 5826 } else 5827 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5828 } else { 5829 // Put argument in the parameter list area of the current stack frame. 5830 assert(VA.isMemLoc()); 5831 unsigned LocMemOffset = VA.getLocMemOffset(); 5832 5833 if (!IsTailCall) { 5834 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5835 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5836 StackPtr, PtrOff); 5837 5838 MemOpChains.push_back( 5839 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5840 } else { 5841 // Calculate and remember argument location. 5842 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5843 TailCallArguments); 5844 } 5845 } 5846 } 5847 5848 if (!MemOpChains.empty()) 5849 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5850 5851 // Build a sequence of copy-to-reg nodes chained together with token chain 5852 // and flag operands which copy the outgoing args into the appropriate regs. 5853 SDValue InFlag; 5854 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5855 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5856 RegsToPass[i].second, InFlag); 5857 InFlag = Chain.getValue(1); 5858 } 5859 5860 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5861 // registers. 5862 if (IsVarArg) { 5863 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5864 SDValue Ops[] = { Chain, InFlag }; 5865 5866 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5867 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5868 5869 InFlag = Chain.getValue(1); 5870 } 5871 5872 if (IsTailCall) 5873 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5874 TailCallArguments); 5875 5876 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5877 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5878 } 5879 5880 // Copy an argument into memory, being careful to do this outside the 5881 // call sequence for the call to which the argument belongs. 5882 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5883 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5884 SelectionDAG &DAG, const SDLoc &dl) const { 5885 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5886 CallSeqStart.getNode()->getOperand(0), 5887 Flags, DAG, dl); 5888 // The MEMCPY must go outside the CALLSEQ_START..END. 5889 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5890 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5891 SDLoc(MemcpyCall)); 5892 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5893 NewCallSeqStart.getNode()); 5894 return NewCallSeqStart; 5895 } 5896 5897 SDValue PPCTargetLowering::LowerCall_64SVR4( 5898 SDValue Chain, SDValue Callee, CallFlags CFlags, 5899 const SmallVectorImpl<ISD::OutputArg> &Outs, 5900 const SmallVectorImpl<SDValue> &OutVals, 5901 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5902 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5903 const CallBase *CB) const { 5904 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5905 bool isLittleEndian = Subtarget.isLittleEndian(); 5906 unsigned NumOps = Outs.size(); 5907 bool IsSibCall = false; 5908 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5909 5910 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5911 unsigned PtrByteSize = 8; 5912 5913 MachineFunction &MF = DAG.getMachineFunction(); 5914 5915 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5916 IsSibCall = true; 5917 5918 // Mark this function as potentially containing a function that contains a 5919 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5920 // and restoring the callers stack pointer in this functions epilog. This is 5921 // done because by tail calling the called function might overwrite the value 5922 // in this function's (MF) stack pointer stack slot 0(SP). 5923 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5924 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5925 5926 assert(!(IsFastCall && CFlags.IsVarArg) && 5927 "fastcc not supported on varargs functions"); 5928 5929 // Count how many bytes are to be pushed on the stack, including the linkage 5930 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5931 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5932 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5933 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5934 unsigned NumBytes = LinkageSize; 5935 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5936 5937 static const MCPhysReg GPR[] = { 5938 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5939 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5940 }; 5941 static const MCPhysReg VR[] = { 5942 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5943 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5944 }; 5945 5946 const unsigned NumGPRs = array_lengthof(GPR); 5947 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5948 const unsigned NumVRs = array_lengthof(VR); 5949 5950 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5951 // can be passed to the callee in registers. 5952 // For the fast calling convention, there is another check below. 5953 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5954 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5955 if (!HasParameterArea) { 5956 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5957 unsigned AvailableFPRs = NumFPRs; 5958 unsigned AvailableVRs = NumVRs; 5959 unsigned NumBytesTmp = NumBytes; 5960 for (unsigned i = 0; i != NumOps; ++i) { 5961 if (Outs[i].Flags.isNest()) continue; 5962 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5963 PtrByteSize, LinkageSize, ParamAreaSize, 5964 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5965 HasParameterArea = true; 5966 } 5967 } 5968 5969 // When using the fast calling convention, we don't provide backing for 5970 // arguments that will be in registers. 5971 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5972 5973 // Avoid allocating parameter area for fastcc functions if all the arguments 5974 // can be passed in the registers. 5975 if (IsFastCall) 5976 HasParameterArea = false; 5977 5978 // Add up all the space actually used. 5979 for (unsigned i = 0; i != NumOps; ++i) { 5980 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5981 EVT ArgVT = Outs[i].VT; 5982 EVT OrigVT = Outs[i].ArgVT; 5983 5984 if (Flags.isNest()) 5985 continue; 5986 5987 if (IsFastCall) { 5988 if (Flags.isByVal()) { 5989 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5990 if (NumGPRsUsed > NumGPRs) 5991 HasParameterArea = true; 5992 } else { 5993 switch (ArgVT.getSimpleVT().SimpleTy) { 5994 default: llvm_unreachable("Unexpected ValueType for argument!"); 5995 case MVT::i1: 5996 case MVT::i32: 5997 case MVT::i64: 5998 if (++NumGPRsUsed <= NumGPRs) 5999 continue; 6000 break; 6001 case MVT::v4i32: 6002 case MVT::v8i16: 6003 case MVT::v16i8: 6004 case MVT::v2f64: 6005 case MVT::v2i64: 6006 case MVT::v1i128: 6007 case MVT::f128: 6008 if (++NumVRsUsed <= NumVRs) 6009 continue; 6010 break; 6011 case MVT::v4f32: 6012 if (++NumVRsUsed <= NumVRs) 6013 continue; 6014 break; 6015 case MVT::f32: 6016 case MVT::f64: 6017 if (++NumFPRsUsed <= NumFPRs) 6018 continue; 6019 break; 6020 } 6021 HasParameterArea = true; 6022 } 6023 } 6024 6025 /* Respect alignment of argument on the stack. */ 6026 auto Alignement = 6027 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6028 NumBytes = alignTo(NumBytes, Alignement); 6029 6030 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6031 if (Flags.isInConsecutiveRegsLast()) 6032 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6033 } 6034 6035 unsigned NumBytesActuallyUsed = NumBytes; 6036 6037 // In the old ELFv1 ABI, 6038 // the prolog code of the callee may store up to 8 GPR argument registers to 6039 // the stack, allowing va_start to index over them in memory if its varargs. 6040 // Because we cannot tell if this is needed on the caller side, we have to 6041 // conservatively assume that it is needed. As such, make sure we have at 6042 // least enough stack space for the caller to store the 8 GPRs. 6043 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6044 // really requires memory operands, e.g. a vararg function. 6045 if (HasParameterArea) 6046 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6047 else 6048 NumBytes = LinkageSize; 6049 6050 // Tail call needs the stack to be aligned. 6051 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6052 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6053 6054 int SPDiff = 0; 6055 6056 // Calculate by how many bytes the stack has to be adjusted in case of tail 6057 // call optimization. 6058 if (!IsSibCall) 6059 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6060 6061 // To protect arguments on the stack from being clobbered in a tail call, 6062 // force all the loads to happen before doing any other lowering. 6063 if (CFlags.IsTailCall) 6064 Chain = DAG.getStackArgumentTokenFactor(Chain); 6065 6066 // Adjust the stack pointer for the new arguments... 6067 // These operations are automatically eliminated by the prolog/epilog pass 6068 if (!IsSibCall) 6069 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6070 SDValue CallSeqStart = Chain; 6071 6072 // Load the return address and frame pointer so it can be move somewhere else 6073 // later. 6074 SDValue LROp, FPOp; 6075 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6076 6077 // Set up a copy of the stack pointer for use loading and storing any 6078 // arguments that may not fit in the registers available for argument 6079 // passing. 6080 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6081 6082 // Figure out which arguments are going to go in registers, and which in 6083 // memory. Also, if this is a vararg function, floating point operations 6084 // must be stored to our stack, and loaded into integer regs as well, if 6085 // any integer regs are available for argument passing. 6086 unsigned ArgOffset = LinkageSize; 6087 6088 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6089 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6090 6091 SmallVector<SDValue, 8> MemOpChains; 6092 for (unsigned i = 0; i != NumOps; ++i) { 6093 SDValue Arg = OutVals[i]; 6094 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6095 EVT ArgVT = Outs[i].VT; 6096 EVT OrigVT = Outs[i].ArgVT; 6097 6098 // PtrOff will be used to store the current argument to the stack if a 6099 // register cannot be found for it. 6100 SDValue PtrOff; 6101 6102 // We re-align the argument offset for each argument, except when using the 6103 // fast calling convention, when we need to make sure we do that only when 6104 // we'll actually use a stack slot. 6105 auto ComputePtrOff = [&]() { 6106 /* Respect alignment of argument on the stack. */ 6107 auto Alignment = 6108 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6109 ArgOffset = alignTo(ArgOffset, Alignment); 6110 6111 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6112 6113 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6114 }; 6115 6116 if (!IsFastCall) { 6117 ComputePtrOff(); 6118 6119 /* Compute GPR index associated with argument offset. */ 6120 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6121 GPR_idx = std::min(GPR_idx, NumGPRs); 6122 } 6123 6124 // Promote integers to 64-bit values. 6125 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6126 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6127 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6128 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6129 } 6130 6131 // FIXME memcpy is used way more than necessary. Correctness first. 6132 // Note: "by value" is code for passing a structure by value, not 6133 // basic types. 6134 if (Flags.isByVal()) { 6135 // Note: Size includes alignment padding, so 6136 // struct x { short a; char b; } 6137 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6138 // These are the proper values we need for right-justifying the 6139 // aggregate in a parameter register. 6140 unsigned Size = Flags.getByValSize(); 6141 6142 // An empty aggregate parameter takes up no storage and no 6143 // registers. 6144 if (Size == 0) 6145 continue; 6146 6147 if (IsFastCall) 6148 ComputePtrOff(); 6149 6150 // All aggregates smaller than 8 bytes must be passed right-justified. 6151 if (Size==1 || Size==2 || Size==4) { 6152 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6153 if (GPR_idx != NumGPRs) { 6154 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6155 MachinePointerInfo(), VT); 6156 MemOpChains.push_back(Load.getValue(1)); 6157 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6158 6159 ArgOffset += PtrByteSize; 6160 continue; 6161 } 6162 } 6163 6164 if (GPR_idx == NumGPRs && Size < 8) { 6165 SDValue AddPtr = PtrOff; 6166 if (!isLittleEndian) { 6167 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6168 PtrOff.getValueType()); 6169 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6170 } 6171 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6172 CallSeqStart, 6173 Flags, DAG, dl); 6174 ArgOffset += PtrByteSize; 6175 continue; 6176 } 6177 // Copy entire object into memory. There are cases where gcc-generated 6178 // code assumes it is there, even if it could be put entirely into 6179 // registers. (This is not what the doc says.) 6180 6181 // FIXME: The above statement is likely due to a misunderstanding of the 6182 // documents. All arguments must be copied into the parameter area BY 6183 // THE CALLEE in the event that the callee takes the address of any 6184 // formal argument. That has not yet been implemented. However, it is 6185 // reasonable to use the stack area as a staging area for the register 6186 // load. 6187 6188 // Skip this for small aggregates, as we will use the same slot for a 6189 // right-justified copy, below. 6190 if (Size >= 8) 6191 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6192 CallSeqStart, 6193 Flags, DAG, dl); 6194 6195 // When a register is available, pass a small aggregate right-justified. 6196 if (Size < 8 && GPR_idx != NumGPRs) { 6197 // The easiest way to get this right-justified in a register 6198 // is to copy the structure into the rightmost portion of a 6199 // local variable slot, then load the whole slot into the 6200 // register. 6201 // FIXME: The memcpy seems to produce pretty awful code for 6202 // small aggregates, particularly for packed ones. 6203 // FIXME: It would be preferable to use the slot in the 6204 // parameter save area instead of a new local variable. 6205 SDValue AddPtr = PtrOff; 6206 if (!isLittleEndian) { 6207 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6208 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6209 } 6210 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6211 CallSeqStart, 6212 Flags, DAG, dl); 6213 6214 // Load the slot into the register. 6215 SDValue Load = 6216 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6217 MemOpChains.push_back(Load.getValue(1)); 6218 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6219 6220 // Done with this argument. 6221 ArgOffset += PtrByteSize; 6222 continue; 6223 } 6224 6225 // For aggregates larger than PtrByteSize, copy the pieces of the 6226 // object that fit into registers from the parameter save area. 6227 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6228 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6229 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6230 if (GPR_idx != NumGPRs) { 6231 SDValue Load = 6232 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6233 MemOpChains.push_back(Load.getValue(1)); 6234 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6235 ArgOffset += PtrByteSize; 6236 } else { 6237 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6238 break; 6239 } 6240 } 6241 continue; 6242 } 6243 6244 switch (Arg.getSimpleValueType().SimpleTy) { 6245 default: llvm_unreachable("Unexpected ValueType for argument!"); 6246 case MVT::i1: 6247 case MVT::i32: 6248 case MVT::i64: 6249 if (Flags.isNest()) { 6250 // The 'nest' parameter, if any, is passed in R11. 6251 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6252 break; 6253 } 6254 6255 // These can be scalar arguments or elements of an integer array type 6256 // passed directly. Clang may use those instead of "byval" aggregate 6257 // types to avoid forcing arguments to memory unnecessarily. 6258 if (GPR_idx != NumGPRs) { 6259 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6260 } else { 6261 if (IsFastCall) 6262 ComputePtrOff(); 6263 6264 assert(HasParameterArea && 6265 "Parameter area must exist to pass an argument in memory."); 6266 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6267 true, CFlags.IsTailCall, false, MemOpChains, 6268 TailCallArguments, dl); 6269 if (IsFastCall) 6270 ArgOffset += PtrByteSize; 6271 } 6272 if (!IsFastCall) 6273 ArgOffset += PtrByteSize; 6274 break; 6275 case MVT::f32: 6276 case MVT::f64: { 6277 // These can be scalar arguments or elements of a float array type 6278 // passed directly. The latter are used to implement ELFv2 homogenous 6279 // float aggregates. 6280 6281 // Named arguments go into FPRs first, and once they overflow, the 6282 // remaining arguments go into GPRs and then the parameter save area. 6283 // Unnamed arguments for vararg functions always go to GPRs and 6284 // then the parameter save area. For now, put all arguments to vararg 6285 // routines always in both locations (FPR *and* GPR or stack slot). 6286 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6287 bool NeededLoad = false; 6288 6289 // First load the argument into the next available FPR. 6290 if (FPR_idx != NumFPRs) 6291 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6292 6293 // Next, load the argument into GPR or stack slot if needed. 6294 if (!NeedGPROrStack) 6295 ; 6296 else if (GPR_idx != NumGPRs && !IsFastCall) { 6297 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6298 // once we support fp <-> gpr moves. 6299 6300 // In the non-vararg case, this can only ever happen in the 6301 // presence of f32 array types, since otherwise we never run 6302 // out of FPRs before running out of GPRs. 6303 SDValue ArgVal; 6304 6305 // Double values are always passed in a single GPR. 6306 if (Arg.getValueType() != MVT::f32) { 6307 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6308 6309 // Non-array float values are extended and passed in a GPR. 6310 } else if (!Flags.isInConsecutiveRegs()) { 6311 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6312 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6313 6314 // If we have an array of floats, we collect every odd element 6315 // together with its predecessor into one GPR. 6316 } else if (ArgOffset % PtrByteSize != 0) { 6317 SDValue Lo, Hi; 6318 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6319 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6320 if (!isLittleEndian) 6321 std::swap(Lo, Hi); 6322 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6323 6324 // The final element, if even, goes into the first half of a GPR. 6325 } else if (Flags.isInConsecutiveRegsLast()) { 6326 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6327 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6328 if (!isLittleEndian) 6329 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6330 DAG.getConstant(32, dl, MVT::i32)); 6331 6332 // Non-final even elements are skipped; they will be handled 6333 // together the with subsequent argument on the next go-around. 6334 } else 6335 ArgVal = SDValue(); 6336 6337 if (ArgVal.getNode()) 6338 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6339 } else { 6340 if (IsFastCall) 6341 ComputePtrOff(); 6342 6343 // Single-precision floating-point values are mapped to the 6344 // second (rightmost) word of the stack doubleword. 6345 if (Arg.getValueType() == MVT::f32 && 6346 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6347 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6348 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6349 } 6350 6351 assert(HasParameterArea && 6352 "Parameter area must exist to pass an argument in memory."); 6353 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6354 true, CFlags.IsTailCall, false, MemOpChains, 6355 TailCallArguments, dl); 6356 6357 NeededLoad = true; 6358 } 6359 // When passing an array of floats, the array occupies consecutive 6360 // space in the argument area; only round up to the next doubleword 6361 // at the end of the array. Otherwise, each float takes 8 bytes. 6362 if (!IsFastCall || NeededLoad) { 6363 ArgOffset += (Arg.getValueType() == MVT::f32 && 6364 Flags.isInConsecutiveRegs()) ? 4 : 8; 6365 if (Flags.isInConsecutiveRegsLast()) 6366 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6367 } 6368 break; 6369 } 6370 case MVT::v4f32: 6371 case MVT::v4i32: 6372 case MVT::v8i16: 6373 case MVT::v16i8: 6374 case MVT::v2f64: 6375 case MVT::v2i64: 6376 case MVT::v1i128: 6377 case MVT::f128: 6378 // These can be scalar arguments or elements of a vector array type 6379 // passed directly. The latter are used to implement ELFv2 homogenous 6380 // vector aggregates. 6381 6382 // For a varargs call, named arguments go into VRs or on the stack as 6383 // usual; unnamed arguments always go to the stack or the corresponding 6384 // GPRs when within range. For now, we always put the value in both 6385 // locations (or even all three). 6386 if (CFlags.IsVarArg) { 6387 assert(HasParameterArea && 6388 "Parameter area must exist if we have a varargs call."); 6389 // We could elide this store in the case where the object fits 6390 // entirely in R registers. Maybe later. 6391 SDValue Store = 6392 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6393 MemOpChains.push_back(Store); 6394 if (VR_idx != NumVRs) { 6395 SDValue Load = 6396 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6397 MemOpChains.push_back(Load.getValue(1)); 6398 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6399 } 6400 ArgOffset += 16; 6401 for (unsigned i=0; i<16; i+=PtrByteSize) { 6402 if (GPR_idx == NumGPRs) 6403 break; 6404 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6405 DAG.getConstant(i, dl, PtrVT)); 6406 SDValue Load = 6407 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6408 MemOpChains.push_back(Load.getValue(1)); 6409 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6410 } 6411 break; 6412 } 6413 6414 // Non-varargs Altivec params go into VRs or on the stack. 6415 if (VR_idx != NumVRs) { 6416 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6417 } else { 6418 if (IsFastCall) 6419 ComputePtrOff(); 6420 6421 assert(HasParameterArea && 6422 "Parameter area must exist to pass an argument in memory."); 6423 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6424 true, CFlags.IsTailCall, true, MemOpChains, 6425 TailCallArguments, dl); 6426 if (IsFastCall) 6427 ArgOffset += 16; 6428 } 6429 6430 if (!IsFastCall) 6431 ArgOffset += 16; 6432 break; 6433 } 6434 } 6435 6436 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6437 "mismatch in size of parameter area"); 6438 (void)NumBytesActuallyUsed; 6439 6440 if (!MemOpChains.empty()) 6441 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6442 6443 // Check if this is an indirect call (MTCTR/BCTRL). 6444 // See prepareDescriptorIndirectCall and buildCallOperands for more 6445 // information about calls through function pointers in the 64-bit SVR4 ABI. 6446 if (CFlags.IsIndirect) { 6447 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6448 // caller in the TOC save area. 6449 if (isTOCSaveRestoreRequired(Subtarget)) { 6450 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6451 // Load r2 into a virtual register and store it to the TOC save area. 6452 setUsesTOCBasePtr(DAG); 6453 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6454 // TOC save area offset. 6455 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6456 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6457 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6458 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6459 MachinePointerInfo::getStack( 6460 DAG.getMachineFunction(), TOCSaveOffset)); 6461 } 6462 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6463 // This does not mean the MTCTR instruction must use R12; it's easier 6464 // to model this as an extra parameter, so do that. 6465 if (isELFv2ABI && !CFlags.IsPatchPoint) 6466 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6467 } 6468 6469 // Build a sequence of copy-to-reg nodes chained together with token chain 6470 // and flag operands which copy the outgoing args into the appropriate regs. 6471 SDValue InFlag; 6472 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6473 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6474 RegsToPass[i].second, InFlag); 6475 InFlag = Chain.getValue(1); 6476 } 6477 6478 if (CFlags.IsTailCall && !IsSibCall) 6479 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6480 TailCallArguments); 6481 6482 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6483 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6484 } 6485 6486 SDValue PPCTargetLowering::LowerCall_Darwin( 6487 SDValue Chain, SDValue Callee, CallFlags CFlags, 6488 const SmallVectorImpl<ISD::OutputArg> &Outs, 6489 const SmallVectorImpl<SDValue> &OutVals, 6490 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6491 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6492 const CallBase *CB) const { 6493 unsigned NumOps = Outs.size(); 6494 6495 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6496 bool isPPC64 = PtrVT == MVT::i64; 6497 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6498 6499 MachineFunction &MF = DAG.getMachineFunction(); 6500 6501 // Mark this function as potentially containing a function that contains a 6502 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6503 // and restoring the callers stack pointer in this functions epilog. This is 6504 // done because by tail calling the called function might overwrite the value 6505 // in this function's (MF) stack pointer stack slot 0(SP). 6506 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6507 CFlags.CallConv == CallingConv::Fast) 6508 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6509 6510 // Count how many bytes are to be pushed on the stack, including the linkage 6511 // area, and parameter passing area. We start with 24/48 bytes, which is 6512 // prereserved space for [SP][CR][LR][3 x unused]. 6513 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6514 unsigned NumBytes = LinkageSize; 6515 6516 // Add up all the space actually used. 6517 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6518 // they all go in registers, but we must reserve stack space for them for 6519 // possible use by the caller. In varargs or 64-bit calls, parameters are 6520 // assigned stack space in order, with padding so Altivec parameters are 6521 // 16-byte aligned. 6522 unsigned nAltivecParamsAtEnd = 0; 6523 for (unsigned i = 0; i != NumOps; ++i) { 6524 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6525 EVT ArgVT = Outs[i].VT; 6526 // Varargs Altivec parameters are padded to a 16 byte boundary. 6527 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6528 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6529 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6530 if (!CFlags.IsVarArg && !isPPC64) { 6531 // Non-varargs Altivec parameters go after all the non-Altivec 6532 // parameters; handle those later so we know how much padding we need. 6533 nAltivecParamsAtEnd++; 6534 continue; 6535 } 6536 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6537 NumBytes = ((NumBytes+15)/16)*16; 6538 } 6539 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6540 } 6541 6542 // Allow for Altivec parameters at the end, if needed. 6543 if (nAltivecParamsAtEnd) { 6544 NumBytes = ((NumBytes+15)/16)*16; 6545 NumBytes += 16*nAltivecParamsAtEnd; 6546 } 6547 6548 // The prolog code of the callee may store up to 8 GPR argument registers to 6549 // the stack, allowing va_start to index over them in memory if its varargs. 6550 // Because we cannot tell if this is needed on the caller side, we have to 6551 // conservatively assume that it is needed. As such, make sure we have at 6552 // least enough stack space for the caller to store the 8 GPRs. 6553 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6554 6555 // Tail call needs the stack to be aligned. 6556 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6557 CFlags.CallConv == CallingConv::Fast) 6558 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6559 6560 // Calculate by how many bytes the stack has to be adjusted in case of tail 6561 // call optimization. 6562 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6563 6564 // To protect arguments on the stack from being clobbered in a tail call, 6565 // force all the loads to happen before doing any other lowering. 6566 if (CFlags.IsTailCall) 6567 Chain = DAG.getStackArgumentTokenFactor(Chain); 6568 6569 // Adjust the stack pointer for the new arguments... 6570 // These operations are automatically eliminated by the prolog/epilog pass 6571 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6572 SDValue CallSeqStart = Chain; 6573 6574 // Load the return address and frame pointer so it can be move somewhere else 6575 // later. 6576 SDValue LROp, FPOp; 6577 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6578 6579 // Set up a copy of the stack pointer for use loading and storing any 6580 // arguments that may not fit in the registers available for argument 6581 // passing. 6582 SDValue StackPtr; 6583 if (isPPC64) 6584 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6585 else 6586 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6587 6588 // Figure out which arguments are going to go in registers, and which in 6589 // memory. Also, if this is a vararg function, floating point operations 6590 // must be stored to our stack, and loaded into integer regs as well, if 6591 // any integer regs are available for argument passing. 6592 unsigned ArgOffset = LinkageSize; 6593 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6594 6595 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6596 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6597 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6598 }; 6599 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6600 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6601 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6602 }; 6603 static const MCPhysReg VR[] = { 6604 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6605 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6606 }; 6607 const unsigned NumGPRs = array_lengthof(GPR_32); 6608 const unsigned NumFPRs = 13; 6609 const unsigned NumVRs = array_lengthof(VR); 6610 6611 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6612 6613 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6614 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6615 6616 SmallVector<SDValue, 8> MemOpChains; 6617 for (unsigned i = 0; i != NumOps; ++i) { 6618 SDValue Arg = OutVals[i]; 6619 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6620 6621 // PtrOff will be used to store the current argument to the stack if a 6622 // register cannot be found for it. 6623 SDValue PtrOff; 6624 6625 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6626 6627 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6628 6629 // On PPC64, promote integers to 64-bit values. 6630 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6631 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6632 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6633 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6634 } 6635 6636 // FIXME memcpy is used way more than necessary. Correctness first. 6637 // Note: "by value" is code for passing a structure by value, not 6638 // basic types. 6639 if (Flags.isByVal()) { 6640 unsigned Size = Flags.getByValSize(); 6641 // Very small objects are passed right-justified. Everything else is 6642 // passed left-justified. 6643 if (Size==1 || Size==2) { 6644 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6645 if (GPR_idx != NumGPRs) { 6646 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6647 MachinePointerInfo(), VT); 6648 MemOpChains.push_back(Load.getValue(1)); 6649 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6650 6651 ArgOffset += PtrByteSize; 6652 } else { 6653 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6654 PtrOff.getValueType()); 6655 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6656 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6657 CallSeqStart, 6658 Flags, DAG, dl); 6659 ArgOffset += PtrByteSize; 6660 } 6661 continue; 6662 } 6663 // Copy entire object into memory. There are cases where gcc-generated 6664 // code assumes it is there, even if it could be put entirely into 6665 // registers. (This is not what the doc says.) 6666 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6667 CallSeqStart, 6668 Flags, DAG, dl); 6669 6670 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6671 // copy the pieces of the object that fit into registers from the 6672 // parameter save area. 6673 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6674 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6675 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6676 if (GPR_idx != NumGPRs) { 6677 SDValue Load = 6678 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6679 MemOpChains.push_back(Load.getValue(1)); 6680 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6681 ArgOffset += PtrByteSize; 6682 } else { 6683 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6684 break; 6685 } 6686 } 6687 continue; 6688 } 6689 6690 switch (Arg.getSimpleValueType().SimpleTy) { 6691 default: llvm_unreachable("Unexpected ValueType for argument!"); 6692 case MVT::i1: 6693 case MVT::i32: 6694 case MVT::i64: 6695 if (GPR_idx != NumGPRs) { 6696 if (Arg.getValueType() == MVT::i1) 6697 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6698 6699 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6700 } else { 6701 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6702 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6703 TailCallArguments, dl); 6704 } 6705 ArgOffset += PtrByteSize; 6706 break; 6707 case MVT::f32: 6708 case MVT::f64: 6709 if (FPR_idx != NumFPRs) { 6710 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6711 6712 if (CFlags.IsVarArg) { 6713 SDValue Store = 6714 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6715 MemOpChains.push_back(Store); 6716 6717 // Float varargs are always shadowed in available integer registers 6718 if (GPR_idx != NumGPRs) { 6719 SDValue Load = 6720 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6721 MemOpChains.push_back(Load.getValue(1)); 6722 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6723 } 6724 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6725 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6726 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6727 SDValue Load = 6728 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6729 MemOpChains.push_back(Load.getValue(1)); 6730 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6731 } 6732 } else { 6733 // If we have any FPRs remaining, we may also have GPRs remaining. 6734 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6735 // GPRs. 6736 if (GPR_idx != NumGPRs) 6737 ++GPR_idx; 6738 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6739 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6740 ++GPR_idx; 6741 } 6742 } else 6743 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6744 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6745 TailCallArguments, dl); 6746 if (isPPC64) 6747 ArgOffset += 8; 6748 else 6749 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6750 break; 6751 case MVT::v4f32: 6752 case MVT::v4i32: 6753 case MVT::v8i16: 6754 case MVT::v16i8: 6755 if (CFlags.IsVarArg) { 6756 // These go aligned on the stack, or in the corresponding R registers 6757 // when within range. The Darwin PPC ABI doc claims they also go in 6758 // V registers; in fact gcc does this only for arguments that are 6759 // prototyped, not for those that match the ... We do it for all 6760 // arguments, seems to work. 6761 while (ArgOffset % 16 !=0) { 6762 ArgOffset += PtrByteSize; 6763 if (GPR_idx != NumGPRs) 6764 GPR_idx++; 6765 } 6766 // We could elide this store in the case where the object fits 6767 // entirely in R registers. Maybe later. 6768 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6769 DAG.getConstant(ArgOffset, dl, PtrVT)); 6770 SDValue Store = 6771 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6772 MemOpChains.push_back(Store); 6773 if (VR_idx != NumVRs) { 6774 SDValue Load = 6775 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6776 MemOpChains.push_back(Load.getValue(1)); 6777 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6778 } 6779 ArgOffset += 16; 6780 for (unsigned i=0; i<16; i+=PtrByteSize) { 6781 if (GPR_idx == NumGPRs) 6782 break; 6783 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6784 DAG.getConstant(i, dl, PtrVT)); 6785 SDValue Load = 6786 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6787 MemOpChains.push_back(Load.getValue(1)); 6788 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6789 } 6790 break; 6791 } 6792 6793 // Non-varargs Altivec params generally go in registers, but have 6794 // stack space allocated at the end. 6795 if (VR_idx != NumVRs) { 6796 // Doesn't have GPR space allocated. 6797 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6798 } else if (nAltivecParamsAtEnd==0) { 6799 // We are emitting Altivec params in order. 6800 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6801 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6802 TailCallArguments, dl); 6803 ArgOffset += 16; 6804 } 6805 break; 6806 } 6807 } 6808 // If all Altivec parameters fit in registers, as they usually do, 6809 // they get stack space following the non-Altivec parameters. We 6810 // don't track this here because nobody below needs it. 6811 // If there are more Altivec parameters than fit in registers emit 6812 // the stores here. 6813 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6814 unsigned j = 0; 6815 // Offset is aligned; skip 1st 12 params which go in V registers. 6816 ArgOffset = ((ArgOffset+15)/16)*16; 6817 ArgOffset += 12*16; 6818 for (unsigned i = 0; i != NumOps; ++i) { 6819 SDValue Arg = OutVals[i]; 6820 EVT ArgType = Outs[i].VT; 6821 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6822 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6823 if (++j > NumVRs) { 6824 SDValue PtrOff; 6825 // We are emitting Altivec params in order. 6826 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6827 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6828 TailCallArguments, dl); 6829 ArgOffset += 16; 6830 } 6831 } 6832 } 6833 } 6834 6835 if (!MemOpChains.empty()) 6836 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6837 6838 // On Darwin, R12 must contain the address of an indirect callee. This does 6839 // not mean the MTCTR instruction must use R12; it's easier to model this as 6840 // an extra parameter, so do that. 6841 if (CFlags.IsIndirect) { 6842 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6843 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6844 PPC::R12), Callee)); 6845 } 6846 6847 // Build a sequence of copy-to-reg nodes chained together with token chain 6848 // and flag operands which copy the outgoing args into the appropriate regs. 6849 SDValue InFlag; 6850 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6851 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6852 RegsToPass[i].second, InFlag); 6853 InFlag = Chain.getValue(1); 6854 } 6855 6856 if (CFlags.IsTailCall) 6857 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6858 TailCallArguments); 6859 6860 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6861 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6862 } 6863 6864 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6865 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6866 CCState &State) { 6867 6868 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6869 State.getMachineFunction().getSubtarget()); 6870 const bool IsPPC64 = Subtarget.isPPC64(); 6871 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6872 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6873 6874 assert((!ValVT.isInteger() || 6875 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6876 "Integer argument exceeds register size: should have been legalized"); 6877 6878 if (ValVT == MVT::f128) 6879 report_fatal_error("f128 is unimplemented on AIX."); 6880 6881 if (ArgFlags.isNest()) 6882 report_fatal_error("Nest arguments are unimplemented."); 6883 6884 if (ValVT.isVector() || LocVT.isVector()) 6885 report_fatal_error("Vector arguments are unimplemented on AIX."); 6886 6887 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6888 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6889 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6890 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6891 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6892 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6893 6894 if (ArgFlags.isByVal()) { 6895 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6896 report_fatal_error("Pass-by-value arguments with alignment greater than " 6897 "register width are not supported."); 6898 6899 const unsigned ByValSize = ArgFlags.getByValSize(); 6900 6901 // An empty aggregate parameter takes up no storage and no registers, 6902 // but needs a MemLoc for a stack slot for the formal arguments side. 6903 if (ByValSize == 0) { 6904 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6905 State.getNextStackOffset(), RegVT, 6906 LocInfo)); 6907 return false; 6908 } 6909 6910 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6911 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6912 for (const unsigned E = Offset + StackSize; Offset < E; 6913 Offset += PtrAlign.value()) { 6914 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6915 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6916 else { 6917 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6918 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6919 LocInfo)); 6920 break; 6921 } 6922 } 6923 return false; 6924 } 6925 6926 // Arguments always reserve parameter save area. 6927 switch (ValVT.SimpleTy) { 6928 default: 6929 report_fatal_error("Unhandled value type for argument."); 6930 case MVT::i64: 6931 // i64 arguments should have been split to i32 for PPC32. 6932 assert(IsPPC64 && "PPC32 should have split i64 values."); 6933 LLVM_FALLTHROUGH; 6934 case MVT::i1: 6935 case MVT::i32: { 6936 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6937 // AIX integer arguments are always passed in register width. 6938 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6939 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6940 : CCValAssign::LocInfo::ZExt; 6941 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6942 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6943 else 6944 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6945 6946 return false; 6947 } 6948 case MVT::f32: 6949 case MVT::f64: { 6950 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6951 const unsigned StoreSize = LocVT.getStoreSize(); 6952 // Floats are always 4-byte aligned in the PSA on AIX. 6953 // This includes f64 in 64-bit mode for ABI compatibility. 6954 const unsigned Offset = 6955 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6956 unsigned FReg = State.AllocateReg(FPR); 6957 if (FReg) 6958 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6959 6960 // Reserve and initialize GPRs or initialize the PSA as required. 6961 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6962 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6963 assert(FReg && "An FPR should be available when a GPR is reserved."); 6964 if (State.isVarArg()) { 6965 // Successfully reserved GPRs are only initialized for vararg calls. 6966 // Custom handling is required for: 6967 // f64 in PPC32 needs to be split into 2 GPRs. 6968 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6969 State.addLoc( 6970 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6971 } 6972 } else { 6973 // If there are insufficient GPRs, the PSA needs to be initialized. 6974 // Initialization occurs even if an FPR was initialized for 6975 // compatibility with the AIX XL compiler. The full memory for the 6976 // argument will be initialized even if a prior word is saved in GPR. 6977 // A custom memLoc is used when the argument also passes in FPR so 6978 // that the callee handling can skip over it easily. 6979 State.addLoc( 6980 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6981 LocInfo) 6982 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6983 break; 6984 } 6985 } 6986 6987 return false; 6988 } 6989 } 6990 return true; 6991 } 6992 6993 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6994 bool IsPPC64) { 6995 assert((IsPPC64 || SVT != MVT::i64) && 6996 "i64 should have been split for 32-bit codegen."); 6997 6998 switch (SVT) { 6999 default: 7000 report_fatal_error("Unexpected value type for formal argument"); 7001 case MVT::i1: 7002 case MVT::i32: 7003 case MVT::i64: 7004 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7005 case MVT::f32: 7006 return &PPC::F4RCRegClass; 7007 case MVT::f64: 7008 return &PPC::F8RCRegClass; 7009 } 7010 } 7011 7012 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7013 SelectionDAG &DAG, SDValue ArgValue, 7014 MVT LocVT, const SDLoc &dl) { 7015 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7016 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7017 7018 if (Flags.isSExt()) 7019 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7020 DAG.getValueType(ValVT)); 7021 else if (Flags.isZExt()) 7022 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7023 DAG.getValueType(ValVT)); 7024 7025 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7026 } 7027 7028 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7029 const unsigned LASize = FL->getLinkageSize(); 7030 7031 if (PPC::GPRCRegClass.contains(Reg)) { 7032 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7033 "Reg must be a valid argument register!"); 7034 return LASize + 4 * (Reg - PPC::R3); 7035 } 7036 7037 if (PPC::G8RCRegClass.contains(Reg)) { 7038 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7039 "Reg must be a valid argument register!"); 7040 return LASize + 8 * (Reg - PPC::X3); 7041 } 7042 7043 llvm_unreachable("Only general purpose registers expected."); 7044 } 7045 7046 // AIX ABI Stack Frame Layout: 7047 // 7048 // Low Memory +--------------------------------------------+ 7049 // SP +---> | Back chain | ---+ 7050 // | +--------------------------------------------+ | 7051 // | | Saved Condition Register | | 7052 // | +--------------------------------------------+ | 7053 // | | Saved Linkage Register | | 7054 // | +--------------------------------------------+ | Linkage Area 7055 // | | Reserved for compilers | | 7056 // | +--------------------------------------------+ | 7057 // | | Reserved for binders | | 7058 // | +--------------------------------------------+ | 7059 // | | Saved TOC pointer | ---+ 7060 // | +--------------------------------------------+ 7061 // | | Parameter save area | 7062 // | +--------------------------------------------+ 7063 // | | Alloca space | 7064 // | +--------------------------------------------+ 7065 // | | Local variable space | 7066 // | +--------------------------------------------+ 7067 // | | Float/int conversion temporary | 7068 // | +--------------------------------------------+ 7069 // | | Save area for AltiVec registers | 7070 // | +--------------------------------------------+ 7071 // | | AltiVec alignment padding | 7072 // | +--------------------------------------------+ 7073 // | | Save area for VRSAVE register | 7074 // | +--------------------------------------------+ 7075 // | | Save area for General Purpose registers | 7076 // | +--------------------------------------------+ 7077 // | | Save area for Floating Point registers | 7078 // | +--------------------------------------------+ 7079 // +---- | Back chain | 7080 // High Memory +--------------------------------------------+ 7081 // 7082 // Specifications: 7083 // AIX 7.2 Assembler Language Reference 7084 // Subroutine linkage convention 7085 7086 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7087 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7088 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7089 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7090 7091 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7092 CallConv == CallingConv::Fast) && 7093 "Unexpected calling convention!"); 7094 7095 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7096 report_fatal_error("Tail call support is unimplemented on AIX."); 7097 7098 if (useSoftFloat()) 7099 report_fatal_error("Soft float support is unimplemented on AIX."); 7100 7101 const PPCSubtarget &Subtarget = 7102 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7103 7104 const bool IsPPC64 = Subtarget.isPPC64(); 7105 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7106 7107 // Assign locations to all of the incoming arguments. 7108 SmallVector<CCValAssign, 16> ArgLocs; 7109 MachineFunction &MF = DAG.getMachineFunction(); 7110 MachineFrameInfo &MFI = MF.getFrameInfo(); 7111 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7112 7113 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7114 // Reserve space for the linkage area on the stack. 7115 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7116 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7117 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7118 7119 SmallVector<SDValue, 8> MemOps; 7120 7121 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7122 CCValAssign &VA = ArgLocs[I++]; 7123 MVT LocVT = VA.getLocVT(); 7124 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7125 7126 // For compatibility with the AIX XL compiler, the float args in the 7127 // parameter save area are initialized even if the argument is available 7128 // in register. The caller is required to initialize both the register 7129 // and memory, however, the callee can choose to expect it in either. 7130 // The memloc is dismissed here because the argument is retrieved from 7131 // the register. 7132 if (VA.isMemLoc() && VA.needsCustom()) 7133 continue; 7134 7135 if (Flags.isByVal() && VA.isMemLoc()) { 7136 const unsigned Size = 7137 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7138 PtrByteSize); 7139 const int FI = MF.getFrameInfo().CreateFixedObject( 7140 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7141 /* IsAliased */ true); 7142 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7143 InVals.push_back(FIN); 7144 7145 continue; 7146 } 7147 7148 if (Flags.isByVal()) { 7149 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7150 7151 const MCPhysReg ArgReg = VA.getLocReg(); 7152 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7153 7154 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7155 report_fatal_error("Over aligned byvals not supported yet."); 7156 7157 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7158 const int FI = MF.getFrameInfo().CreateFixedObject( 7159 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7160 /* IsAliased */ true); 7161 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7162 InVals.push_back(FIN); 7163 7164 // Add live ins for all the RegLocs for the same ByVal. 7165 const TargetRegisterClass *RegClass = 7166 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7167 7168 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7169 unsigned Offset) { 7170 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7171 // Since the callers side has left justified the aggregate in the 7172 // register, we can simply store the entire register into the stack 7173 // slot. 7174 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7175 // The store to the fixedstack object is needed becuase accessing a 7176 // field of the ByVal will use a gep and load. Ideally we will optimize 7177 // to extracting the value from the register directly, and elide the 7178 // stores when the arguments address is not taken, but that will need to 7179 // be future work. 7180 SDValue Store = DAG.getStore( 7181 CopyFrom.getValue(1), dl, CopyFrom, 7182 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7183 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7184 7185 MemOps.push_back(Store); 7186 }; 7187 7188 unsigned Offset = 0; 7189 HandleRegLoc(VA.getLocReg(), Offset); 7190 Offset += PtrByteSize; 7191 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7192 Offset += PtrByteSize) { 7193 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7194 "RegLocs should be for ByVal argument."); 7195 7196 const CCValAssign RL = ArgLocs[I++]; 7197 HandleRegLoc(RL.getLocReg(), Offset); 7198 } 7199 7200 if (Offset != StackSize) { 7201 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7202 "Expected MemLoc for remaining bytes."); 7203 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7204 // Consume the MemLoc.The InVal has already been emitted, so nothing 7205 // more needs to be done. 7206 ++I; 7207 } 7208 7209 continue; 7210 } 7211 7212 EVT ValVT = VA.getValVT(); 7213 if (VA.isRegLoc() && !VA.needsCustom()) { 7214 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7215 unsigned VReg = 7216 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7217 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7218 if (ValVT.isScalarInteger() && 7219 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7220 ArgValue = 7221 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7222 } 7223 InVals.push_back(ArgValue); 7224 continue; 7225 } 7226 if (VA.isMemLoc()) { 7227 const unsigned LocSize = LocVT.getStoreSize(); 7228 const unsigned ValSize = ValVT.getStoreSize(); 7229 assert((ValSize <= LocSize) && 7230 "Object size is larger than size of MemLoc"); 7231 int CurArgOffset = VA.getLocMemOffset(); 7232 // Objects are right-justified because AIX is big-endian. 7233 if (LocSize > ValSize) 7234 CurArgOffset += LocSize - ValSize; 7235 // Potential tail calls could cause overwriting of argument stack slots. 7236 const bool IsImmutable = 7237 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7238 (CallConv == CallingConv::Fast)); 7239 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7240 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7241 SDValue ArgValue = 7242 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7243 InVals.push_back(ArgValue); 7244 continue; 7245 } 7246 } 7247 7248 // On AIX a minimum of 8 words is saved to the parameter save area. 7249 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7250 // Area that is at least reserved in the caller of this function. 7251 unsigned CallerReservedArea = 7252 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7253 7254 // Set the size that is at least reserved in caller of this function. Tail 7255 // call optimized function's reserved stack space needs to be aligned so 7256 // that taking the difference between two stack areas will result in an 7257 // aligned stack. 7258 CallerReservedArea = 7259 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7260 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7261 FuncInfo->setMinReservedArea(CallerReservedArea); 7262 7263 if (isVarArg) { 7264 FuncInfo->setVarArgsFrameIndex( 7265 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7266 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7267 7268 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7269 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7270 7271 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7272 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7273 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7274 7275 // The fixed integer arguments of a variadic function are stored to the 7276 // VarArgsFrameIndex on the stack so that they may be loaded by 7277 // dereferencing the result of va_next. 7278 for (unsigned GPRIndex = 7279 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7280 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7281 7282 const unsigned VReg = 7283 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7284 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7285 7286 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7287 SDValue Store = 7288 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7289 MemOps.push_back(Store); 7290 // Increment the address for the next argument to store. 7291 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7292 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7293 } 7294 } 7295 7296 if (!MemOps.empty()) 7297 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7298 7299 return Chain; 7300 } 7301 7302 SDValue PPCTargetLowering::LowerCall_AIX( 7303 SDValue Chain, SDValue Callee, CallFlags CFlags, 7304 const SmallVectorImpl<ISD::OutputArg> &Outs, 7305 const SmallVectorImpl<SDValue> &OutVals, 7306 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7307 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7308 const CallBase *CB) const { 7309 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7310 // AIX ABI stack frame layout. 7311 7312 assert((CFlags.CallConv == CallingConv::C || 7313 CFlags.CallConv == CallingConv::Cold || 7314 CFlags.CallConv == CallingConv::Fast) && 7315 "Unexpected calling convention!"); 7316 7317 if (CFlags.IsPatchPoint) 7318 report_fatal_error("This call type is unimplemented on AIX."); 7319 7320 const PPCSubtarget& Subtarget = 7321 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7322 if (Subtarget.hasAltivec()) 7323 report_fatal_error("Altivec support is unimplemented on AIX."); 7324 7325 MachineFunction &MF = DAG.getMachineFunction(); 7326 SmallVector<CCValAssign, 16> ArgLocs; 7327 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7328 *DAG.getContext()); 7329 7330 // Reserve space for the linkage save area (LSA) on the stack. 7331 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7332 // [SP][CR][LR][2 x reserved][TOC]. 7333 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7334 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7335 const bool IsPPC64 = Subtarget.isPPC64(); 7336 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7337 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7338 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7339 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7340 7341 // The prolog code of the callee may store up to 8 GPR argument registers to 7342 // the stack, allowing va_start to index over them in memory if the callee 7343 // is variadic. 7344 // Because we cannot tell if this is needed on the caller side, we have to 7345 // conservatively assume that it is needed. As such, make sure we have at 7346 // least enough stack space for the caller to store the 8 GPRs. 7347 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7348 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7349 CCInfo.getNextStackOffset()); 7350 7351 // Adjust the stack pointer for the new arguments... 7352 // These operations are automatically eliminated by the prolog/epilog pass. 7353 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7354 SDValue CallSeqStart = Chain; 7355 7356 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7357 SmallVector<SDValue, 8> MemOpChains; 7358 7359 // Set up a copy of the stack pointer for loading and storing any 7360 // arguments that may not fit in the registers available for argument 7361 // passing. 7362 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7363 : DAG.getRegister(PPC::R1, MVT::i32); 7364 7365 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7366 const unsigned ValNo = ArgLocs[I].getValNo(); 7367 SDValue Arg = OutVals[ValNo]; 7368 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7369 7370 if (Flags.isByVal()) { 7371 const unsigned ByValSize = Flags.getByValSize(); 7372 7373 // Nothing to do for zero-sized ByVals on the caller side. 7374 if (!ByValSize) { 7375 ++I; 7376 continue; 7377 } 7378 7379 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7380 return DAG.getExtLoad( 7381 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7382 (LoadOffset != 0) 7383 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7384 : Arg, 7385 MachinePointerInfo(), VT); 7386 }; 7387 7388 unsigned LoadOffset = 0; 7389 7390 // Initialize registers, which are fully occupied by the by-val argument. 7391 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7392 SDValue Load = GetLoad(PtrVT, LoadOffset); 7393 MemOpChains.push_back(Load.getValue(1)); 7394 LoadOffset += PtrByteSize; 7395 const CCValAssign &ByValVA = ArgLocs[I++]; 7396 assert(ByValVA.getValNo() == ValNo && 7397 "Unexpected location for pass-by-value argument."); 7398 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7399 } 7400 7401 if (LoadOffset == ByValSize) 7402 continue; 7403 7404 // There must be one more loc to handle the remainder. 7405 assert(ArgLocs[I].getValNo() == ValNo && 7406 "Expected additional location for by-value argument."); 7407 7408 if (ArgLocs[I].isMemLoc()) { 7409 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7410 const CCValAssign &ByValVA = ArgLocs[I++]; 7411 ISD::ArgFlagsTy MemcpyFlags = Flags; 7412 // Only memcpy the bytes that don't pass in register. 7413 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7414 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7415 (LoadOffset != 0) 7416 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7417 : Arg, 7418 DAG.getObjectPtrOffset(dl, StackPtr, 7419 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7420 CallSeqStart, MemcpyFlags, DAG, dl); 7421 continue; 7422 } 7423 7424 // Initialize the final register residue. 7425 // Any residue that occupies the final by-val arg register must be 7426 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7427 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7428 // 2 and 1 byte loads. 7429 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7430 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7431 "Unexpected register residue for by-value argument."); 7432 SDValue ResidueVal; 7433 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7434 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7435 const MVT VT = 7436 N == 1 ? MVT::i8 7437 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7438 SDValue Load = GetLoad(VT, LoadOffset); 7439 MemOpChains.push_back(Load.getValue(1)); 7440 LoadOffset += N; 7441 Bytes += N; 7442 7443 // By-val arguments are passed left-justfied in register. 7444 // Every load here needs to be shifted, otherwise a full register load 7445 // should have been used. 7446 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7447 "Unexpected load emitted during handling of pass-by-value " 7448 "argument."); 7449 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7450 EVT ShiftAmountTy = 7451 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7452 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7453 SDValue ShiftedLoad = 7454 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7455 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7456 ShiftedLoad) 7457 : ShiftedLoad; 7458 } 7459 7460 const CCValAssign &ByValVA = ArgLocs[I++]; 7461 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7462 continue; 7463 } 7464 7465 CCValAssign &VA = ArgLocs[I++]; 7466 const MVT LocVT = VA.getLocVT(); 7467 const MVT ValVT = VA.getValVT(); 7468 7469 switch (VA.getLocInfo()) { 7470 default: 7471 report_fatal_error("Unexpected argument extension type."); 7472 case CCValAssign::Full: 7473 break; 7474 case CCValAssign::ZExt: 7475 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7476 break; 7477 case CCValAssign::SExt: 7478 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7479 break; 7480 } 7481 7482 if (VA.isRegLoc() && !VA.needsCustom()) { 7483 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7484 continue; 7485 } 7486 7487 if (VA.isMemLoc()) { 7488 SDValue PtrOff = 7489 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7490 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7491 MemOpChains.push_back( 7492 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7493 7494 continue; 7495 } 7496 7497 // Custom handling is used for GPR initializations for vararg float 7498 // arguments. 7499 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7500 ValVT.isFloatingPoint() && LocVT.isInteger() && 7501 "Unexpected register handling for calling convention."); 7502 7503 SDValue ArgAsInt = 7504 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7505 7506 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7507 // f32 in 32-bit GPR 7508 // f64 in 64-bit GPR 7509 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7510 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7511 // f32 in 64-bit GPR. 7512 RegsToPass.push_back(std::make_pair( 7513 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7514 else { 7515 // f64 in two 32-bit GPRs 7516 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7517 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7518 "Unexpected custom register for argument!"); 7519 CCValAssign &GPR1 = VA; 7520 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7521 DAG.getConstant(32, dl, MVT::i8)); 7522 RegsToPass.push_back(std::make_pair( 7523 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7524 7525 if (I != E) { 7526 // If only 1 GPR was available, there will only be one custom GPR and 7527 // the argument will also pass in memory. 7528 CCValAssign &PeekArg = ArgLocs[I]; 7529 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7530 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7531 CCValAssign &GPR2 = ArgLocs[I++]; 7532 RegsToPass.push_back(std::make_pair( 7533 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7534 } 7535 } 7536 } 7537 } 7538 7539 if (!MemOpChains.empty()) 7540 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7541 7542 // For indirect calls, we need to save the TOC base to the stack for 7543 // restoration after the call. 7544 if (CFlags.IsIndirect) { 7545 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7546 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7547 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7548 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7549 const unsigned TOCSaveOffset = 7550 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7551 7552 setUsesTOCBasePtr(DAG); 7553 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7554 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7555 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7556 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7557 Chain = DAG.getStore( 7558 Val.getValue(1), dl, Val, AddPtr, 7559 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7560 } 7561 7562 // Build a sequence of copy-to-reg nodes chained together with token chain 7563 // and flag operands which copy the outgoing args into the appropriate regs. 7564 SDValue InFlag; 7565 for (auto Reg : RegsToPass) { 7566 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7567 InFlag = Chain.getValue(1); 7568 } 7569 7570 const int SPDiff = 0; 7571 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7572 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7573 } 7574 7575 bool 7576 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7577 MachineFunction &MF, bool isVarArg, 7578 const SmallVectorImpl<ISD::OutputArg> &Outs, 7579 LLVMContext &Context) const { 7580 SmallVector<CCValAssign, 16> RVLocs; 7581 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7582 return CCInfo.CheckReturn( 7583 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7584 ? RetCC_PPC_Cold 7585 : RetCC_PPC); 7586 } 7587 7588 SDValue 7589 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7590 bool isVarArg, 7591 const SmallVectorImpl<ISD::OutputArg> &Outs, 7592 const SmallVectorImpl<SDValue> &OutVals, 7593 const SDLoc &dl, SelectionDAG &DAG) const { 7594 SmallVector<CCValAssign, 16> RVLocs; 7595 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7596 *DAG.getContext()); 7597 CCInfo.AnalyzeReturn(Outs, 7598 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7599 ? RetCC_PPC_Cold 7600 : RetCC_PPC); 7601 7602 SDValue Flag; 7603 SmallVector<SDValue, 4> RetOps(1, Chain); 7604 7605 // Copy the result values into the output registers. 7606 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7607 CCValAssign &VA = RVLocs[i]; 7608 assert(VA.isRegLoc() && "Can only return in registers!"); 7609 7610 SDValue Arg = OutVals[RealResIdx]; 7611 7612 switch (VA.getLocInfo()) { 7613 default: llvm_unreachable("Unknown loc info!"); 7614 case CCValAssign::Full: break; 7615 case CCValAssign::AExt: 7616 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7617 break; 7618 case CCValAssign::ZExt: 7619 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7620 break; 7621 case CCValAssign::SExt: 7622 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7623 break; 7624 } 7625 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7626 bool isLittleEndian = Subtarget.isLittleEndian(); 7627 // Legalize ret f64 -> ret 2 x i32. 7628 SDValue SVal = 7629 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7630 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7631 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7632 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7633 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7634 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7635 Flag = Chain.getValue(1); 7636 VA = RVLocs[++i]; // skip ahead to next loc 7637 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7638 } else 7639 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7640 Flag = Chain.getValue(1); 7641 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7642 } 7643 7644 RetOps[0] = Chain; // Update chain. 7645 7646 // Add the flag if we have it. 7647 if (Flag.getNode()) 7648 RetOps.push_back(Flag); 7649 7650 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7651 } 7652 7653 SDValue 7654 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7655 SelectionDAG &DAG) const { 7656 SDLoc dl(Op); 7657 7658 // Get the correct type for integers. 7659 EVT IntVT = Op.getValueType(); 7660 7661 // Get the inputs. 7662 SDValue Chain = Op.getOperand(0); 7663 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7664 // Build a DYNAREAOFFSET node. 7665 SDValue Ops[2] = {Chain, FPSIdx}; 7666 SDVTList VTs = DAG.getVTList(IntVT); 7667 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7668 } 7669 7670 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7671 SelectionDAG &DAG) const { 7672 // When we pop the dynamic allocation we need to restore the SP link. 7673 SDLoc dl(Op); 7674 7675 // Get the correct type for pointers. 7676 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7677 7678 // Construct the stack pointer operand. 7679 bool isPPC64 = Subtarget.isPPC64(); 7680 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7681 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7682 7683 // Get the operands for the STACKRESTORE. 7684 SDValue Chain = Op.getOperand(0); 7685 SDValue SaveSP = Op.getOperand(1); 7686 7687 // Load the old link SP. 7688 SDValue LoadLinkSP = 7689 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7690 7691 // Restore the stack pointer. 7692 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7693 7694 // Store the old link SP. 7695 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7696 } 7697 7698 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7699 MachineFunction &MF = DAG.getMachineFunction(); 7700 bool isPPC64 = Subtarget.isPPC64(); 7701 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7702 7703 // Get current frame pointer save index. The users of this index will be 7704 // primarily DYNALLOC instructions. 7705 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7706 int RASI = FI->getReturnAddrSaveIndex(); 7707 7708 // If the frame pointer save index hasn't been defined yet. 7709 if (!RASI) { 7710 // Find out what the fix offset of the frame pointer save area. 7711 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7712 // Allocate the frame index for frame pointer save area. 7713 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7714 // Save the result. 7715 FI->setReturnAddrSaveIndex(RASI); 7716 } 7717 return DAG.getFrameIndex(RASI, PtrVT); 7718 } 7719 7720 SDValue 7721 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7722 MachineFunction &MF = DAG.getMachineFunction(); 7723 bool isPPC64 = Subtarget.isPPC64(); 7724 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7725 7726 // Get current frame pointer save index. The users of this index will be 7727 // primarily DYNALLOC instructions. 7728 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7729 int FPSI = FI->getFramePointerSaveIndex(); 7730 7731 // If the frame pointer save index hasn't been defined yet. 7732 if (!FPSI) { 7733 // Find out what the fix offset of the frame pointer save area. 7734 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7735 // Allocate the frame index for frame pointer save area. 7736 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7737 // Save the result. 7738 FI->setFramePointerSaveIndex(FPSI); 7739 } 7740 return DAG.getFrameIndex(FPSI, PtrVT); 7741 } 7742 7743 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7744 SelectionDAG &DAG) const { 7745 MachineFunction &MF = DAG.getMachineFunction(); 7746 // Get the inputs. 7747 SDValue Chain = Op.getOperand(0); 7748 SDValue Size = Op.getOperand(1); 7749 SDLoc dl(Op); 7750 7751 // Get the correct type for pointers. 7752 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7753 // Negate the size. 7754 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7755 DAG.getConstant(0, dl, PtrVT), Size); 7756 // Construct a node for the frame pointer save index. 7757 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7758 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7759 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7760 if (hasInlineStackProbe(MF)) 7761 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7762 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7763 } 7764 7765 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7766 SelectionDAG &DAG) const { 7767 MachineFunction &MF = DAG.getMachineFunction(); 7768 7769 bool isPPC64 = Subtarget.isPPC64(); 7770 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7771 7772 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7773 return DAG.getFrameIndex(FI, PtrVT); 7774 } 7775 7776 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7777 SelectionDAG &DAG) const { 7778 SDLoc DL(Op); 7779 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7780 DAG.getVTList(MVT::i32, MVT::Other), 7781 Op.getOperand(0), Op.getOperand(1)); 7782 } 7783 7784 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7785 SelectionDAG &DAG) const { 7786 SDLoc DL(Op); 7787 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7788 Op.getOperand(0), Op.getOperand(1)); 7789 } 7790 7791 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7792 7793 assert(Op.getValueType() == MVT::i1 && 7794 "Custom lowering only for i1 loads"); 7795 7796 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7797 7798 SDLoc dl(Op); 7799 LoadSDNode *LD = cast<LoadSDNode>(Op); 7800 7801 SDValue Chain = LD->getChain(); 7802 SDValue BasePtr = LD->getBasePtr(); 7803 MachineMemOperand *MMO = LD->getMemOperand(); 7804 7805 SDValue NewLD = 7806 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7807 BasePtr, MVT::i8, MMO); 7808 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7809 7810 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7811 return DAG.getMergeValues(Ops, dl); 7812 } 7813 7814 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7815 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7816 "Custom lowering only for i1 stores"); 7817 7818 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7819 7820 SDLoc dl(Op); 7821 StoreSDNode *ST = cast<StoreSDNode>(Op); 7822 7823 SDValue Chain = ST->getChain(); 7824 SDValue BasePtr = ST->getBasePtr(); 7825 SDValue Value = ST->getValue(); 7826 MachineMemOperand *MMO = ST->getMemOperand(); 7827 7828 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7829 Value); 7830 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7831 } 7832 7833 // FIXME: Remove this once the ANDI glue bug is fixed: 7834 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7835 assert(Op.getValueType() == MVT::i1 && 7836 "Custom lowering only for i1 results"); 7837 7838 SDLoc DL(Op); 7839 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7840 } 7841 7842 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7843 SelectionDAG &DAG) const { 7844 7845 // Implements a vector truncate that fits in a vector register as a shuffle. 7846 // We want to legalize vector truncates down to where the source fits in 7847 // a vector register (and target is therefore smaller than vector register 7848 // size). At that point legalization will try to custom lower the sub-legal 7849 // result and get here - where we can contain the truncate as a single target 7850 // operation. 7851 7852 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7853 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7854 // 7855 // We will implement it for big-endian ordering as this (where x denotes 7856 // undefined): 7857 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7858 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7859 // 7860 // The same operation in little-endian ordering will be: 7861 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7862 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7863 7864 EVT TrgVT = Op.getValueType(); 7865 assert(TrgVT.isVector() && "Vector type expected."); 7866 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7867 EVT EltVT = TrgVT.getVectorElementType(); 7868 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7869 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7870 !isPowerOf2_32(EltVT.getSizeInBits())) 7871 return SDValue(); 7872 7873 SDValue N1 = Op.getOperand(0); 7874 EVT SrcVT = N1.getValueType(); 7875 unsigned SrcSize = SrcVT.getSizeInBits(); 7876 if (SrcSize > 256 || 7877 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7878 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7879 return SDValue(); 7880 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7881 return SDValue(); 7882 7883 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7884 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7885 7886 SDLoc DL(Op); 7887 SDValue Op1, Op2; 7888 if (SrcSize == 256) { 7889 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7890 EVT SplitVT = 7891 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7892 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7893 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7894 DAG.getConstant(0, DL, VecIdxTy)); 7895 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7896 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7897 } 7898 else { 7899 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7900 Op2 = DAG.getUNDEF(WideVT); 7901 } 7902 7903 // First list the elements we want to keep. 7904 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7905 SmallVector<int, 16> ShuffV; 7906 if (Subtarget.isLittleEndian()) 7907 for (unsigned i = 0; i < TrgNumElts; ++i) 7908 ShuffV.push_back(i * SizeMult); 7909 else 7910 for (unsigned i = 1; i <= TrgNumElts; ++i) 7911 ShuffV.push_back(i * SizeMult - 1); 7912 7913 // Populate the remaining elements with undefs. 7914 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7915 // ShuffV.push_back(i + WideNumElts); 7916 ShuffV.push_back(WideNumElts + 1); 7917 7918 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7919 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7920 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7921 } 7922 7923 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7924 /// possible. 7925 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7926 // Not FP, or using SPE? Not a fsel. 7927 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7928 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7929 return Op; 7930 7931 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7932 7933 EVT ResVT = Op.getValueType(); 7934 EVT CmpVT = Op.getOperand(0).getValueType(); 7935 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7936 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7937 SDLoc dl(Op); 7938 SDNodeFlags Flags = Op.getNode()->getFlags(); 7939 7940 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7941 // presence of infinities. 7942 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7943 switch (CC) { 7944 default: 7945 break; 7946 case ISD::SETOGT: 7947 case ISD::SETGT: 7948 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7949 case ISD::SETOLT: 7950 case ISD::SETLT: 7951 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7952 } 7953 } 7954 7955 // We might be able to do better than this under some circumstances, but in 7956 // general, fsel-based lowering of select is a finite-math-only optimization. 7957 // For more information, see section F.3 of the 2.06 ISA specification. 7958 // With ISA 3.0 7959 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7960 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7961 return Op; 7962 7963 // If the RHS of the comparison is a 0.0, we don't need to do the 7964 // subtraction at all. 7965 SDValue Sel1; 7966 if (isFloatingPointZero(RHS)) 7967 switch (CC) { 7968 default: break; // SETUO etc aren't handled by fsel. 7969 case ISD::SETNE: 7970 std::swap(TV, FV); 7971 LLVM_FALLTHROUGH; 7972 case ISD::SETEQ: 7973 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7974 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7975 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7976 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7977 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7978 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7979 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7980 case ISD::SETULT: 7981 case ISD::SETLT: 7982 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7983 LLVM_FALLTHROUGH; 7984 case ISD::SETOGE: 7985 case ISD::SETGE: 7986 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7987 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7988 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7989 case ISD::SETUGT: 7990 case ISD::SETGT: 7991 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7992 LLVM_FALLTHROUGH; 7993 case ISD::SETOLE: 7994 case ISD::SETLE: 7995 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7996 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7997 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7998 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7999 } 8000 8001 SDValue Cmp; 8002 switch (CC) { 8003 default: break; // SETUO etc aren't handled by fsel. 8004 case ISD::SETNE: 8005 std::swap(TV, FV); 8006 LLVM_FALLTHROUGH; 8007 case ISD::SETEQ: 8008 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8009 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8010 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8011 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8012 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8013 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8014 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8015 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8016 case ISD::SETULT: 8017 case ISD::SETLT: 8018 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8019 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8020 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8021 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8022 case ISD::SETOGE: 8023 case ISD::SETGE: 8024 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8025 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8026 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8027 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8028 case ISD::SETUGT: 8029 case ISD::SETGT: 8030 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8031 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8032 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8033 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8034 case ISD::SETOLE: 8035 case ISD::SETLE: 8036 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8037 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8038 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8039 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8040 } 8041 return Op; 8042 } 8043 8044 static unsigned getPPCStrictOpcode(unsigned Opc) { 8045 switch (Opc) { 8046 default: 8047 llvm_unreachable("No strict version of this opcode!"); 8048 case PPCISD::FCTIDZ: 8049 return PPCISD::STRICT_FCTIDZ; 8050 case PPCISD::FCTIWZ: 8051 return PPCISD::STRICT_FCTIWZ; 8052 case PPCISD::FCTIDUZ: 8053 return PPCISD::STRICT_FCTIDUZ; 8054 case PPCISD::FCTIWUZ: 8055 return PPCISD::STRICT_FCTIWUZ; 8056 case PPCISD::FCFID: 8057 return PPCISD::STRICT_FCFID; 8058 case PPCISD::FCFIDU: 8059 return PPCISD::STRICT_FCFIDU; 8060 case PPCISD::FCFIDS: 8061 return PPCISD::STRICT_FCFIDS; 8062 case PPCISD::FCFIDUS: 8063 return PPCISD::STRICT_FCFIDUS; 8064 } 8065 } 8066 8067 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8068 const PPCSubtarget &Subtarget) { 8069 SDLoc dl(Op); 8070 bool IsStrict = Op->isStrictFPOpcode(); 8071 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8072 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8073 // For strict nodes, source is the second operand. 8074 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8075 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8076 assert(Src.getValueType().isFloatingPoint()); 8077 if (Src.getValueType() == MVT::f32) { 8078 if (IsStrict) { 8079 Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other}, 8080 {Chain, Src}); 8081 Chain = Src.getValue(1); 8082 } else 8083 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8084 } 8085 SDValue Conv; 8086 unsigned Opc = ISD::DELETED_NODE; 8087 switch (Op.getSimpleValueType().SimpleTy) { 8088 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8089 case MVT::i32: 8090 Opc = IsSigned ? PPCISD::FCTIWZ 8091 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8092 break; 8093 case MVT::i64: 8094 assert((IsSigned || Subtarget.hasFPCVT()) && 8095 "i64 FP_TO_UINT is supported only with FPCVT"); 8096 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8097 } 8098 if (IsStrict) { 8099 Opc = getPPCStrictOpcode(Opc); 8100 Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src}); 8101 } else { 8102 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8103 } 8104 return Conv; 8105 } 8106 8107 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8108 SelectionDAG &DAG, 8109 const SDLoc &dl) const { 8110 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8111 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8112 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8113 bool IsStrict = Op->isStrictFPOpcode(); 8114 8115 // Convert the FP value to an int value through memory. 8116 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8117 (IsSigned || Subtarget.hasFPCVT()); 8118 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8119 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8120 MachinePointerInfo MPI = 8121 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8122 8123 // Emit a store to the stack slot. 8124 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8125 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8126 if (i32Stack) { 8127 MachineFunction &MF = DAG.getMachineFunction(); 8128 Alignment = Align(4); 8129 MachineMemOperand *MMO = 8130 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8131 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8132 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8133 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8134 } else 8135 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8136 8137 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8138 // add in a bias on big endian. 8139 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8140 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8141 DAG.getConstant(4, dl, FIPtr.getValueType())); 8142 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8143 } 8144 8145 RLI.Chain = Chain; 8146 RLI.Ptr = FIPtr; 8147 RLI.MPI = MPI; 8148 RLI.Alignment = Alignment; 8149 } 8150 8151 /// Custom lowers floating point to integer conversions to use 8152 /// the direct move instructions available in ISA 2.07 to avoid the 8153 /// need for load/store combinations. 8154 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8155 SelectionDAG &DAG, 8156 const SDLoc &dl) const { 8157 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8158 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8159 if (Op->isStrictFPOpcode()) 8160 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8161 else 8162 return Mov; 8163 } 8164 8165 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8166 const SDLoc &dl) const { 8167 bool IsStrict = Op->isStrictFPOpcode(); 8168 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8169 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8170 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8171 EVT SrcVT = Src.getValueType(); 8172 EVT DstVT = Op.getValueType(); 8173 8174 // FP to INT conversions are legal for f128. 8175 if (SrcVT == MVT::f128) 8176 return Op; 8177 8178 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8179 // PPC (the libcall is not available). 8180 if (SrcVT == MVT::ppcf128) { 8181 if (DstVT == MVT::i32) { 8182 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8183 // set other fast-math flags to FP operations in both strict and 8184 // non-strict cases. (FP_TO_SINT, FSUB) 8185 SDNodeFlags Flags; 8186 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8187 8188 if (IsSigned) { 8189 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8190 DAG.getIntPtrConstant(0, dl)); 8191 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8192 DAG.getIntPtrConstant(1, dl)); 8193 8194 // Add the two halves of the long double in round-to-zero mode, and use 8195 // a smaller FP_TO_SINT. 8196 if (IsStrict) { 8197 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8198 DAG.getVTList(MVT::f64, MVT::Other), 8199 {Op.getOperand(0), Lo, Hi}, Flags); 8200 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8201 DAG.getVTList(MVT::i32, MVT::Other), 8202 {Res.getValue(1), Res}, Flags); 8203 } else { 8204 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8205 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8206 } 8207 } else { 8208 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8209 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8210 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8211 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8212 if (IsStrict) { 8213 // Sel = Src < 0x80000000 8214 // FltOfs = select Sel, 0.0, 0x80000000 8215 // IntOfs = select Sel, 0, 0x80000000 8216 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8217 SDValue Chain = Op.getOperand(0); 8218 EVT SetCCVT = 8219 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8220 EVT DstSetCCVT = 8221 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8222 SDValue Sel = 8223 DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, Chain, true); 8224 Chain = Sel.getValue(1); 8225 8226 SDValue FltOfs = DAG.getSelect( 8227 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8228 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8229 8230 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8231 DAG.getVTList(SrcVT, MVT::Other), 8232 {Chain, Src, FltOfs}, Flags); 8233 Chain = Val.getValue(1); 8234 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8235 DAG.getVTList(DstVT, MVT::Other), 8236 {Chain, Val}, Flags); 8237 Chain = SInt.getValue(1); 8238 SDValue IntOfs = DAG.getSelect( 8239 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8240 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8241 return DAG.getMergeValues({Result, Chain}, dl); 8242 } else { 8243 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8244 // FIXME: generated code sucks. 8245 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8246 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8247 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8248 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8249 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8250 } 8251 } 8252 } 8253 8254 return SDValue(); 8255 } 8256 8257 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8258 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8259 8260 ReuseLoadInfo RLI; 8261 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8262 8263 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8264 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8265 } 8266 8267 // We're trying to insert a regular store, S, and then a load, L. If the 8268 // incoming value, O, is a load, we might just be able to have our load use the 8269 // address used by O. However, we don't know if anything else will store to 8270 // that address before we can load from it. To prevent this situation, we need 8271 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8272 // the same chain operand as O, we create a token factor from the chain results 8273 // of O and L, and we replace all uses of O's chain result with that token 8274 // factor (see spliceIntoChain below for this last part). 8275 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8276 ReuseLoadInfo &RLI, 8277 SelectionDAG &DAG, 8278 ISD::LoadExtType ET) const { 8279 // Conservatively skip reusing for constrained FP nodes. 8280 if (Op->isStrictFPOpcode()) 8281 return false; 8282 8283 SDLoc dl(Op); 8284 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8285 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8286 if (ET == ISD::NON_EXTLOAD && 8287 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8288 isOperationLegalOrCustom(Op.getOpcode(), 8289 Op.getOperand(0).getValueType())) { 8290 8291 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8292 return true; 8293 } 8294 8295 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8296 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8297 LD->isNonTemporal()) 8298 return false; 8299 if (LD->getMemoryVT() != MemVT) 8300 return false; 8301 8302 RLI.Ptr = LD->getBasePtr(); 8303 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8304 assert(LD->getAddressingMode() == ISD::PRE_INC && 8305 "Non-pre-inc AM on PPC?"); 8306 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8307 LD->getOffset()); 8308 } 8309 8310 RLI.Chain = LD->getChain(); 8311 RLI.MPI = LD->getPointerInfo(); 8312 RLI.IsDereferenceable = LD->isDereferenceable(); 8313 RLI.IsInvariant = LD->isInvariant(); 8314 RLI.Alignment = LD->getAlign(); 8315 RLI.AAInfo = LD->getAAInfo(); 8316 RLI.Ranges = LD->getRanges(); 8317 8318 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8319 return true; 8320 } 8321 8322 // Given the head of the old chain, ResChain, insert a token factor containing 8323 // it and NewResChain, and make users of ResChain now be users of that token 8324 // factor. 8325 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8326 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8327 SDValue NewResChain, 8328 SelectionDAG &DAG) const { 8329 if (!ResChain) 8330 return; 8331 8332 SDLoc dl(NewResChain); 8333 8334 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8335 NewResChain, DAG.getUNDEF(MVT::Other)); 8336 assert(TF.getNode() != NewResChain.getNode() && 8337 "A new TF really is required here"); 8338 8339 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8340 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8341 } 8342 8343 /// Analyze profitability of direct move 8344 /// prefer float load to int load plus direct move 8345 /// when there is no integer use of int load 8346 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8347 SDNode *Origin = Op.getOperand(0).getNode(); 8348 if (Origin->getOpcode() != ISD::LOAD) 8349 return true; 8350 8351 // If there is no LXSIBZX/LXSIHZX, like Power8, 8352 // prefer direct move if the memory size is 1 or 2 bytes. 8353 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8354 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8355 return true; 8356 8357 for (SDNode::use_iterator UI = Origin->use_begin(), 8358 UE = Origin->use_end(); 8359 UI != UE; ++UI) { 8360 8361 // Only look at the users of the loaded value. 8362 if (UI.getUse().get().getResNo() != 0) 8363 continue; 8364 8365 if (UI->getOpcode() != ISD::SINT_TO_FP && 8366 UI->getOpcode() != ISD::UINT_TO_FP && 8367 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8368 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8369 return true; 8370 } 8371 8372 return false; 8373 } 8374 8375 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8376 const PPCSubtarget &Subtarget, 8377 SDValue Chain = SDValue()) { 8378 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8379 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8380 SDLoc dl(Op); 8381 // If we have FCFIDS, then use it when converting to single-precision. 8382 // Otherwise, convert to double-precision and then round. 8383 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8384 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8385 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8386 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8387 if (Op->isStrictFPOpcode()) { 8388 if (!Chain) 8389 Chain = Op.getOperand(0); 8390 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other}, 8391 {Chain, Src}); 8392 } else 8393 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8394 } 8395 8396 /// Custom lowers integer to floating point conversions to use 8397 /// the direct move instructions available in ISA 2.07 to avoid the 8398 /// need for load/store combinations. 8399 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8400 SelectionDAG &DAG, 8401 const SDLoc &dl) const { 8402 assert((Op.getValueType() == MVT::f32 || 8403 Op.getValueType() == MVT::f64) && 8404 "Invalid floating point type as target of conversion"); 8405 assert(Subtarget.hasFPCVT() && 8406 "Int to FP conversions with direct moves require FPCVT"); 8407 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8408 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8409 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8410 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8411 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8412 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8413 return convertIntToFP(Op, Mov, DAG, Subtarget); 8414 } 8415 8416 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8417 8418 EVT VecVT = Vec.getValueType(); 8419 assert(VecVT.isVector() && "Expected a vector type."); 8420 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8421 8422 EVT EltVT = VecVT.getVectorElementType(); 8423 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8424 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8425 8426 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8427 SmallVector<SDValue, 16> Ops(NumConcat); 8428 Ops[0] = Vec; 8429 SDValue UndefVec = DAG.getUNDEF(VecVT); 8430 for (unsigned i = 1; i < NumConcat; ++i) 8431 Ops[i] = UndefVec; 8432 8433 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8434 } 8435 8436 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8437 const SDLoc &dl) const { 8438 bool IsStrict = Op->isStrictFPOpcode(); 8439 unsigned Opc = Op.getOpcode(); 8440 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8441 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8442 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8443 "Unexpected conversion type"); 8444 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8445 "Supports conversions to v2f64/v4f32 only."); 8446 8447 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8448 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8449 8450 SDValue Wide = widenVec(DAG, Src, dl); 8451 EVT WideVT = Wide.getValueType(); 8452 unsigned WideNumElts = WideVT.getVectorNumElements(); 8453 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8454 8455 SmallVector<int, 16> ShuffV; 8456 for (unsigned i = 0; i < WideNumElts; ++i) 8457 ShuffV.push_back(i + WideNumElts); 8458 8459 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8460 int SaveElts = FourEltRes ? 4 : 2; 8461 if (Subtarget.isLittleEndian()) 8462 for (int i = 0; i < SaveElts; i++) 8463 ShuffV[i * Stride] = i; 8464 else 8465 for (int i = 1; i <= SaveElts; i++) 8466 ShuffV[i * Stride - 1] = i - 1; 8467 8468 SDValue ShuffleSrc2 = 8469 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8470 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8471 8472 SDValue Extend; 8473 if (SignedConv) { 8474 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8475 EVT ExtVT = Src.getValueType(); 8476 if (Subtarget.hasP9Altivec()) 8477 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8478 IntermediateVT.getVectorNumElements()); 8479 8480 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8481 DAG.getValueType(ExtVT)); 8482 } else 8483 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8484 8485 if (IsStrict) 8486 return DAG.getNode(Opc, dl, {Op.getValueType(), MVT::Other}, 8487 {Op.getOperand(0), Extend}); 8488 8489 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8490 } 8491 8492 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8493 SelectionDAG &DAG) const { 8494 SDLoc dl(Op); 8495 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8496 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8497 bool IsStrict = Op->isStrictFPOpcode(); 8498 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8499 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8500 8501 EVT InVT = Src.getValueType(); 8502 EVT OutVT = Op.getValueType(); 8503 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8504 isOperationCustom(Op.getOpcode(), InVT)) 8505 return LowerINT_TO_FPVector(Op, DAG, dl); 8506 8507 // Conversions to f128 are legal. 8508 if (Op.getValueType() == MVT::f128) 8509 return Op; 8510 8511 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8512 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8513 return SDValue(); 8514 8515 if (Src.getValueType() == MVT::i1) 8516 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8517 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8518 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8519 8520 // If we have direct moves, we can do all the conversion, skip the store/load 8521 // however, without FPCVT we can't do most conversions. 8522 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8523 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8524 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8525 8526 assert((IsSigned || Subtarget.hasFPCVT()) && 8527 "UINT_TO_FP is supported only with FPCVT"); 8528 8529 if (Src.getValueType() == MVT::i64) { 8530 SDValue SINT = Src; 8531 // When converting to single-precision, we actually need to convert 8532 // to double-precision first and then round to single-precision. 8533 // To avoid double-rounding effects during that operation, we have 8534 // to prepare the input operand. Bits that might be truncated when 8535 // converting to double-precision are replaced by a bit that won't 8536 // be lost at this stage, but is below the single-precision rounding 8537 // position. 8538 // 8539 // However, if -enable-unsafe-fp-math is in effect, accept double 8540 // rounding to avoid the extra overhead. 8541 if (Op.getValueType() == MVT::f32 && 8542 !Subtarget.hasFPCVT() && 8543 !DAG.getTarget().Options.UnsafeFPMath) { 8544 8545 // Twiddle input to make sure the low 11 bits are zero. (If this 8546 // is the case, we are guaranteed the value will fit into the 53 bit 8547 // mantissa of an IEEE double-precision value without rounding.) 8548 // If any of those low 11 bits were not zero originally, make sure 8549 // bit 12 (value 2048) is set instead, so that the final rounding 8550 // to single-precision gets the correct result. 8551 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8552 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8553 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8554 Round, DAG.getConstant(2047, dl, MVT::i64)); 8555 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8556 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8557 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8558 8559 // However, we cannot use that value unconditionally: if the magnitude 8560 // of the input value is small, the bit-twiddling we did above might 8561 // end up visibly changing the output. Fortunately, in that case, we 8562 // don't need to twiddle bits since the original input will convert 8563 // exactly to double-precision floating-point already. Therefore, 8564 // construct a conditional to use the original value if the top 11 8565 // bits are all sign-bit copies, and use the rounded value computed 8566 // above otherwise. 8567 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8568 SINT, DAG.getConstant(53, dl, MVT::i32)); 8569 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8570 Cond, DAG.getConstant(1, dl, MVT::i64)); 8571 Cond = DAG.getSetCC( 8572 dl, 8573 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8574 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8575 8576 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8577 } 8578 8579 ReuseLoadInfo RLI; 8580 SDValue Bits; 8581 8582 MachineFunction &MF = DAG.getMachineFunction(); 8583 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8584 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8585 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8586 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8587 } else if (Subtarget.hasLFIWAX() && 8588 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8589 MachineMemOperand *MMO = 8590 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8591 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8592 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8593 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8594 DAG.getVTList(MVT::f64, MVT::Other), 8595 Ops, MVT::i32, MMO); 8596 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8597 } else if (Subtarget.hasFPCVT() && 8598 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8599 MachineMemOperand *MMO = 8600 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8601 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8602 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8603 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8604 DAG.getVTList(MVT::f64, MVT::Other), 8605 Ops, MVT::i32, MMO); 8606 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8607 } else if (((Subtarget.hasLFIWAX() && 8608 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8609 (Subtarget.hasFPCVT() && 8610 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8611 SINT.getOperand(0).getValueType() == MVT::i32) { 8612 MachineFrameInfo &MFI = MF.getFrameInfo(); 8613 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8614 8615 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8616 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8617 8618 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8619 MachinePointerInfo::getFixedStack( 8620 DAG.getMachineFunction(), FrameIdx)); 8621 Chain = Store; 8622 8623 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8624 "Expected an i32 store"); 8625 8626 RLI.Ptr = FIdx; 8627 RLI.Chain = Chain; 8628 RLI.MPI = 8629 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8630 RLI.Alignment = Align(4); 8631 8632 MachineMemOperand *MMO = 8633 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8634 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8635 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8636 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8637 PPCISD::LFIWZX : PPCISD::LFIWAX, 8638 dl, DAG.getVTList(MVT::f64, MVT::Other), 8639 Ops, MVT::i32, MMO); 8640 Chain = Bits.getValue(1); 8641 } else 8642 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8643 8644 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8645 if (IsStrict) 8646 Chain = FP.getValue(1); 8647 8648 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8649 if (IsStrict) 8650 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8651 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8652 else 8653 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8654 DAG.getIntPtrConstant(0, dl)); 8655 } 8656 return FP; 8657 } 8658 8659 assert(Src.getValueType() == MVT::i32 && 8660 "Unhandled INT_TO_FP type in custom expander!"); 8661 // Since we only generate this in 64-bit mode, we can take advantage of 8662 // 64-bit registers. In particular, sign extend the input value into the 8663 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8664 // then lfd it and fcfid it. 8665 MachineFunction &MF = DAG.getMachineFunction(); 8666 MachineFrameInfo &MFI = MF.getFrameInfo(); 8667 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8668 8669 SDValue Ld; 8670 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8671 ReuseLoadInfo RLI; 8672 bool ReusingLoad; 8673 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8674 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8675 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8676 8677 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8678 MachinePointerInfo::getFixedStack( 8679 DAG.getMachineFunction(), FrameIdx)); 8680 Chain = Store; 8681 8682 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8683 "Expected an i32 store"); 8684 8685 RLI.Ptr = FIdx; 8686 RLI.Chain = Chain; 8687 RLI.MPI = 8688 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8689 RLI.Alignment = Align(4); 8690 } 8691 8692 MachineMemOperand *MMO = 8693 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8694 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8695 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8696 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8697 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8698 MVT::i32, MMO); 8699 Chain = Ld.getValue(1); 8700 if (ReusingLoad) 8701 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8702 } else { 8703 assert(Subtarget.isPPC64() && 8704 "i32->FP without LFIWAX supported only on PPC64"); 8705 8706 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8707 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8708 8709 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8710 8711 // STD the extended value into the stack slot. 8712 SDValue Store = DAG.getStore( 8713 Chain, dl, Ext64, FIdx, 8714 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8715 Chain = Store; 8716 8717 // Load the value as a double. 8718 Ld = DAG.getLoad( 8719 MVT::f64, dl, Chain, FIdx, 8720 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8721 Chain = Ld.getValue(1); 8722 } 8723 8724 // FCFID it and return it. 8725 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8726 if (IsStrict) 8727 Chain = FP.getValue(1); 8728 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8729 if (IsStrict) 8730 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8731 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8732 else 8733 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8734 DAG.getIntPtrConstant(0, dl)); 8735 } 8736 return FP; 8737 } 8738 8739 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8740 SelectionDAG &DAG) const { 8741 SDLoc dl(Op); 8742 /* 8743 The rounding mode is in bits 30:31 of FPSR, and has the following 8744 settings: 8745 00 Round to nearest 8746 01 Round to 0 8747 10 Round to +inf 8748 11 Round to -inf 8749 8750 FLT_ROUNDS, on the other hand, expects the following: 8751 -1 Undefined 8752 0 Round to 0 8753 1 Round to nearest 8754 2 Round to +inf 8755 3 Round to -inf 8756 8757 To perform the conversion, we do: 8758 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8759 */ 8760 8761 MachineFunction &MF = DAG.getMachineFunction(); 8762 EVT VT = Op.getValueType(); 8763 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8764 8765 // Save FP Control Word to register 8766 SDValue Chain = Op.getOperand(0); 8767 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8768 Chain = MFFS.getValue(1); 8769 8770 // Save FP register to stack slot 8771 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8772 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8773 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8774 8775 // Load FP Control Word from low 32 bits of stack slot. 8776 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8777 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8778 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8779 Chain = CWD.getValue(1); 8780 8781 // Transform as necessary 8782 SDValue CWD1 = 8783 DAG.getNode(ISD::AND, dl, MVT::i32, 8784 CWD, DAG.getConstant(3, dl, MVT::i32)); 8785 SDValue CWD2 = 8786 DAG.getNode(ISD::SRL, dl, MVT::i32, 8787 DAG.getNode(ISD::AND, dl, MVT::i32, 8788 DAG.getNode(ISD::XOR, dl, MVT::i32, 8789 CWD, DAG.getConstant(3, dl, MVT::i32)), 8790 DAG.getConstant(3, dl, MVT::i32)), 8791 DAG.getConstant(1, dl, MVT::i32)); 8792 8793 SDValue RetVal = 8794 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8795 8796 RetVal = 8797 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8798 dl, VT, RetVal); 8799 8800 return DAG.getMergeValues({RetVal, Chain}, dl); 8801 } 8802 8803 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8804 EVT VT = Op.getValueType(); 8805 unsigned BitWidth = VT.getSizeInBits(); 8806 SDLoc dl(Op); 8807 assert(Op.getNumOperands() == 3 && 8808 VT == Op.getOperand(1).getValueType() && 8809 "Unexpected SHL!"); 8810 8811 // Expand into a bunch of logical ops. Note that these ops 8812 // depend on the PPC behavior for oversized shift amounts. 8813 SDValue Lo = Op.getOperand(0); 8814 SDValue Hi = Op.getOperand(1); 8815 SDValue Amt = Op.getOperand(2); 8816 EVT AmtVT = Amt.getValueType(); 8817 8818 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8819 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8820 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8821 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8822 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8823 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8824 DAG.getConstant(-BitWidth, dl, AmtVT)); 8825 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8826 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8827 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8828 SDValue OutOps[] = { OutLo, OutHi }; 8829 return DAG.getMergeValues(OutOps, dl); 8830 } 8831 8832 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8833 EVT VT = Op.getValueType(); 8834 SDLoc dl(Op); 8835 unsigned BitWidth = VT.getSizeInBits(); 8836 assert(Op.getNumOperands() == 3 && 8837 VT == Op.getOperand(1).getValueType() && 8838 "Unexpected SRL!"); 8839 8840 // Expand into a bunch of logical ops. Note that these ops 8841 // depend on the PPC behavior for oversized shift amounts. 8842 SDValue Lo = Op.getOperand(0); 8843 SDValue Hi = Op.getOperand(1); 8844 SDValue Amt = Op.getOperand(2); 8845 EVT AmtVT = Amt.getValueType(); 8846 8847 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8848 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8849 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8850 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8851 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8852 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8853 DAG.getConstant(-BitWidth, dl, AmtVT)); 8854 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8855 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8856 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8857 SDValue OutOps[] = { OutLo, OutHi }; 8858 return DAG.getMergeValues(OutOps, dl); 8859 } 8860 8861 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8862 SDLoc dl(Op); 8863 EVT VT = Op.getValueType(); 8864 unsigned BitWidth = VT.getSizeInBits(); 8865 assert(Op.getNumOperands() == 3 && 8866 VT == Op.getOperand(1).getValueType() && 8867 "Unexpected SRA!"); 8868 8869 // Expand into a bunch of logical ops, followed by a select_cc. 8870 SDValue Lo = Op.getOperand(0); 8871 SDValue Hi = Op.getOperand(1); 8872 SDValue Amt = Op.getOperand(2); 8873 EVT AmtVT = Amt.getValueType(); 8874 8875 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8876 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8877 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8878 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8879 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8880 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8881 DAG.getConstant(-BitWidth, dl, AmtVT)); 8882 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8883 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8884 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8885 Tmp4, Tmp6, ISD::SETLE); 8886 SDValue OutOps[] = { OutLo, OutHi }; 8887 return DAG.getMergeValues(OutOps, dl); 8888 } 8889 8890 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8891 SelectionDAG &DAG) const { 8892 SDLoc dl(Op); 8893 EVT VT = Op.getValueType(); 8894 unsigned BitWidth = VT.getSizeInBits(); 8895 8896 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8897 SDValue X = Op.getOperand(0); 8898 SDValue Y = Op.getOperand(1); 8899 SDValue Z = Op.getOperand(2); 8900 EVT AmtVT = Z.getValueType(); 8901 8902 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8903 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8904 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8905 // on PowerPC shift by BW being well defined. 8906 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8907 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8908 SDValue SubZ = 8909 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8910 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8911 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8912 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8913 } 8914 8915 //===----------------------------------------------------------------------===// 8916 // Vector related lowering. 8917 // 8918 8919 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8920 /// element size of SplatSize. Cast the result to VT. 8921 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8922 SelectionDAG &DAG, const SDLoc &dl) { 8923 static const MVT VTys[] = { // canonical VT to use for each size. 8924 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8925 }; 8926 8927 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8928 8929 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8930 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8931 SplatSize = 1; 8932 Val = 0xFF; 8933 } 8934 8935 EVT CanonicalVT = VTys[SplatSize-1]; 8936 8937 // Build a canonical splat for this value. 8938 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8939 } 8940 8941 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8942 /// specified intrinsic ID. 8943 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8944 const SDLoc &dl, EVT DestVT = MVT::Other) { 8945 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8946 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8947 DAG.getConstant(IID, dl, MVT::i32), Op); 8948 } 8949 8950 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8951 /// specified intrinsic ID. 8952 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8953 SelectionDAG &DAG, const SDLoc &dl, 8954 EVT DestVT = MVT::Other) { 8955 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8956 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8957 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8958 } 8959 8960 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8961 /// specified intrinsic ID. 8962 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8963 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8964 EVT DestVT = MVT::Other) { 8965 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8966 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8967 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8968 } 8969 8970 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8971 /// amount. The result has the specified value type. 8972 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8973 SelectionDAG &DAG, const SDLoc &dl) { 8974 // Force LHS/RHS to be the right type. 8975 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8976 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8977 8978 int Ops[16]; 8979 for (unsigned i = 0; i != 16; ++i) 8980 Ops[i] = i + Amt; 8981 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8982 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8983 } 8984 8985 /// Do we have an efficient pattern in a .td file for this node? 8986 /// 8987 /// \param V - pointer to the BuildVectorSDNode being matched 8988 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8989 /// 8990 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8991 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8992 /// the opposite is true (expansion is beneficial) are: 8993 /// - The node builds a vector out of integers that are not 32 or 64-bits 8994 /// - The node builds a vector out of constants 8995 /// - The node is a "load-and-splat" 8996 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8997 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8998 bool HasDirectMove, 8999 bool HasP8Vector) { 9000 EVT VecVT = V->getValueType(0); 9001 bool RightType = VecVT == MVT::v2f64 || 9002 (HasP8Vector && VecVT == MVT::v4f32) || 9003 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9004 if (!RightType) 9005 return false; 9006 9007 bool IsSplat = true; 9008 bool IsLoad = false; 9009 SDValue Op0 = V->getOperand(0); 9010 9011 // This function is called in a block that confirms the node is not a constant 9012 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9013 // different constants. 9014 if (V->isConstant()) 9015 return false; 9016 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9017 if (V->getOperand(i).isUndef()) 9018 return false; 9019 // We want to expand nodes that represent load-and-splat even if the 9020 // loaded value is a floating point truncation or conversion to int. 9021 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9022 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9023 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9024 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9025 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9026 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9027 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9028 IsLoad = true; 9029 // If the operands are different or the input is not a load and has more 9030 // uses than just this BV node, then it isn't a splat. 9031 if (V->getOperand(i) != Op0 || 9032 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9033 IsSplat = false; 9034 } 9035 return !(IsSplat && IsLoad); 9036 } 9037 9038 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9039 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9040 9041 SDLoc dl(Op); 9042 SDValue Op0 = Op->getOperand(0); 9043 9044 if ((Op.getValueType() != MVT::f128) || 9045 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9046 (Op0.getOperand(0).getValueType() != MVT::i64) || 9047 (Op0.getOperand(1).getValueType() != MVT::i64)) 9048 return SDValue(); 9049 9050 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9051 Op0.getOperand(1)); 9052 } 9053 9054 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9055 const SDValue *InputLoad = &Op; 9056 if (InputLoad->getOpcode() == ISD::BITCAST) 9057 InputLoad = &InputLoad->getOperand(0); 9058 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9059 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9060 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9061 InputLoad = &InputLoad->getOperand(0); 9062 } 9063 if (InputLoad->getOpcode() != ISD::LOAD) 9064 return nullptr; 9065 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9066 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9067 } 9068 9069 // Convert the argument APFloat to a single precision APFloat if there is no 9070 // loss in information during the conversion to single precision APFloat and the 9071 // resulting number is not a denormal number. Return true if successful. 9072 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9073 APFloat APFloatToConvert = ArgAPFloat; 9074 bool LosesInfo = true; 9075 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9076 &LosesInfo); 9077 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9078 if (Success) 9079 ArgAPFloat = APFloatToConvert; 9080 return Success; 9081 } 9082 9083 // Bitcast the argument APInt to a double and convert it to a single precision 9084 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9085 // argument if there is no loss in information during the conversion from 9086 // double to single precision APFloat and the resulting number is not a denormal 9087 // number. Return true if successful. 9088 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9089 double DpValue = ArgAPInt.bitsToDouble(); 9090 APFloat APFloatDp(DpValue); 9091 bool Success = convertToNonDenormSingle(APFloatDp); 9092 if (Success) 9093 ArgAPInt = APFloatDp.bitcastToAPInt(); 9094 return Success; 9095 } 9096 9097 // If this is a case we can't handle, return null and let the default 9098 // expansion code take care of it. If we CAN select this case, and if it 9099 // selects to a single instruction, return Op. Otherwise, if we can codegen 9100 // this case more efficiently than a constant pool load, lower it to the 9101 // sequence of ops that should be used. 9102 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9103 SelectionDAG &DAG) const { 9104 SDLoc dl(Op); 9105 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9106 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9107 9108 // Check if this is a splat of a constant value. 9109 APInt APSplatBits, APSplatUndef; 9110 unsigned SplatBitSize; 9111 bool HasAnyUndefs; 9112 bool BVNIsConstantSplat = 9113 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9114 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9115 9116 // If it is a splat of a double, check if we can shrink it to a 32 bit 9117 // non-denormal float which when converted back to double gives us the same 9118 // double. This is to exploit the XXSPLTIDP instruction. 9119 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9120 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9121 convertToNonDenormSingle(APSplatBits)) { 9122 SDValue SplatNode = DAG.getNode( 9123 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9124 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9125 return DAG.getBitcast(Op.getValueType(), SplatNode); 9126 } 9127 9128 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9129 9130 bool IsPermutedLoad = false; 9131 const SDValue *InputLoad = 9132 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9133 // Handle load-and-splat patterns as we have instructions that will do this 9134 // in one go. 9135 if (InputLoad && DAG.isSplatValue(Op, true)) { 9136 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9137 9138 // We have handling for 4 and 8 byte elements. 9139 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9140 9141 // Checking for a single use of this load, we have to check for vector 9142 // width (128 bits) / ElementSize uses (since each operand of the 9143 // BUILD_VECTOR is a separate use of the value. 9144 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9145 ((Subtarget.hasVSX() && ElementSize == 64) || 9146 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9147 SDValue Ops[] = { 9148 LD->getChain(), // Chain 9149 LD->getBasePtr(), // Ptr 9150 DAG.getValueType(Op.getValueType()) // VT 9151 }; 9152 return 9153 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9154 DAG.getVTList(Op.getValueType(), MVT::Other), 9155 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9156 } 9157 } 9158 9159 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9160 // lowered to VSX instructions under certain conditions. 9161 // Without VSX, there is no pattern more efficient than expanding the node. 9162 if (Subtarget.hasVSX() && 9163 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9164 Subtarget.hasP8Vector())) 9165 return Op; 9166 return SDValue(); 9167 } 9168 9169 uint64_t SplatBits = APSplatBits.getZExtValue(); 9170 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9171 unsigned SplatSize = SplatBitSize / 8; 9172 9173 // First, handle single instruction cases. 9174 9175 // All zeros? 9176 if (SplatBits == 0) { 9177 // Canonicalize all zero vectors to be v4i32. 9178 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9179 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9180 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9181 } 9182 return Op; 9183 } 9184 9185 // We have XXSPLTIW for constant splats four bytes wide. 9186 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9187 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9188 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9189 // turned into a 4-byte splat of 0xABABABAB. 9190 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9191 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9192 Op.getValueType(), DAG, dl); 9193 9194 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9195 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9196 dl); 9197 9198 // We have XXSPLTIB for constant splats one byte wide. 9199 if (Subtarget.hasP9Vector() && SplatSize == 1) 9200 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9201 dl); 9202 9203 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9204 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9205 (32-SplatBitSize)); 9206 if (SextVal >= -16 && SextVal <= 15) 9207 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9208 dl); 9209 9210 // Two instruction sequences. 9211 9212 // If this value is in the range [-32,30] and is even, use: 9213 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9214 // If this value is in the range [17,31] and is odd, use: 9215 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9216 // If this value is in the range [-31,-17] and is odd, use: 9217 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9218 // Note the last two are three-instruction sequences. 9219 if (SextVal >= -32 && SextVal <= 31) { 9220 // To avoid having these optimizations undone by constant folding, 9221 // we convert to a pseudo that will be expanded later into one of 9222 // the above forms. 9223 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9224 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9225 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9226 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9227 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9228 if (VT == Op.getValueType()) 9229 return RetVal; 9230 else 9231 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9232 } 9233 9234 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9235 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9236 // for fneg/fabs. 9237 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9238 // Make -1 and vspltisw -1: 9239 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9240 9241 // Make the VSLW intrinsic, computing 0x8000_0000. 9242 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9243 OnesV, DAG, dl); 9244 9245 // xor by OnesV to invert it. 9246 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9247 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9248 } 9249 9250 // Check to see if this is a wide variety of vsplti*, binop self cases. 9251 static const signed char SplatCsts[] = { 9252 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9253 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9254 }; 9255 9256 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9257 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9258 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9259 int i = SplatCsts[idx]; 9260 9261 // Figure out what shift amount will be used by altivec if shifted by i in 9262 // this splat size. 9263 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9264 9265 // vsplti + shl self. 9266 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9267 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9268 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9269 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9270 Intrinsic::ppc_altivec_vslw 9271 }; 9272 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9273 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9274 } 9275 9276 // vsplti + srl self. 9277 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9278 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9279 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9280 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9281 Intrinsic::ppc_altivec_vsrw 9282 }; 9283 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9284 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9285 } 9286 9287 // vsplti + sra self. 9288 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9289 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9290 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9291 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9292 Intrinsic::ppc_altivec_vsraw 9293 }; 9294 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9295 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9296 } 9297 9298 // vsplti + rol self. 9299 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9300 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9301 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9302 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9303 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9304 Intrinsic::ppc_altivec_vrlw 9305 }; 9306 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9307 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9308 } 9309 9310 // t = vsplti c, result = vsldoi t, t, 1 9311 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9312 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9313 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9314 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9315 } 9316 // t = vsplti c, result = vsldoi t, t, 2 9317 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9318 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9319 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9320 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9321 } 9322 // t = vsplti c, result = vsldoi t, t, 3 9323 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9324 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9325 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9326 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9327 } 9328 } 9329 9330 return SDValue(); 9331 } 9332 9333 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9334 /// the specified operations to build the shuffle. 9335 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9336 SDValue RHS, SelectionDAG &DAG, 9337 const SDLoc &dl) { 9338 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9339 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9340 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9341 9342 enum { 9343 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9344 OP_VMRGHW, 9345 OP_VMRGLW, 9346 OP_VSPLTISW0, 9347 OP_VSPLTISW1, 9348 OP_VSPLTISW2, 9349 OP_VSPLTISW3, 9350 OP_VSLDOI4, 9351 OP_VSLDOI8, 9352 OP_VSLDOI12 9353 }; 9354 9355 if (OpNum == OP_COPY) { 9356 if (LHSID == (1*9+2)*9+3) return LHS; 9357 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9358 return RHS; 9359 } 9360 9361 SDValue OpLHS, OpRHS; 9362 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9363 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9364 9365 int ShufIdxs[16]; 9366 switch (OpNum) { 9367 default: llvm_unreachable("Unknown i32 permute!"); 9368 case OP_VMRGHW: 9369 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9370 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9371 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9372 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9373 break; 9374 case OP_VMRGLW: 9375 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9376 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9377 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9378 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9379 break; 9380 case OP_VSPLTISW0: 9381 for (unsigned i = 0; i != 16; ++i) 9382 ShufIdxs[i] = (i&3)+0; 9383 break; 9384 case OP_VSPLTISW1: 9385 for (unsigned i = 0; i != 16; ++i) 9386 ShufIdxs[i] = (i&3)+4; 9387 break; 9388 case OP_VSPLTISW2: 9389 for (unsigned i = 0; i != 16; ++i) 9390 ShufIdxs[i] = (i&3)+8; 9391 break; 9392 case OP_VSPLTISW3: 9393 for (unsigned i = 0; i != 16; ++i) 9394 ShufIdxs[i] = (i&3)+12; 9395 break; 9396 case OP_VSLDOI4: 9397 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9398 case OP_VSLDOI8: 9399 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9400 case OP_VSLDOI12: 9401 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9402 } 9403 EVT VT = OpLHS.getValueType(); 9404 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9405 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9406 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9407 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9408 } 9409 9410 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9411 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9412 /// SDValue. 9413 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9414 SelectionDAG &DAG) const { 9415 const unsigned BytesInVector = 16; 9416 bool IsLE = Subtarget.isLittleEndian(); 9417 SDLoc dl(N); 9418 SDValue V1 = N->getOperand(0); 9419 SDValue V2 = N->getOperand(1); 9420 unsigned ShiftElts = 0, InsertAtByte = 0; 9421 bool Swap = false; 9422 9423 // Shifts required to get the byte we want at element 7. 9424 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9425 0, 15, 14, 13, 12, 11, 10, 9}; 9426 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9427 1, 2, 3, 4, 5, 6, 7, 8}; 9428 9429 ArrayRef<int> Mask = N->getMask(); 9430 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9431 9432 // For each mask element, find out if we're just inserting something 9433 // from V2 into V1 or vice versa. 9434 // Possible permutations inserting an element from V2 into V1: 9435 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9436 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9437 // ... 9438 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9439 // Inserting from V1 into V2 will be similar, except mask range will be 9440 // [16,31]. 9441 9442 bool FoundCandidate = false; 9443 // If both vector operands for the shuffle are the same vector, the mask 9444 // will contain only elements from the first one and the second one will be 9445 // undef. 9446 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9447 // Go through the mask of half-words to find an element that's being moved 9448 // from one vector to the other. 9449 for (unsigned i = 0; i < BytesInVector; ++i) { 9450 unsigned CurrentElement = Mask[i]; 9451 // If 2nd operand is undefined, we should only look for element 7 in the 9452 // Mask. 9453 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9454 continue; 9455 9456 bool OtherElementsInOrder = true; 9457 // Examine the other elements in the Mask to see if they're in original 9458 // order. 9459 for (unsigned j = 0; j < BytesInVector; ++j) { 9460 if (j == i) 9461 continue; 9462 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9463 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9464 // in which we always assume we're always picking from the 1st operand. 9465 int MaskOffset = 9466 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9467 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9468 OtherElementsInOrder = false; 9469 break; 9470 } 9471 } 9472 // If other elements are in original order, we record the number of shifts 9473 // we need to get the element we want into element 7. Also record which byte 9474 // in the vector we should insert into. 9475 if (OtherElementsInOrder) { 9476 // If 2nd operand is undefined, we assume no shifts and no swapping. 9477 if (V2.isUndef()) { 9478 ShiftElts = 0; 9479 Swap = false; 9480 } else { 9481 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9482 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9483 : BigEndianShifts[CurrentElement & 0xF]; 9484 Swap = CurrentElement < BytesInVector; 9485 } 9486 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9487 FoundCandidate = true; 9488 break; 9489 } 9490 } 9491 9492 if (!FoundCandidate) 9493 return SDValue(); 9494 9495 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9496 // optionally with VECSHL if shift is required. 9497 if (Swap) 9498 std::swap(V1, V2); 9499 if (V2.isUndef()) 9500 V2 = V1; 9501 if (ShiftElts) { 9502 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9503 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9504 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9505 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9506 } 9507 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9508 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9509 } 9510 9511 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9512 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9513 /// SDValue. 9514 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9515 SelectionDAG &DAG) const { 9516 const unsigned NumHalfWords = 8; 9517 const unsigned BytesInVector = NumHalfWords * 2; 9518 // Check that the shuffle is on half-words. 9519 if (!isNByteElemShuffleMask(N, 2, 1)) 9520 return SDValue(); 9521 9522 bool IsLE = Subtarget.isLittleEndian(); 9523 SDLoc dl(N); 9524 SDValue V1 = N->getOperand(0); 9525 SDValue V2 = N->getOperand(1); 9526 unsigned ShiftElts = 0, InsertAtByte = 0; 9527 bool Swap = false; 9528 9529 // Shifts required to get the half-word we want at element 3. 9530 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9531 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9532 9533 uint32_t Mask = 0; 9534 uint32_t OriginalOrderLow = 0x1234567; 9535 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9536 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9537 // 32-bit space, only need 4-bit nibbles per element. 9538 for (unsigned i = 0; i < NumHalfWords; ++i) { 9539 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9540 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9541 } 9542 9543 // For each mask element, find out if we're just inserting something 9544 // from V2 into V1 or vice versa. Possible permutations inserting an element 9545 // from V2 into V1: 9546 // X, 1, 2, 3, 4, 5, 6, 7 9547 // 0, X, 2, 3, 4, 5, 6, 7 9548 // 0, 1, X, 3, 4, 5, 6, 7 9549 // 0, 1, 2, X, 4, 5, 6, 7 9550 // 0, 1, 2, 3, X, 5, 6, 7 9551 // 0, 1, 2, 3, 4, X, 6, 7 9552 // 0, 1, 2, 3, 4, 5, X, 7 9553 // 0, 1, 2, 3, 4, 5, 6, X 9554 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9555 9556 bool FoundCandidate = false; 9557 // Go through the mask of half-words to find an element that's being moved 9558 // from one vector to the other. 9559 for (unsigned i = 0; i < NumHalfWords; ++i) { 9560 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9561 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9562 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9563 uint32_t TargetOrder = 0x0; 9564 9565 // If both vector operands for the shuffle are the same vector, the mask 9566 // will contain only elements from the first one and the second one will be 9567 // undef. 9568 if (V2.isUndef()) { 9569 ShiftElts = 0; 9570 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9571 TargetOrder = OriginalOrderLow; 9572 Swap = false; 9573 // Skip if not the correct element or mask of other elements don't equal 9574 // to our expected order. 9575 if (MaskOneElt == VINSERTHSrcElem && 9576 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9577 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9578 FoundCandidate = true; 9579 break; 9580 } 9581 } else { // If both operands are defined. 9582 // Target order is [8,15] if the current mask is between [0,7]. 9583 TargetOrder = 9584 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9585 // Skip if mask of other elements don't equal our expected order. 9586 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9587 // We only need the last 3 bits for the number of shifts. 9588 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9589 : BigEndianShifts[MaskOneElt & 0x7]; 9590 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9591 Swap = MaskOneElt < NumHalfWords; 9592 FoundCandidate = true; 9593 break; 9594 } 9595 } 9596 } 9597 9598 if (!FoundCandidate) 9599 return SDValue(); 9600 9601 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9602 // optionally with VECSHL if shift is required. 9603 if (Swap) 9604 std::swap(V1, V2); 9605 if (V2.isUndef()) 9606 V2 = V1; 9607 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9608 if (ShiftElts) { 9609 // Double ShiftElts because we're left shifting on v16i8 type. 9610 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9611 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9612 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9613 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9614 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9615 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9616 } 9617 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9618 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9619 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9620 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9621 } 9622 9623 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9624 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9625 /// return the default SDValue. 9626 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9627 SelectionDAG &DAG) const { 9628 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9629 // to v16i8. Peek through the bitcasts to get the actual operands. 9630 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9631 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9632 9633 auto ShuffleMask = SVN->getMask(); 9634 SDValue VecShuffle(SVN, 0); 9635 SDLoc DL(SVN); 9636 9637 // Check that we have a four byte shuffle. 9638 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9639 return SDValue(); 9640 9641 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9642 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9643 std::swap(LHS, RHS); 9644 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9645 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9646 } 9647 9648 // Ensure that the RHS is a vector of constants. 9649 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9650 if (!BVN) 9651 return SDValue(); 9652 9653 // Check if RHS is a splat of 4-bytes (or smaller). 9654 APInt APSplatValue, APSplatUndef; 9655 unsigned SplatBitSize; 9656 bool HasAnyUndefs; 9657 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9658 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9659 SplatBitSize > 32) 9660 return SDValue(); 9661 9662 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9663 // The instruction splats a constant C into two words of the source vector 9664 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9665 // Thus we check that the shuffle mask is the equivalent of 9666 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9667 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9668 // within each word are consecutive, so we only need to check the first byte. 9669 SDValue Index; 9670 bool IsLE = Subtarget.isLittleEndian(); 9671 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9672 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9673 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9674 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9675 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9676 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9677 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9678 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9679 else 9680 return SDValue(); 9681 9682 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9683 // for XXSPLTI32DX. 9684 unsigned SplatVal = APSplatValue.getZExtValue(); 9685 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9686 SplatVal |= (SplatVal << SplatBitSize); 9687 9688 SDValue SplatNode = DAG.getNode( 9689 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9690 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9691 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9692 } 9693 9694 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9695 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9696 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9697 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9698 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9699 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9700 assert(Op.getValueType() == MVT::v1i128 && 9701 "Only set v1i128 as custom, other type shouldn't reach here!"); 9702 SDLoc dl(Op); 9703 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9704 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9705 unsigned SHLAmt = N1.getConstantOperandVal(0); 9706 if (SHLAmt % 8 == 0) { 9707 SmallVector<int, 16> Mask(16, 0); 9708 std::iota(Mask.begin(), Mask.end(), 0); 9709 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9710 if (SDValue Shuffle = 9711 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9712 DAG.getUNDEF(MVT::v16i8), Mask)) 9713 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9714 } 9715 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9716 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9717 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9718 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9719 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9720 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9721 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9722 } 9723 9724 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9725 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9726 /// return the code it can be lowered into. Worst case, it can always be 9727 /// lowered into a vperm. 9728 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9729 SelectionDAG &DAG) const { 9730 SDLoc dl(Op); 9731 SDValue V1 = Op.getOperand(0); 9732 SDValue V2 = Op.getOperand(1); 9733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9734 9735 // Any nodes that were combined in the target-independent combiner prior 9736 // to vector legalization will not be sent to the target combine. Try to 9737 // combine it here. 9738 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9739 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9740 return NewShuffle; 9741 Op = NewShuffle; 9742 SVOp = cast<ShuffleVectorSDNode>(Op); 9743 V1 = Op.getOperand(0); 9744 V2 = Op.getOperand(1); 9745 } 9746 EVT VT = Op.getValueType(); 9747 bool isLittleEndian = Subtarget.isLittleEndian(); 9748 9749 unsigned ShiftElts, InsertAtByte; 9750 bool Swap = false; 9751 9752 // If this is a load-and-splat, we can do that with a single instruction 9753 // in some cases. However if the load has multiple uses, we don't want to 9754 // combine it because that will just produce multiple loads. 9755 bool IsPermutedLoad = false; 9756 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9757 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9758 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9759 InputLoad->hasOneUse()) { 9760 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9761 int SplatIdx = 9762 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9763 9764 // The splat index for permuted loads will be in the left half of the vector 9765 // which is strictly wider than the loaded value by 8 bytes. So we need to 9766 // adjust the splat index to point to the correct address in memory. 9767 if (IsPermutedLoad) { 9768 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9769 SplatIdx += IsFourByte ? 2 : 1; 9770 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9771 "Splat of a value outside of the loaded memory"); 9772 } 9773 9774 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9775 // For 4-byte load-and-splat, we need Power9. 9776 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9777 uint64_t Offset = 0; 9778 if (IsFourByte) 9779 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9780 else 9781 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9782 9783 SDValue BasePtr = LD->getBasePtr(); 9784 if (Offset != 0) 9785 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9786 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9787 SDValue Ops[] = { 9788 LD->getChain(), // Chain 9789 BasePtr, // BasePtr 9790 DAG.getValueType(Op.getValueType()) // VT 9791 }; 9792 SDVTList VTL = 9793 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9794 SDValue LdSplt = 9795 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9796 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9797 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9798 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9799 return LdSplt; 9800 } 9801 } 9802 if (Subtarget.hasP9Vector() && 9803 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9804 isLittleEndian)) { 9805 if (Swap) 9806 std::swap(V1, V2); 9807 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9808 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9809 if (ShiftElts) { 9810 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9811 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9812 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9813 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9814 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9815 } 9816 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9817 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9818 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9819 } 9820 9821 if (Subtarget.hasPrefixInstrs()) { 9822 SDValue SplatInsertNode; 9823 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9824 return SplatInsertNode; 9825 } 9826 9827 if (Subtarget.hasP9Altivec()) { 9828 SDValue NewISDNode; 9829 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9830 return NewISDNode; 9831 9832 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9833 return NewISDNode; 9834 } 9835 9836 if (Subtarget.hasVSX() && 9837 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9838 if (Swap) 9839 std::swap(V1, V2); 9840 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9841 SDValue Conv2 = 9842 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9843 9844 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9845 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9846 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9847 } 9848 9849 if (Subtarget.hasVSX() && 9850 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9851 if (Swap) 9852 std::swap(V1, V2); 9853 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9854 SDValue Conv2 = 9855 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9856 9857 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9858 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9859 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9860 } 9861 9862 if (Subtarget.hasP9Vector()) { 9863 if (PPC::isXXBRHShuffleMask(SVOp)) { 9864 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9865 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9866 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9867 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9868 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9869 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9870 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9871 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9872 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9873 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9874 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9875 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9876 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9877 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9878 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9879 } 9880 } 9881 9882 if (Subtarget.hasVSX()) { 9883 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9884 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9885 9886 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9887 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9888 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9889 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9890 } 9891 9892 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9893 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9894 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9895 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9896 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9897 } 9898 } 9899 9900 // Cases that are handled by instructions that take permute immediates 9901 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9902 // selected by the instruction selector. 9903 if (V2.isUndef()) { 9904 if (PPC::isSplatShuffleMask(SVOp, 1) || 9905 PPC::isSplatShuffleMask(SVOp, 2) || 9906 PPC::isSplatShuffleMask(SVOp, 4) || 9907 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9908 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9909 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9910 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9911 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9912 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9913 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9914 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9915 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9916 (Subtarget.hasP8Altivec() && ( 9917 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9918 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9919 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9920 return Op; 9921 } 9922 } 9923 9924 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9925 // and produce a fixed permutation. If any of these match, do not lower to 9926 // VPERM. 9927 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9928 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9929 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9930 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9931 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9932 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9933 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9934 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9935 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9936 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9937 (Subtarget.hasP8Altivec() && ( 9938 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9939 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9940 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9941 return Op; 9942 9943 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9944 // perfect shuffle table to emit an optimal matching sequence. 9945 ArrayRef<int> PermMask = SVOp->getMask(); 9946 9947 unsigned PFIndexes[4]; 9948 bool isFourElementShuffle = true; 9949 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9950 unsigned EltNo = 8; // Start out undef. 9951 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9952 if (PermMask[i*4+j] < 0) 9953 continue; // Undef, ignore it. 9954 9955 unsigned ByteSource = PermMask[i*4+j]; 9956 if ((ByteSource & 3) != j) { 9957 isFourElementShuffle = false; 9958 break; 9959 } 9960 9961 if (EltNo == 8) { 9962 EltNo = ByteSource/4; 9963 } else if (EltNo != ByteSource/4) { 9964 isFourElementShuffle = false; 9965 break; 9966 } 9967 } 9968 PFIndexes[i] = EltNo; 9969 } 9970 9971 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9972 // perfect shuffle vector to determine if it is cost effective to do this as 9973 // discrete instructions, or whether we should use a vperm. 9974 // For now, we skip this for little endian until such time as we have a 9975 // little-endian perfect shuffle table. 9976 if (isFourElementShuffle && !isLittleEndian) { 9977 // Compute the index in the perfect shuffle table. 9978 unsigned PFTableIndex = 9979 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9980 9981 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9982 unsigned Cost = (PFEntry >> 30); 9983 9984 // Determining when to avoid vperm is tricky. Many things affect the cost 9985 // of vperm, particularly how many times the perm mask needs to be computed. 9986 // For example, if the perm mask can be hoisted out of a loop or is already 9987 // used (perhaps because there are multiple permutes with the same shuffle 9988 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9989 // the loop requires an extra register. 9990 // 9991 // As a compromise, we only emit discrete instructions if the shuffle can be 9992 // generated in 3 or fewer operations. When we have loop information 9993 // available, if this block is within a loop, we should avoid using vperm 9994 // for 3-operation perms and use a constant pool load instead. 9995 if (Cost < 3) 9996 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9997 } 9998 9999 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10000 // vector that will get spilled to the constant pool. 10001 if (V2.isUndef()) V2 = V1; 10002 10003 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10004 // that it is in input element units, not in bytes. Convert now. 10005 10006 // For little endian, the order of the input vectors is reversed, and 10007 // the permutation mask is complemented with respect to 31. This is 10008 // necessary to produce proper semantics with the big-endian-biased vperm 10009 // instruction. 10010 EVT EltVT = V1.getValueType().getVectorElementType(); 10011 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10012 10013 SmallVector<SDValue, 16> ResultMask; 10014 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10015 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10016 10017 for (unsigned j = 0; j != BytesPerElement; ++j) 10018 if (isLittleEndian) 10019 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10020 dl, MVT::i32)); 10021 else 10022 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10023 MVT::i32)); 10024 } 10025 10026 ShufflesHandledWithVPERM++; 10027 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10028 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10029 LLVM_DEBUG(SVOp->dump()); 10030 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10031 LLVM_DEBUG(VPermMask.dump()); 10032 10033 if (isLittleEndian) 10034 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10035 V2, V1, VPermMask); 10036 else 10037 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10038 V1, V2, VPermMask); 10039 } 10040 10041 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10042 /// vector comparison. If it is, return true and fill in Opc/isDot with 10043 /// information about the intrinsic. 10044 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10045 bool &isDot, const PPCSubtarget &Subtarget) { 10046 unsigned IntrinsicID = 10047 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10048 CompareOpc = -1; 10049 isDot = false; 10050 switch (IntrinsicID) { 10051 default: 10052 return false; 10053 // Comparison predicates. 10054 case Intrinsic::ppc_altivec_vcmpbfp_p: 10055 CompareOpc = 966; 10056 isDot = true; 10057 break; 10058 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10059 CompareOpc = 198; 10060 isDot = true; 10061 break; 10062 case Intrinsic::ppc_altivec_vcmpequb_p: 10063 CompareOpc = 6; 10064 isDot = true; 10065 break; 10066 case Intrinsic::ppc_altivec_vcmpequh_p: 10067 CompareOpc = 70; 10068 isDot = true; 10069 break; 10070 case Intrinsic::ppc_altivec_vcmpequw_p: 10071 CompareOpc = 134; 10072 isDot = true; 10073 break; 10074 case Intrinsic::ppc_altivec_vcmpequd_p: 10075 if (Subtarget.hasP8Altivec()) { 10076 CompareOpc = 199; 10077 isDot = true; 10078 } else 10079 return false; 10080 break; 10081 case Intrinsic::ppc_altivec_vcmpneb_p: 10082 case Intrinsic::ppc_altivec_vcmpneh_p: 10083 case Intrinsic::ppc_altivec_vcmpnew_p: 10084 case Intrinsic::ppc_altivec_vcmpnezb_p: 10085 case Intrinsic::ppc_altivec_vcmpnezh_p: 10086 case Intrinsic::ppc_altivec_vcmpnezw_p: 10087 if (Subtarget.hasP9Altivec()) { 10088 switch (IntrinsicID) { 10089 default: 10090 llvm_unreachable("Unknown comparison intrinsic."); 10091 case Intrinsic::ppc_altivec_vcmpneb_p: 10092 CompareOpc = 7; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpneh_p: 10095 CompareOpc = 71; 10096 break; 10097 case Intrinsic::ppc_altivec_vcmpnew_p: 10098 CompareOpc = 135; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpnezb_p: 10101 CompareOpc = 263; 10102 break; 10103 case Intrinsic::ppc_altivec_vcmpnezh_p: 10104 CompareOpc = 327; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpnezw_p: 10107 CompareOpc = 391; 10108 break; 10109 } 10110 isDot = true; 10111 } else 10112 return false; 10113 break; 10114 case Intrinsic::ppc_altivec_vcmpgefp_p: 10115 CompareOpc = 454; 10116 isDot = true; 10117 break; 10118 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10119 CompareOpc = 710; 10120 isDot = true; 10121 break; 10122 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10123 CompareOpc = 774; 10124 isDot = true; 10125 break; 10126 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10127 CompareOpc = 838; 10128 isDot = true; 10129 break; 10130 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10131 CompareOpc = 902; 10132 isDot = true; 10133 break; 10134 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10135 if (Subtarget.hasP8Altivec()) { 10136 CompareOpc = 967; 10137 isDot = true; 10138 } else 10139 return false; 10140 break; 10141 case Intrinsic::ppc_altivec_vcmpgtub_p: 10142 CompareOpc = 518; 10143 isDot = true; 10144 break; 10145 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10146 CompareOpc = 582; 10147 isDot = true; 10148 break; 10149 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10150 CompareOpc = 646; 10151 isDot = true; 10152 break; 10153 case Intrinsic::ppc_altivec_vcmpgtud_p: 10154 if (Subtarget.hasP8Altivec()) { 10155 CompareOpc = 711; 10156 isDot = true; 10157 } else 10158 return false; 10159 break; 10160 10161 // VSX predicate comparisons use the same infrastructure 10162 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10163 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10164 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10165 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10166 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10167 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10168 if (Subtarget.hasVSX()) { 10169 switch (IntrinsicID) { 10170 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10171 CompareOpc = 99; 10172 break; 10173 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10174 CompareOpc = 115; 10175 break; 10176 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10177 CompareOpc = 107; 10178 break; 10179 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10180 CompareOpc = 67; 10181 break; 10182 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10183 CompareOpc = 83; 10184 break; 10185 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10186 CompareOpc = 75; 10187 break; 10188 } 10189 isDot = true; 10190 } else 10191 return false; 10192 break; 10193 10194 // Normal Comparisons. 10195 case Intrinsic::ppc_altivec_vcmpbfp: 10196 CompareOpc = 966; 10197 break; 10198 case Intrinsic::ppc_altivec_vcmpeqfp: 10199 CompareOpc = 198; 10200 break; 10201 case Intrinsic::ppc_altivec_vcmpequb: 10202 CompareOpc = 6; 10203 break; 10204 case Intrinsic::ppc_altivec_vcmpequh: 10205 CompareOpc = 70; 10206 break; 10207 case Intrinsic::ppc_altivec_vcmpequw: 10208 CompareOpc = 134; 10209 break; 10210 case Intrinsic::ppc_altivec_vcmpequd: 10211 if (Subtarget.hasP8Altivec()) 10212 CompareOpc = 199; 10213 else 10214 return false; 10215 break; 10216 case Intrinsic::ppc_altivec_vcmpneb: 10217 case Intrinsic::ppc_altivec_vcmpneh: 10218 case Intrinsic::ppc_altivec_vcmpnew: 10219 case Intrinsic::ppc_altivec_vcmpnezb: 10220 case Intrinsic::ppc_altivec_vcmpnezh: 10221 case Intrinsic::ppc_altivec_vcmpnezw: 10222 if (Subtarget.hasP9Altivec()) 10223 switch (IntrinsicID) { 10224 default: 10225 llvm_unreachable("Unknown comparison intrinsic."); 10226 case Intrinsic::ppc_altivec_vcmpneb: 10227 CompareOpc = 7; 10228 break; 10229 case Intrinsic::ppc_altivec_vcmpneh: 10230 CompareOpc = 71; 10231 break; 10232 case Intrinsic::ppc_altivec_vcmpnew: 10233 CompareOpc = 135; 10234 break; 10235 case Intrinsic::ppc_altivec_vcmpnezb: 10236 CompareOpc = 263; 10237 break; 10238 case Intrinsic::ppc_altivec_vcmpnezh: 10239 CompareOpc = 327; 10240 break; 10241 case Intrinsic::ppc_altivec_vcmpnezw: 10242 CompareOpc = 391; 10243 break; 10244 } 10245 else 10246 return false; 10247 break; 10248 case Intrinsic::ppc_altivec_vcmpgefp: 10249 CompareOpc = 454; 10250 break; 10251 case Intrinsic::ppc_altivec_vcmpgtfp: 10252 CompareOpc = 710; 10253 break; 10254 case Intrinsic::ppc_altivec_vcmpgtsb: 10255 CompareOpc = 774; 10256 break; 10257 case Intrinsic::ppc_altivec_vcmpgtsh: 10258 CompareOpc = 838; 10259 break; 10260 case Intrinsic::ppc_altivec_vcmpgtsw: 10261 CompareOpc = 902; 10262 break; 10263 case Intrinsic::ppc_altivec_vcmpgtsd: 10264 if (Subtarget.hasP8Altivec()) 10265 CompareOpc = 967; 10266 else 10267 return false; 10268 break; 10269 case Intrinsic::ppc_altivec_vcmpgtub: 10270 CompareOpc = 518; 10271 break; 10272 case Intrinsic::ppc_altivec_vcmpgtuh: 10273 CompareOpc = 582; 10274 break; 10275 case Intrinsic::ppc_altivec_vcmpgtuw: 10276 CompareOpc = 646; 10277 break; 10278 case Intrinsic::ppc_altivec_vcmpgtud: 10279 if (Subtarget.hasP8Altivec()) 10280 CompareOpc = 711; 10281 else 10282 return false; 10283 break; 10284 } 10285 return true; 10286 } 10287 10288 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10289 /// lower, do it, otherwise return null. 10290 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10291 SelectionDAG &DAG) const { 10292 unsigned IntrinsicID = 10293 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10294 10295 SDLoc dl(Op); 10296 10297 if (IntrinsicID == Intrinsic::thread_pointer) { 10298 // Reads the thread pointer register, used for __builtin_thread_pointer. 10299 if (Subtarget.isPPC64()) 10300 return DAG.getRegister(PPC::X13, MVT::i64); 10301 return DAG.getRegister(PPC::R2, MVT::i32); 10302 } 10303 10304 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10305 // opcode number of the comparison. 10306 int CompareOpc; 10307 bool isDot; 10308 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10309 return SDValue(); // Don't custom lower most intrinsics. 10310 10311 // If this is a non-dot comparison, make the VCMP node and we are done. 10312 if (!isDot) { 10313 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10314 Op.getOperand(1), Op.getOperand(2), 10315 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10316 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10317 } 10318 10319 // Create the PPCISD altivec 'dot' comparison node. 10320 SDValue Ops[] = { 10321 Op.getOperand(2), // LHS 10322 Op.getOperand(3), // RHS 10323 DAG.getConstant(CompareOpc, dl, MVT::i32) 10324 }; 10325 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10326 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10327 10328 // Now that we have the comparison, emit a copy from the CR to a GPR. 10329 // This is flagged to the above dot comparison. 10330 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10331 DAG.getRegister(PPC::CR6, MVT::i32), 10332 CompNode.getValue(1)); 10333 10334 // Unpack the result based on how the target uses it. 10335 unsigned BitNo; // Bit # of CR6. 10336 bool InvertBit; // Invert result? 10337 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10338 default: // Can't happen, don't crash on invalid number though. 10339 case 0: // Return the value of the EQ bit of CR6. 10340 BitNo = 0; InvertBit = false; 10341 break; 10342 case 1: // Return the inverted value of the EQ bit of CR6. 10343 BitNo = 0; InvertBit = true; 10344 break; 10345 case 2: // Return the value of the LT bit of CR6. 10346 BitNo = 2; InvertBit = false; 10347 break; 10348 case 3: // Return the inverted value of the LT bit of CR6. 10349 BitNo = 2; InvertBit = true; 10350 break; 10351 } 10352 10353 // Shift the bit into the low position. 10354 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10355 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10356 // Isolate the bit. 10357 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10358 DAG.getConstant(1, dl, MVT::i32)); 10359 10360 // If we are supposed to, toggle the bit. 10361 if (InvertBit) 10362 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10363 DAG.getConstant(1, dl, MVT::i32)); 10364 return Flags; 10365 } 10366 10367 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10368 SelectionDAG &DAG) const { 10369 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10370 // the beginning of the argument list. 10371 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10372 SDLoc DL(Op); 10373 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10374 case Intrinsic::ppc_cfence: { 10375 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10376 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10377 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10378 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10379 Op.getOperand(ArgStart + 1)), 10380 Op.getOperand(0)), 10381 0); 10382 } 10383 default: 10384 break; 10385 } 10386 return SDValue(); 10387 } 10388 10389 // Lower scalar BSWAP64 to xxbrd. 10390 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10391 SDLoc dl(Op); 10392 // MTVSRDD 10393 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10394 Op.getOperand(0)); 10395 // XXBRD 10396 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10397 // MFVSRD 10398 int VectorIndex = 0; 10399 if (Subtarget.isLittleEndian()) 10400 VectorIndex = 1; 10401 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10402 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10403 return Op; 10404 } 10405 10406 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10407 // compared to a value that is atomically loaded (atomic loads zero-extend). 10408 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10409 SelectionDAG &DAG) const { 10410 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10411 "Expecting an atomic compare-and-swap here."); 10412 SDLoc dl(Op); 10413 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10414 EVT MemVT = AtomicNode->getMemoryVT(); 10415 if (MemVT.getSizeInBits() >= 32) 10416 return Op; 10417 10418 SDValue CmpOp = Op.getOperand(2); 10419 // If this is already correctly zero-extended, leave it alone. 10420 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10421 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10422 return Op; 10423 10424 // Clear the high bits of the compare operand. 10425 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10426 SDValue NewCmpOp = 10427 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10428 DAG.getConstant(MaskVal, dl, MVT::i32)); 10429 10430 // Replace the existing compare operand with the properly zero-extended one. 10431 SmallVector<SDValue, 4> Ops; 10432 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10433 Ops.push_back(AtomicNode->getOperand(i)); 10434 Ops[2] = NewCmpOp; 10435 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10436 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10437 auto NodeTy = 10438 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10439 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10440 } 10441 10442 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10443 SelectionDAG &DAG) const { 10444 SDLoc dl(Op); 10445 // Create a stack slot that is 16-byte aligned. 10446 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10447 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10448 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10449 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10450 10451 // Store the input value into Value#0 of the stack slot. 10452 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10453 MachinePointerInfo()); 10454 // Load it out. 10455 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10456 } 10457 10458 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10459 SelectionDAG &DAG) const { 10460 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10461 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10462 10463 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10464 // We have legal lowering for constant indices but not for variable ones. 10465 if (!C) 10466 return SDValue(); 10467 10468 EVT VT = Op.getValueType(); 10469 SDLoc dl(Op); 10470 SDValue V1 = Op.getOperand(0); 10471 SDValue V2 = Op.getOperand(1); 10472 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10473 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10474 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10475 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10476 unsigned InsertAtElement = C->getZExtValue(); 10477 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10478 if (Subtarget.isLittleEndian()) { 10479 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10480 } 10481 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10482 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10483 } 10484 return Op; 10485 } 10486 10487 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10488 SDLoc dl(Op); 10489 if (Op.getValueType() == MVT::v4i32) { 10490 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10491 10492 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10493 // +16 as shift amt. 10494 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10495 SDValue RHSSwap = // = vrlw RHS, 16 10496 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10497 10498 // Shrinkify inputs to v8i16. 10499 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10500 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10501 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10502 10503 // Low parts multiplied together, generating 32-bit results (we ignore the 10504 // top parts). 10505 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10506 LHS, RHS, DAG, dl, MVT::v4i32); 10507 10508 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10509 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10510 // Shift the high parts up 16 bits. 10511 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10512 Neg16, DAG, dl); 10513 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10514 } else if (Op.getValueType() == MVT::v16i8) { 10515 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10516 bool isLittleEndian = Subtarget.isLittleEndian(); 10517 10518 // Multiply the even 8-bit parts, producing 16-bit sums. 10519 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10520 LHS, RHS, DAG, dl, MVT::v8i16); 10521 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10522 10523 // Multiply the odd 8-bit parts, producing 16-bit sums. 10524 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10525 LHS, RHS, DAG, dl, MVT::v8i16); 10526 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10527 10528 // Merge the results together. Because vmuleub and vmuloub are 10529 // instructions with a big-endian bias, we must reverse the 10530 // element numbering and reverse the meaning of "odd" and "even" 10531 // when generating little endian code. 10532 int Ops[16]; 10533 for (unsigned i = 0; i != 8; ++i) { 10534 if (isLittleEndian) { 10535 Ops[i*2 ] = 2*i; 10536 Ops[i*2+1] = 2*i+16; 10537 } else { 10538 Ops[i*2 ] = 2*i+1; 10539 Ops[i*2+1] = 2*i+1+16; 10540 } 10541 } 10542 if (isLittleEndian) 10543 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10544 else 10545 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10546 } else { 10547 llvm_unreachable("Unknown mul to lower!"); 10548 } 10549 } 10550 10551 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10552 10553 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10554 10555 EVT VT = Op.getValueType(); 10556 assert(VT.isVector() && 10557 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10558 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10559 VT == MVT::v16i8) && 10560 "Unexpected vector element type!"); 10561 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10562 "Current subtarget doesn't support smax v2i64!"); 10563 10564 // For vector abs, it can be lowered to: 10565 // abs x 10566 // ==> 10567 // y = -x 10568 // smax(x, y) 10569 10570 SDLoc dl(Op); 10571 SDValue X = Op.getOperand(0); 10572 SDValue Zero = DAG.getConstant(0, dl, VT); 10573 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10574 10575 // SMAX patch https://reviews.llvm.org/D47332 10576 // hasn't landed yet, so use intrinsic first here. 10577 // TODO: Should use SMAX directly once SMAX patch landed 10578 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10579 if (VT == MVT::v2i64) 10580 BifID = Intrinsic::ppc_altivec_vmaxsd; 10581 else if (VT == MVT::v8i16) 10582 BifID = Intrinsic::ppc_altivec_vmaxsh; 10583 else if (VT == MVT::v16i8) 10584 BifID = Intrinsic::ppc_altivec_vmaxsb; 10585 10586 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10587 } 10588 10589 // Custom lowering for fpext vf32 to v2f64 10590 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10591 10592 assert(Op.getOpcode() == ISD::FP_EXTEND && 10593 "Should only be called for ISD::FP_EXTEND"); 10594 10595 // FIXME: handle extends from half precision float vectors on P9. 10596 // We only want to custom lower an extend from v2f32 to v2f64. 10597 if (Op.getValueType() != MVT::v2f64 || 10598 Op.getOperand(0).getValueType() != MVT::v2f32) 10599 return SDValue(); 10600 10601 SDLoc dl(Op); 10602 SDValue Op0 = Op.getOperand(0); 10603 10604 switch (Op0.getOpcode()) { 10605 default: 10606 return SDValue(); 10607 case ISD::EXTRACT_SUBVECTOR: { 10608 assert(Op0.getNumOperands() == 2 && 10609 isa<ConstantSDNode>(Op0->getOperand(1)) && 10610 "Node should have 2 operands with second one being a constant!"); 10611 10612 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10613 return SDValue(); 10614 10615 // Custom lower is only done for high or low doubleword. 10616 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10617 if (Idx % 2 != 0) 10618 return SDValue(); 10619 10620 // Since input is v4f32, at this point Idx is either 0 or 2. 10621 // Shift to get the doubleword position we want. 10622 int DWord = Idx >> 1; 10623 10624 // High and low word positions are different on little endian. 10625 if (Subtarget.isLittleEndian()) 10626 DWord ^= 0x1; 10627 10628 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10629 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10630 } 10631 case ISD::FADD: 10632 case ISD::FMUL: 10633 case ISD::FSUB: { 10634 SDValue NewLoad[2]; 10635 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10636 // Ensure both input are loads. 10637 SDValue LdOp = Op0.getOperand(i); 10638 if (LdOp.getOpcode() != ISD::LOAD) 10639 return SDValue(); 10640 // Generate new load node. 10641 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10642 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10643 NewLoad[i] = DAG.getMemIntrinsicNode( 10644 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10645 LD->getMemoryVT(), LD->getMemOperand()); 10646 } 10647 SDValue NewOp = 10648 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10649 NewLoad[1], Op0.getNode()->getFlags()); 10650 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10651 DAG.getConstant(0, dl, MVT::i32)); 10652 } 10653 case ISD::LOAD: { 10654 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10655 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10656 SDValue NewLd = DAG.getMemIntrinsicNode( 10657 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10658 LD->getMemoryVT(), LD->getMemOperand()); 10659 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10660 DAG.getConstant(0, dl, MVT::i32)); 10661 } 10662 } 10663 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10664 } 10665 10666 /// LowerOperation - Provide custom lowering hooks for some operations. 10667 /// 10668 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10669 switch (Op.getOpcode()) { 10670 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10671 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10672 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10673 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10674 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10675 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10676 case ISD::SETCC: return LowerSETCC(Op, DAG); 10677 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10678 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10679 10680 // Variable argument lowering. 10681 case ISD::VASTART: return LowerVASTART(Op, DAG); 10682 case ISD::VAARG: return LowerVAARG(Op, DAG); 10683 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10684 10685 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10686 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10687 case ISD::GET_DYNAMIC_AREA_OFFSET: 10688 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10689 10690 // Exception handling lowering. 10691 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10692 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10693 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10694 10695 case ISD::LOAD: return LowerLOAD(Op, DAG); 10696 case ISD::STORE: return LowerSTORE(Op, DAG); 10697 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10698 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10699 case ISD::STRICT_FP_TO_UINT: 10700 case ISD::STRICT_FP_TO_SINT: 10701 case ISD::FP_TO_UINT: 10702 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10703 case ISD::STRICT_UINT_TO_FP: 10704 case ISD::STRICT_SINT_TO_FP: 10705 case ISD::UINT_TO_FP: 10706 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10707 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10708 10709 // Lower 64-bit shifts. 10710 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10711 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10712 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10713 10714 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10715 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10716 10717 // Vector-related lowering. 10718 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10719 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10720 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10721 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10722 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10723 case ISD::MUL: return LowerMUL(Op, DAG); 10724 case ISD::ABS: return LowerABS(Op, DAG); 10725 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10726 case ISD::ROTL: return LowerROTL(Op, DAG); 10727 10728 // For counter-based loop handling. 10729 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10730 10731 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10732 10733 // Frame & Return address. 10734 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10735 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10736 10737 case ISD::INTRINSIC_VOID: 10738 return LowerINTRINSIC_VOID(Op, DAG); 10739 case ISD::BSWAP: 10740 return LowerBSWAP(Op, DAG); 10741 case ISD::ATOMIC_CMP_SWAP: 10742 return LowerATOMIC_CMP_SWAP(Op, DAG); 10743 } 10744 } 10745 10746 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10747 SmallVectorImpl<SDValue> &Results, 10748 SelectionDAG &DAG) const { 10749 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10750 10751 if (!Res.getNode()) 10752 return; 10753 10754 // Take the return value as-is if original node has only one result. 10755 if (N->getNumValues() == 1) { 10756 Results.push_back(Res); 10757 return; 10758 } 10759 10760 // New node should have the same number of results. 10761 assert((N->getNumValues() == Res->getNumValues()) && 10762 "Lowering returned the wrong number of results!"); 10763 10764 for (unsigned i = 0; i < N->getNumValues(); ++i) 10765 Results.push_back(Res.getValue(i)); 10766 } 10767 10768 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10769 SmallVectorImpl<SDValue>&Results, 10770 SelectionDAG &DAG) const { 10771 SDLoc dl(N); 10772 switch (N->getOpcode()) { 10773 default: 10774 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10775 case ISD::READCYCLECOUNTER: { 10776 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10777 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10778 10779 Results.push_back( 10780 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10781 Results.push_back(RTB.getValue(2)); 10782 break; 10783 } 10784 case ISD::INTRINSIC_W_CHAIN: { 10785 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10786 Intrinsic::loop_decrement) 10787 break; 10788 10789 assert(N->getValueType(0) == MVT::i1 && 10790 "Unexpected result type for CTR decrement intrinsic"); 10791 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10792 N->getValueType(0)); 10793 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10794 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10795 N->getOperand(1)); 10796 10797 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10798 Results.push_back(NewInt.getValue(1)); 10799 break; 10800 } 10801 case ISD::VAARG: { 10802 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10803 return; 10804 10805 EVT VT = N->getValueType(0); 10806 10807 if (VT == MVT::i64) { 10808 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10809 10810 Results.push_back(NewNode); 10811 Results.push_back(NewNode.getValue(1)); 10812 } 10813 return; 10814 } 10815 case ISD::STRICT_FP_TO_SINT: 10816 case ISD::STRICT_FP_TO_UINT: 10817 case ISD::FP_TO_SINT: 10818 case ISD::FP_TO_UINT: 10819 // LowerFP_TO_INT() can only handle f32 and f64. 10820 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10821 MVT::ppcf128) 10822 return; 10823 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10824 return; 10825 case ISD::TRUNCATE: { 10826 if (!N->getValueType(0).isVector()) 10827 return; 10828 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10829 if (Lowered) 10830 Results.push_back(Lowered); 10831 return; 10832 } 10833 case ISD::BITCAST: 10834 // Don't handle bitcast here. 10835 return; 10836 case ISD::FP_EXTEND: 10837 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10838 if (Lowered) 10839 Results.push_back(Lowered); 10840 return; 10841 } 10842 } 10843 10844 //===----------------------------------------------------------------------===// 10845 // Other Lowering Code 10846 //===----------------------------------------------------------------------===// 10847 10848 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10849 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10850 Function *Func = Intrinsic::getDeclaration(M, Id); 10851 return Builder.CreateCall(Func, {}); 10852 } 10853 10854 // The mappings for emitLeading/TrailingFence is taken from 10855 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10856 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10857 Instruction *Inst, 10858 AtomicOrdering Ord) const { 10859 if (Ord == AtomicOrdering::SequentiallyConsistent) 10860 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10861 if (isReleaseOrStronger(Ord)) 10862 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10863 return nullptr; 10864 } 10865 10866 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10867 Instruction *Inst, 10868 AtomicOrdering Ord) const { 10869 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10870 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10871 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10872 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10873 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10874 return Builder.CreateCall( 10875 Intrinsic::getDeclaration( 10876 Builder.GetInsertBlock()->getParent()->getParent(), 10877 Intrinsic::ppc_cfence, {Inst->getType()}), 10878 {Inst}); 10879 // FIXME: Can use isync for rmw operation. 10880 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10881 } 10882 return nullptr; 10883 } 10884 10885 MachineBasicBlock * 10886 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10887 unsigned AtomicSize, 10888 unsigned BinOpcode, 10889 unsigned CmpOpcode, 10890 unsigned CmpPred) const { 10891 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10892 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10893 10894 auto LoadMnemonic = PPC::LDARX; 10895 auto StoreMnemonic = PPC::STDCX; 10896 switch (AtomicSize) { 10897 default: 10898 llvm_unreachable("Unexpected size of atomic entity"); 10899 case 1: 10900 LoadMnemonic = PPC::LBARX; 10901 StoreMnemonic = PPC::STBCX; 10902 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10903 break; 10904 case 2: 10905 LoadMnemonic = PPC::LHARX; 10906 StoreMnemonic = PPC::STHCX; 10907 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10908 break; 10909 case 4: 10910 LoadMnemonic = PPC::LWARX; 10911 StoreMnemonic = PPC::STWCX; 10912 break; 10913 case 8: 10914 LoadMnemonic = PPC::LDARX; 10915 StoreMnemonic = PPC::STDCX; 10916 break; 10917 } 10918 10919 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10920 MachineFunction *F = BB->getParent(); 10921 MachineFunction::iterator It = ++BB->getIterator(); 10922 10923 Register dest = MI.getOperand(0).getReg(); 10924 Register ptrA = MI.getOperand(1).getReg(); 10925 Register ptrB = MI.getOperand(2).getReg(); 10926 Register incr = MI.getOperand(3).getReg(); 10927 DebugLoc dl = MI.getDebugLoc(); 10928 10929 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10930 MachineBasicBlock *loop2MBB = 10931 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10932 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10933 F->insert(It, loopMBB); 10934 if (CmpOpcode) 10935 F->insert(It, loop2MBB); 10936 F->insert(It, exitMBB); 10937 exitMBB->splice(exitMBB->begin(), BB, 10938 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10939 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10940 10941 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10942 Register TmpReg = (!BinOpcode) ? incr : 10943 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10944 : &PPC::GPRCRegClass); 10945 10946 // thisMBB: 10947 // ... 10948 // fallthrough --> loopMBB 10949 BB->addSuccessor(loopMBB); 10950 10951 // loopMBB: 10952 // l[wd]arx dest, ptr 10953 // add r0, dest, incr 10954 // st[wd]cx. r0, ptr 10955 // bne- loopMBB 10956 // fallthrough --> exitMBB 10957 10958 // For max/min... 10959 // loopMBB: 10960 // l[wd]arx dest, ptr 10961 // cmpl?[wd] incr, dest 10962 // bgt exitMBB 10963 // loop2MBB: 10964 // st[wd]cx. dest, ptr 10965 // bne- loopMBB 10966 // fallthrough --> exitMBB 10967 10968 BB = loopMBB; 10969 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10970 .addReg(ptrA).addReg(ptrB); 10971 if (BinOpcode) 10972 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10973 if (CmpOpcode) { 10974 // Signed comparisons of byte or halfword values must be sign-extended. 10975 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10976 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10977 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10978 ExtReg).addReg(dest); 10979 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10980 .addReg(incr).addReg(ExtReg); 10981 } else 10982 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10983 .addReg(incr).addReg(dest); 10984 10985 BuildMI(BB, dl, TII->get(PPC::BCC)) 10986 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10987 BB->addSuccessor(loop2MBB); 10988 BB->addSuccessor(exitMBB); 10989 BB = loop2MBB; 10990 } 10991 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10992 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10993 BuildMI(BB, dl, TII->get(PPC::BCC)) 10994 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10995 BB->addSuccessor(loopMBB); 10996 BB->addSuccessor(exitMBB); 10997 10998 // exitMBB: 10999 // ... 11000 BB = exitMBB; 11001 return BB; 11002 } 11003 11004 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11005 MachineInstr &MI, MachineBasicBlock *BB, 11006 bool is8bit, // operation 11007 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11008 // If we support part-word atomic mnemonics, just use them 11009 if (Subtarget.hasPartwordAtomics()) 11010 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11011 CmpPred); 11012 11013 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11014 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11015 // In 64 bit mode we have to use 64 bits for addresses, even though the 11016 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11017 // registers without caring whether they're 32 or 64, but here we're 11018 // doing actual arithmetic on the addresses. 11019 bool is64bit = Subtarget.isPPC64(); 11020 bool isLittleEndian = Subtarget.isLittleEndian(); 11021 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11022 11023 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11024 MachineFunction *F = BB->getParent(); 11025 MachineFunction::iterator It = ++BB->getIterator(); 11026 11027 Register dest = MI.getOperand(0).getReg(); 11028 Register ptrA = MI.getOperand(1).getReg(); 11029 Register ptrB = MI.getOperand(2).getReg(); 11030 Register incr = MI.getOperand(3).getReg(); 11031 DebugLoc dl = MI.getDebugLoc(); 11032 11033 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11034 MachineBasicBlock *loop2MBB = 11035 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11036 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11037 F->insert(It, loopMBB); 11038 if (CmpOpcode) 11039 F->insert(It, loop2MBB); 11040 F->insert(It, exitMBB); 11041 exitMBB->splice(exitMBB->begin(), BB, 11042 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11043 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11044 11045 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11046 const TargetRegisterClass *RC = 11047 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11048 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11049 11050 Register PtrReg = RegInfo.createVirtualRegister(RC); 11051 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11052 Register ShiftReg = 11053 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11054 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11055 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11056 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11057 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11058 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11059 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11060 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11061 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11062 Register Ptr1Reg; 11063 Register TmpReg = 11064 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11065 11066 // thisMBB: 11067 // ... 11068 // fallthrough --> loopMBB 11069 BB->addSuccessor(loopMBB); 11070 11071 // The 4-byte load must be aligned, while a char or short may be 11072 // anywhere in the word. Hence all this nasty bookkeeping code. 11073 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11074 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11075 // xori shift, shift1, 24 [16] 11076 // rlwinm ptr, ptr1, 0, 0, 29 11077 // slw incr2, incr, shift 11078 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11079 // slw mask, mask2, shift 11080 // loopMBB: 11081 // lwarx tmpDest, ptr 11082 // add tmp, tmpDest, incr2 11083 // andc tmp2, tmpDest, mask 11084 // and tmp3, tmp, mask 11085 // or tmp4, tmp3, tmp2 11086 // stwcx. tmp4, ptr 11087 // bne- loopMBB 11088 // fallthrough --> exitMBB 11089 // srw dest, tmpDest, shift 11090 if (ptrA != ZeroReg) { 11091 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11092 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11093 .addReg(ptrA) 11094 .addReg(ptrB); 11095 } else { 11096 Ptr1Reg = ptrB; 11097 } 11098 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11099 // mode. 11100 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11101 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11102 .addImm(3) 11103 .addImm(27) 11104 .addImm(is8bit ? 28 : 27); 11105 if (!isLittleEndian) 11106 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11107 .addReg(Shift1Reg) 11108 .addImm(is8bit ? 24 : 16); 11109 if (is64bit) 11110 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11111 .addReg(Ptr1Reg) 11112 .addImm(0) 11113 .addImm(61); 11114 else 11115 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11116 .addReg(Ptr1Reg) 11117 .addImm(0) 11118 .addImm(0) 11119 .addImm(29); 11120 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11121 if (is8bit) 11122 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11123 else { 11124 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11125 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11126 .addReg(Mask3Reg) 11127 .addImm(65535); 11128 } 11129 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11130 .addReg(Mask2Reg) 11131 .addReg(ShiftReg); 11132 11133 BB = loopMBB; 11134 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11135 .addReg(ZeroReg) 11136 .addReg(PtrReg); 11137 if (BinOpcode) 11138 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11139 .addReg(Incr2Reg) 11140 .addReg(TmpDestReg); 11141 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11142 .addReg(TmpDestReg) 11143 .addReg(MaskReg); 11144 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11145 if (CmpOpcode) { 11146 // For unsigned comparisons, we can directly compare the shifted values. 11147 // For signed comparisons we shift and sign extend. 11148 Register SReg = RegInfo.createVirtualRegister(GPRC); 11149 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11150 .addReg(TmpDestReg) 11151 .addReg(MaskReg); 11152 unsigned ValueReg = SReg; 11153 unsigned CmpReg = Incr2Reg; 11154 if (CmpOpcode == PPC::CMPW) { 11155 ValueReg = RegInfo.createVirtualRegister(GPRC); 11156 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11157 .addReg(SReg) 11158 .addReg(ShiftReg); 11159 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11160 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11161 .addReg(ValueReg); 11162 ValueReg = ValueSReg; 11163 CmpReg = incr; 11164 } 11165 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11166 .addReg(CmpReg) 11167 .addReg(ValueReg); 11168 BuildMI(BB, dl, TII->get(PPC::BCC)) 11169 .addImm(CmpPred) 11170 .addReg(PPC::CR0) 11171 .addMBB(exitMBB); 11172 BB->addSuccessor(loop2MBB); 11173 BB->addSuccessor(exitMBB); 11174 BB = loop2MBB; 11175 } 11176 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11177 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11178 .addReg(Tmp4Reg) 11179 .addReg(ZeroReg) 11180 .addReg(PtrReg); 11181 BuildMI(BB, dl, TII->get(PPC::BCC)) 11182 .addImm(PPC::PRED_NE) 11183 .addReg(PPC::CR0) 11184 .addMBB(loopMBB); 11185 BB->addSuccessor(loopMBB); 11186 BB->addSuccessor(exitMBB); 11187 11188 // exitMBB: 11189 // ... 11190 BB = exitMBB; 11191 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11192 .addReg(TmpDestReg) 11193 .addReg(ShiftReg); 11194 return BB; 11195 } 11196 11197 llvm::MachineBasicBlock * 11198 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11199 MachineBasicBlock *MBB) const { 11200 DebugLoc DL = MI.getDebugLoc(); 11201 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11202 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11203 11204 MachineFunction *MF = MBB->getParent(); 11205 MachineRegisterInfo &MRI = MF->getRegInfo(); 11206 11207 const BasicBlock *BB = MBB->getBasicBlock(); 11208 MachineFunction::iterator I = ++MBB->getIterator(); 11209 11210 Register DstReg = MI.getOperand(0).getReg(); 11211 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11212 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11213 Register mainDstReg = MRI.createVirtualRegister(RC); 11214 Register restoreDstReg = MRI.createVirtualRegister(RC); 11215 11216 MVT PVT = getPointerTy(MF->getDataLayout()); 11217 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11218 "Invalid Pointer Size!"); 11219 // For v = setjmp(buf), we generate 11220 // 11221 // thisMBB: 11222 // SjLjSetup mainMBB 11223 // bl mainMBB 11224 // v_restore = 1 11225 // b sinkMBB 11226 // 11227 // mainMBB: 11228 // buf[LabelOffset] = LR 11229 // v_main = 0 11230 // 11231 // sinkMBB: 11232 // v = phi(main, restore) 11233 // 11234 11235 MachineBasicBlock *thisMBB = MBB; 11236 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11237 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11238 MF->insert(I, mainMBB); 11239 MF->insert(I, sinkMBB); 11240 11241 MachineInstrBuilder MIB; 11242 11243 // Transfer the remainder of BB and its successor edges to sinkMBB. 11244 sinkMBB->splice(sinkMBB->begin(), MBB, 11245 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11246 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11247 11248 // Note that the structure of the jmp_buf used here is not compatible 11249 // with that used by libc, and is not designed to be. Specifically, it 11250 // stores only those 'reserved' registers that LLVM does not otherwise 11251 // understand how to spill. Also, by convention, by the time this 11252 // intrinsic is called, Clang has already stored the frame address in the 11253 // first slot of the buffer and stack address in the third. Following the 11254 // X86 target code, we'll store the jump address in the second slot. We also 11255 // need to save the TOC pointer (R2) to handle jumps between shared 11256 // libraries, and that will be stored in the fourth slot. The thread 11257 // identifier (R13) is not affected. 11258 11259 // thisMBB: 11260 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11261 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11262 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11263 11264 // Prepare IP either in reg. 11265 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11266 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11267 Register BufReg = MI.getOperand(1).getReg(); 11268 11269 if (Subtarget.is64BitELFABI()) { 11270 setUsesTOCBasePtr(*MBB->getParent()); 11271 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11272 .addReg(PPC::X2) 11273 .addImm(TOCOffset) 11274 .addReg(BufReg) 11275 .cloneMemRefs(MI); 11276 } 11277 11278 // Naked functions never have a base pointer, and so we use r1. For all 11279 // other functions, this decision must be delayed until during PEI. 11280 unsigned BaseReg; 11281 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11282 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11283 else 11284 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11285 11286 MIB = BuildMI(*thisMBB, MI, DL, 11287 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11288 .addReg(BaseReg) 11289 .addImm(BPOffset) 11290 .addReg(BufReg) 11291 .cloneMemRefs(MI); 11292 11293 // Setup 11294 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11295 MIB.addRegMask(TRI->getNoPreservedMask()); 11296 11297 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11298 11299 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11300 .addMBB(mainMBB); 11301 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11302 11303 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11304 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11305 11306 // mainMBB: 11307 // mainDstReg = 0 11308 MIB = 11309 BuildMI(mainMBB, DL, 11310 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11311 11312 // Store IP 11313 if (Subtarget.isPPC64()) { 11314 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11315 .addReg(LabelReg) 11316 .addImm(LabelOffset) 11317 .addReg(BufReg); 11318 } else { 11319 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11320 .addReg(LabelReg) 11321 .addImm(LabelOffset) 11322 .addReg(BufReg); 11323 } 11324 MIB.cloneMemRefs(MI); 11325 11326 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11327 mainMBB->addSuccessor(sinkMBB); 11328 11329 // sinkMBB: 11330 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11331 TII->get(PPC::PHI), DstReg) 11332 .addReg(mainDstReg).addMBB(mainMBB) 11333 .addReg(restoreDstReg).addMBB(thisMBB); 11334 11335 MI.eraseFromParent(); 11336 return sinkMBB; 11337 } 11338 11339 MachineBasicBlock * 11340 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11341 MachineBasicBlock *MBB) const { 11342 DebugLoc DL = MI.getDebugLoc(); 11343 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11344 11345 MachineFunction *MF = MBB->getParent(); 11346 MachineRegisterInfo &MRI = MF->getRegInfo(); 11347 11348 MVT PVT = getPointerTy(MF->getDataLayout()); 11349 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11350 "Invalid Pointer Size!"); 11351 11352 const TargetRegisterClass *RC = 11353 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11354 Register Tmp = MRI.createVirtualRegister(RC); 11355 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11356 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11357 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11358 unsigned BP = 11359 (PVT == MVT::i64) 11360 ? PPC::X30 11361 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11362 : PPC::R30); 11363 11364 MachineInstrBuilder MIB; 11365 11366 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11367 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11368 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11369 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11370 11371 Register BufReg = MI.getOperand(0).getReg(); 11372 11373 // Reload FP (the jumped-to function may not have had a 11374 // frame pointer, and if so, then its r31 will be restored 11375 // as necessary). 11376 if (PVT == MVT::i64) { 11377 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11378 .addImm(0) 11379 .addReg(BufReg); 11380 } else { 11381 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11382 .addImm(0) 11383 .addReg(BufReg); 11384 } 11385 MIB.cloneMemRefs(MI); 11386 11387 // Reload IP 11388 if (PVT == MVT::i64) { 11389 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11390 .addImm(LabelOffset) 11391 .addReg(BufReg); 11392 } else { 11393 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11394 .addImm(LabelOffset) 11395 .addReg(BufReg); 11396 } 11397 MIB.cloneMemRefs(MI); 11398 11399 // Reload SP 11400 if (PVT == MVT::i64) { 11401 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11402 .addImm(SPOffset) 11403 .addReg(BufReg); 11404 } else { 11405 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11406 .addImm(SPOffset) 11407 .addReg(BufReg); 11408 } 11409 MIB.cloneMemRefs(MI); 11410 11411 // Reload BP 11412 if (PVT == MVT::i64) { 11413 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11414 .addImm(BPOffset) 11415 .addReg(BufReg); 11416 } else { 11417 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11418 .addImm(BPOffset) 11419 .addReg(BufReg); 11420 } 11421 MIB.cloneMemRefs(MI); 11422 11423 // Reload TOC 11424 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11425 setUsesTOCBasePtr(*MBB->getParent()); 11426 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11427 .addImm(TOCOffset) 11428 .addReg(BufReg) 11429 .cloneMemRefs(MI); 11430 } 11431 11432 // Jump 11433 BuildMI(*MBB, MI, DL, 11434 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11435 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11436 11437 MI.eraseFromParent(); 11438 return MBB; 11439 } 11440 11441 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11442 // If the function specifically requests inline stack probes, emit them. 11443 if (MF.getFunction().hasFnAttribute("probe-stack")) 11444 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11445 "inline-asm"; 11446 return false; 11447 } 11448 11449 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11450 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11451 unsigned StackAlign = TFI->getStackAlignment(); 11452 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11453 "Unexpected stack alignment"); 11454 // The default stack probe size is 4096 if the function has no 11455 // stack-probe-size attribute. 11456 unsigned StackProbeSize = 4096; 11457 const Function &Fn = MF.getFunction(); 11458 if (Fn.hasFnAttribute("stack-probe-size")) 11459 Fn.getFnAttribute("stack-probe-size") 11460 .getValueAsString() 11461 .getAsInteger(0, StackProbeSize); 11462 // Round down to the stack alignment. 11463 StackProbeSize &= ~(StackAlign - 1); 11464 return StackProbeSize ? StackProbeSize : StackAlign; 11465 } 11466 11467 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11468 // into three phases. In the first phase, it uses pseudo instruction 11469 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11470 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11471 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11472 // MaxCallFrameSize so that it can calculate correct data area pointer. 11473 MachineBasicBlock * 11474 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11475 MachineBasicBlock *MBB) const { 11476 const bool isPPC64 = Subtarget.isPPC64(); 11477 MachineFunction *MF = MBB->getParent(); 11478 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11479 DebugLoc DL = MI.getDebugLoc(); 11480 const unsigned ProbeSize = getStackProbeSize(*MF); 11481 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11482 MachineRegisterInfo &MRI = MF->getRegInfo(); 11483 // The CFG of probing stack looks as 11484 // +-----+ 11485 // | MBB | 11486 // +--+--+ 11487 // | 11488 // +----v----+ 11489 // +--->+ TestMBB +---+ 11490 // | +----+----+ | 11491 // | | | 11492 // | +-----v----+ | 11493 // +---+ BlockMBB | | 11494 // +----------+ | 11495 // | 11496 // +---------+ | 11497 // | TailMBB +<--+ 11498 // +---------+ 11499 // In MBB, calculate previous frame pointer and final stack pointer. 11500 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11501 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11502 // TailMBB is spliced via \p MI. 11503 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11504 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11505 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11506 11507 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11508 MF->insert(MBBIter, TestMBB); 11509 MF->insert(MBBIter, BlockMBB); 11510 MF->insert(MBBIter, TailMBB); 11511 11512 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11513 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11514 11515 Register DstReg = MI.getOperand(0).getReg(); 11516 Register NegSizeReg = MI.getOperand(1).getReg(); 11517 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11518 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11519 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11520 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11521 11522 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11523 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11524 // NegSize. 11525 unsigned ProbeOpc; 11526 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11527 ProbeOpc = 11528 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11529 else 11530 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11531 // and NegSizeReg will be allocated in the same phyreg to avoid 11532 // redundant copy when NegSizeReg has only one use which is current MI and 11533 // will be replaced by PREPARE_PROBED_ALLOCA then. 11534 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11535 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11536 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11537 .addDef(ActualNegSizeReg) 11538 .addReg(NegSizeReg) 11539 .add(MI.getOperand(2)) 11540 .add(MI.getOperand(3)); 11541 11542 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11543 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11544 FinalStackPtr) 11545 .addReg(SPReg) 11546 .addReg(ActualNegSizeReg); 11547 11548 // Materialize a scratch register for update. 11549 int64_t NegProbeSize = -(int64_t)ProbeSize; 11550 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11551 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11552 if (!isInt<16>(NegProbeSize)) { 11553 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11554 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11555 .addImm(NegProbeSize >> 16); 11556 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11557 ScratchReg) 11558 .addReg(TempReg) 11559 .addImm(NegProbeSize & 0xFFFF); 11560 } else 11561 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11562 .addImm(NegProbeSize); 11563 11564 { 11565 // Probing leading residual part. 11566 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11567 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11568 .addReg(ActualNegSizeReg) 11569 .addReg(ScratchReg); 11570 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11571 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11572 .addReg(Div) 11573 .addReg(ScratchReg); 11574 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11575 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11576 .addReg(Mul) 11577 .addReg(ActualNegSizeReg); 11578 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11579 .addReg(FramePointer) 11580 .addReg(SPReg) 11581 .addReg(NegMod); 11582 } 11583 11584 { 11585 // Remaining part should be multiple of ProbeSize. 11586 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11587 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11588 .addReg(SPReg) 11589 .addReg(FinalStackPtr); 11590 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11591 .addImm(PPC::PRED_EQ) 11592 .addReg(CmpResult) 11593 .addMBB(TailMBB); 11594 TestMBB->addSuccessor(BlockMBB); 11595 TestMBB->addSuccessor(TailMBB); 11596 } 11597 11598 { 11599 // Touch the block. 11600 // |P...|P...|P... 11601 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11602 .addReg(FramePointer) 11603 .addReg(SPReg) 11604 .addReg(ScratchReg); 11605 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11606 BlockMBB->addSuccessor(TestMBB); 11607 } 11608 11609 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11610 // DYNAREAOFFSET pseudo instruction to get the future result. 11611 Register MaxCallFrameSizeReg = 11612 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11613 BuildMI(TailMBB, DL, 11614 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11615 MaxCallFrameSizeReg) 11616 .add(MI.getOperand(2)) 11617 .add(MI.getOperand(3)); 11618 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11619 .addReg(SPReg) 11620 .addReg(MaxCallFrameSizeReg); 11621 11622 // Splice instructions after MI to TailMBB. 11623 TailMBB->splice(TailMBB->end(), MBB, 11624 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11625 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11626 MBB->addSuccessor(TestMBB); 11627 11628 // Delete the pseudo instruction. 11629 MI.eraseFromParent(); 11630 11631 ++NumDynamicAllocaProbed; 11632 return TailMBB; 11633 } 11634 11635 MachineBasicBlock * 11636 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11637 MachineBasicBlock *BB) const { 11638 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11639 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11640 if (Subtarget.is64BitELFABI() && 11641 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11642 !Subtarget.isUsingPCRelativeCalls()) { 11643 // Call lowering should have added an r2 operand to indicate a dependence 11644 // on the TOC base pointer value. It can't however, because there is no 11645 // way to mark the dependence as implicit there, and so the stackmap code 11646 // will confuse it with a regular operand. Instead, add the dependence 11647 // here. 11648 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11649 } 11650 11651 return emitPatchPoint(MI, BB); 11652 } 11653 11654 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11655 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11656 return emitEHSjLjSetJmp(MI, BB); 11657 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11658 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11659 return emitEHSjLjLongJmp(MI, BB); 11660 } 11661 11662 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11663 11664 // To "insert" these instructions we actually have to insert their 11665 // control-flow patterns. 11666 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11667 MachineFunction::iterator It = ++BB->getIterator(); 11668 11669 MachineFunction *F = BB->getParent(); 11670 11671 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11672 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11673 MI.getOpcode() == PPC::SELECT_I8) { 11674 SmallVector<MachineOperand, 2> Cond; 11675 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11676 MI.getOpcode() == PPC::SELECT_CC_I8) 11677 Cond.push_back(MI.getOperand(4)); 11678 else 11679 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11680 Cond.push_back(MI.getOperand(1)); 11681 11682 DebugLoc dl = MI.getDebugLoc(); 11683 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11684 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11685 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11686 MI.getOpcode() == PPC::SELECT_CC_F8 || 11687 MI.getOpcode() == PPC::SELECT_CC_F16 || 11688 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11689 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11690 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11691 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11692 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11693 MI.getOpcode() == PPC::SELECT_CC_SPE || 11694 MI.getOpcode() == PPC::SELECT_F4 || 11695 MI.getOpcode() == PPC::SELECT_F8 || 11696 MI.getOpcode() == PPC::SELECT_F16 || 11697 MI.getOpcode() == PPC::SELECT_SPE || 11698 MI.getOpcode() == PPC::SELECT_SPE4 || 11699 MI.getOpcode() == PPC::SELECT_VRRC || 11700 MI.getOpcode() == PPC::SELECT_VSFRC || 11701 MI.getOpcode() == PPC::SELECT_VSSRC || 11702 MI.getOpcode() == PPC::SELECT_VSRC) { 11703 // The incoming instruction knows the destination vreg to set, the 11704 // condition code register to branch on, the true/false values to 11705 // select between, and a branch opcode to use. 11706 11707 // thisMBB: 11708 // ... 11709 // TrueVal = ... 11710 // cmpTY ccX, r1, r2 11711 // bCC copy1MBB 11712 // fallthrough --> copy0MBB 11713 MachineBasicBlock *thisMBB = BB; 11714 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11715 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11716 DebugLoc dl = MI.getDebugLoc(); 11717 F->insert(It, copy0MBB); 11718 F->insert(It, sinkMBB); 11719 11720 // Transfer the remainder of BB and its successor edges to sinkMBB. 11721 sinkMBB->splice(sinkMBB->begin(), BB, 11722 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11723 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11724 11725 // Next, add the true and fallthrough blocks as its successors. 11726 BB->addSuccessor(copy0MBB); 11727 BB->addSuccessor(sinkMBB); 11728 11729 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11730 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11731 MI.getOpcode() == PPC::SELECT_F16 || 11732 MI.getOpcode() == PPC::SELECT_SPE4 || 11733 MI.getOpcode() == PPC::SELECT_SPE || 11734 MI.getOpcode() == PPC::SELECT_VRRC || 11735 MI.getOpcode() == PPC::SELECT_VSFRC || 11736 MI.getOpcode() == PPC::SELECT_VSSRC || 11737 MI.getOpcode() == PPC::SELECT_VSRC) { 11738 BuildMI(BB, dl, TII->get(PPC::BC)) 11739 .addReg(MI.getOperand(1).getReg()) 11740 .addMBB(sinkMBB); 11741 } else { 11742 unsigned SelectPred = MI.getOperand(4).getImm(); 11743 BuildMI(BB, dl, TII->get(PPC::BCC)) 11744 .addImm(SelectPred) 11745 .addReg(MI.getOperand(1).getReg()) 11746 .addMBB(sinkMBB); 11747 } 11748 11749 // copy0MBB: 11750 // %FalseValue = ... 11751 // # fallthrough to sinkMBB 11752 BB = copy0MBB; 11753 11754 // Update machine-CFG edges 11755 BB->addSuccessor(sinkMBB); 11756 11757 // sinkMBB: 11758 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11759 // ... 11760 BB = sinkMBB; 11761 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11762 .addReg(MI.getOperand(3).getReg()) 11763 .addMBB(copy0MBB) 11764 .addReg(MI.getOperand(2).getReg()) 11765 .addMBB(thisMBB); 11766 } else if (MI.getOpcode() == PPC::ReadTB) { 11767 // To read the 64-bit time-base register on a 32-bit target, we read the 11768 // two halves. Should the counter have wrapped while it was being read, we 11769 // need to try again. 11770 // ... 11771 // readLoop: 11772 // mfspr Rx,TBU # load from TBU 11773 // mfspr Ry,TB # load from TB 11774 // mfspr Rz,TBU # load from TBU 11775 // cmpw crX,Rx,Rz # check if 'old'='new' 11776 // bne readLoop # branch if they're not equal 11777 // ... 11778 11779 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11780 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11781 DebugLoc dl = MI.getDebugLoc(); 11782 F->insert(It, readMBB); 11783 F->insert(It, sinkMBB); 11784 11785 // Transfer the remainder of BB and its successor edges to sinkMBB. 11786 sinkMBB->splice(sinkMBB->begin(), BB, 11787 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11788 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11789 11790 BB->addSuccessor(readMBB); 11791 BB = readMBB; 11792 11793 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11794 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11795 Register LoReg = MI.getOperand(0).getReg(); 11796 Register HiReg = MI.getOperand(1).getReg(); 11797 11798 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11799 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11800 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11801 11802 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11803 11804 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11805 .addReg(HiReg) 11806 .addReg(ReadAgainReg); 11807 BuildMI(BB, dl, TII->get(PPC::BCC)) 11808 .addImm(PPC::PRED_NE) 11809 .addReg(CmpReg) 11810 .addMBB(readMBB); 11811 11812 BB->addSuccessor(readMBB); 11813 BB->addSuccessor(sinkMBB); 11814 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11815 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11817 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11819 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11821 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11822 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11824 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11826 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11828 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11830 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11831 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11833 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11835 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11837 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11839 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11840 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11842 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11844 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11846 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11848 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11849 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11851 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11853 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11855 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11857 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11858 11859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11860 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11862 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11863 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11864 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11866 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11867 11868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11869 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11871 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11872 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11873 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11874 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11875 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11876 11877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11878 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11880 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11881 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11882 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11883 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11884 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11885 11886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11887 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11889 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11890 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11891 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11892 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11893 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11894 11895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11896 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11898 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11899 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11900 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11901 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11902 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11903 11904 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11905 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11906 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11907 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11908 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11909 BB = EmitAtomicBinary(MI, BB, 4, 0); 11910 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11911 BB = EmitAtomicBinary(MI, BB, 8, 0); 11912 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11913 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11914 (Subtarget.hasPartwordAtomics() && 11915 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11916 (Subtarget.hasPartwordAtomics() && 11917 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11918 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11919 11920 auto LoadMnemonic = PPC::LDARX; 11921 auto StoreMnemonic = PPC::STDCX; 11922 switch (MI.getOpcode()) { 11923 default: 11924 llvm_unreachable("Compare and swap of unknown size"); 11925 case PPC::ATOMIC_CMP_SWAP_I8: 11926 LoadMnemonic = PPC::LBARX; 11927 StoreMnemonic = PPC::STBCX; 11928 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11929 break; 11930 case PPC::ATOMIC_CMP_SWAP_I16: 11931 LoadMnemonic = PPC::LHARX; 11932 StoreMnemonic = PPC::STHCX; 11933 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11934 break; 11935 case PPC::ATOMIC_CMP_SWAP_I32: 11936 LoadMnemonic = PPC::LWARX; 11937 StoreMnemonic = PPC::STWCX; 11938 break; 11939 case PPC::ATOMIC_CMP_SWAP_I64: 11940 LoadMnemonic = PPC::LDARX; 11941 StoreMnemonic = PPC::STDCX; 11942 break; 11943 } 11944 Register dest = MI.getOperand(0).getReg(); 11945 Register ptrA = MI.getOperand(1).getReg(); 11946 Register ptrB = MI.getOperand(2).getReg(); 11947 Register oldval = MI.getOperand(3).getReg(); 11948 Register newval = MI.getOperand(4).getReg(); 11949 DebugLoc dl = MI.getDebugLoc(); 11950 11951 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11952 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11953 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11954 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11955 F->insert(It, loop1MBB); 11956 F->insert(It, loop2MBB); 11957 F->insert(It, midMBB); 11958 F->insert(It, exitMBB); 11959 exitMBB->splice(exitMBB->begin(), BB, 11960 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11961 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11962 11963 // thisMBB: 11964 // ... 11965 // fallthrough --> loopMBB 11966 BB->addSuccessor(loop1MBB); 11967 11968 // loop1MBB: 11969 // l[bhwd]arx dest, ptr 11970 // cmp[wd] dest, oldval 11971 // bne- midMBB 11972 // loop2MBB: 11973 // st[bhwd]cx. newval, ptr 11974 // bne- loopMBB 11975 // b exitBB 11976 // midMBB: 11977 // st[bhwd]cx. dest, ptr 11978 // exitBB: 11979 BB = loop1MBB; 11980 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11981 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11982 .addReg(oldval) 11983 .addReg(dest); 11984 BuildMI(BB, dl, TII->get(PPC::BCC)) 11985 .addImm(PPC::PRED_NE) 11986 .addReg(PPC::CR0) 11987 .addMBB(midMBB); 11988 BB->addSuccessor(loop2MBB); 11989 BB->addSuccessor(midMBB); 11990 11991 BB = loop2MBB; 11992 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11993 .addReg(newval) 11994 .addReg(ptrA) 11995 .addReg(ptrB); 11996 BuildMI(BB, dl, TII->get(PPC::BCC)) 11997 .addImm(PPC::PRED_NE) 11998 .addReg(PPC::CR0) 11999 .addMBB(loop1MBB); 12000 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12001 BB->addSuccessor(loop1MBB); 12002 BB->addSuccessor(exitMBB); 12003 12004 BB = midMBB; 12005 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12006 .addReg(dest) 12007 .addReg(ptrA) 12008 .addReg(ptrB); 12009 BB->addSuccessor(exitMBB); 12010 12011 // exitMBB: 12012 // ... 12013 BB = exitMBB; 12014 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12015 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12016 // We must use 64-bit registers for addresses when targeting 64-bit, 12017 // since we're actually doing arithmetic on them. Other registers 12018 // can be 32-bit. 12019 bool is64bit = Subtarget.isPPC64(); 12020 bool isLittleEndian = Subtarget.isLittleEndian(); 12021 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12022 12023 Register dest = MI.getOperand(0).getReg(); 12024 Register ptrA = MI.getOperand(1).getReg(); 12025 Register ptrB = MI.getOperand(2).getReg(); 12026 Register oldval = MI.getOperand(3).getReg(); 12027 Register newval = MI.getOperand(4).getReg(); 12028 DebugLoc dl = MI.getDebugLoc(); 12029 12030 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12031 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12032 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12033 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12034 F->insert(It, loop1MBB); 12035 F->insert(It, loop2MBB); 12036 F->insert(It, midMBB); 12037 F->insert(It, exitMBB); 12038 exitMBB->splice(exitMBB->begin(), BB, 12039 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12040 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12041 12042 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12043 const TargetRegisterClass *RC = 12044 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12045 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12046 12047 Register PtrReg = RegInfo.createVirtualRegister(RC); 12048 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12049 Register ShiftReg = 12050 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12051 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12052 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12053 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12054 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12055 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12056 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12057 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12058 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12059 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12060 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12061 Register Ptr1Reg; 12062 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12063 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12064 // thisMBB: 12065 // ... 12066 // fallthrough --> loopMBB 12067 BB->addSuccessor(loop1MBB); 12068 12069 // The 4-byte load must be aligned, while a char or short may be 12070 // anywhere in the word. Hence all this nasty bookkeeping code. 12071 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12072 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12073 // xori shift, shift1, 24 [16] 12074 // rlwinm ptr, ptr1, 0, 0, 29 12075 // slw newval2, newval, shift 12076 // slw oldval2, oldval,shift 12077 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12078 // slw mask, mask2, shift 12079 // and newval3, newval2, mask 12080 // and oldval3, oldval2, mask 12081 // loop1MBB: 12082 // lwarx tmpDest, ptr 12083 // and tmp, tmpDest, mask 12084 // cmpw tmp, oldval3 12085 // bne- midMBB 12086 // loop2MBB: 12087 // andc tmp2, tmpDest, mask 12088 // or tmp4, tmp2, newval3 12089 // stwcx. tmp4, ptr 12090 // bne- loop1MBB 12091 // b exitBB 12092 // midMBB: 12093 // stwcx. tmpDest, ptr 12094 // exitBB: 12095 // srw dest, tmpDest, shift 12096 if (ptrA != ZeroReg) { 12097 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12098 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12099 .addReg(ptrA) 12100 .addReg(ptrB); 12101 } else { 12102 Ptr1Reg = ptrB; 12103 } 12104 12105 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12106 // mode. 12107 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12108 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12109 .addImm(3) 12110 .addImm(27) 12111 .addImm(is8bit ? 28 : 27); 12112 if (!isLittleEndian) 12113 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12114 .addReg(Shift1Reg) 12115 .addImm(is8bit ? 24 : 16); 12116 if (is64bit) 12117 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12118 .addReg(Ptr1Reg) 12119 .addImm(0) 12120 .addImm(61); 12121 else 12122 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12123 .addReg(Ptr1Reg) 12124 .addImm(0) 12125 .addImm(0) 12126 .addImm(29); 12127 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12128 .addReg(newval) 12129 .addReg(ShiftReg); 12130 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12131 .addReg(oldval) 12132 .addReg(ShiftReg); 12133 if (is8bit) 12134 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12135 else { 12136 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12137 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12138 .addReg(Mask3Reg) 12139 .addImm(65535); 12140 } 12141 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12142 .addReg(Mask2Reg) 12143 .addReg(ShiftReg); 12144 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12145 .addReg(NewVal2Reg) 12146 .addReg(MaskReg); 12147 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12148 .addReg(OldVal2Reg) 12149 .addReg(MaskReg); 12150 12151 BB = loop1MBB; 12152 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12153 .addReg(ZeroReg) 12154 .addReg(PtrReg); 12155 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12156 .addReg(TmpDestReg) 12157 .addReg(MaskReg); 12158 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12159 .addReg(TmpReg) 12160 .addReg(OldVal3Reg); 12161 BuildMI(BB, dl, TII->get(PPC::BCC)) 12162 .addImm(PPC::PRED_NE) 12163 .addReg(PPC::CR0) 12164 .addMBB(midMBB); 12165 BB->addSuccessor(loop2MBB); 12166 BB->addSuccessor(midMBB); 12167 12168 BB = loop2MBB; 12169 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12170 .addReg(TmpDestReg) 12171 .addReg(MaskReg); 12172 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12173 .addReg(Tmp2Reg) 12174 .addReg(NewVal3Reg); 12175 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12176 .addReg(Tmp4Reg) 12177 .addReg(ZeroReg) 12178 .addReg(PtrReg); 12179 BuildMI(BB, dl, TII->get(PPC::BCC)) 12180 .addImm(PPC::PRED_NE) 12181 .addReg(PPC::CR0) 12182 .addMBB(loop1MBB); 12183 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12184 BB->addSuccessor(loop1MBB); 12185 BB->addSuccessor(exitMBB); 12186 12187 BB = midMBB; 12188 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12189 .addReg(TmpDestReg) 12190 .addReg(ZeroReg) 12191 .addReg(PtrReg); 12192 BB->addSuccessor(exitMBB); 12193 12194 // exitMBB: 12195 // ... 12196 BB = exitMBB; 12197 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12198 .addReg(TmpReg) 12199 .addReg(ShiftReg); 12200 } else if (MI.getOpcode() == PPC::FADDrtz) { 12201 // This pseudo performs an FADD with rounding mode temporarily forced 12202 // to round-to-zero. We emit this via custom inserter since the FPSCR 12203 // is not modeled at the SelectionDAG level. 12204 Register Dest = MI.getOperand(0).getReg(); 12205 Register Src1 = MI.getOperand(1).getReg(); 12206 Register Src2 = MI.getOperand(2).getReg(); 12207 DebugLoc dl = MI.getDebugLoc(); 12208 12209 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12210 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12211 12212 // Save FPSCR value. 12213 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12214 12215 // Set rounding mode to round-to-zero. 12216 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12217 .addImm(31) 12218 .addReg(PPC::RM, RegState::ImplicitDefine); 12219 12220 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12221 .addImm(30) 12222 .addReg(PPC::RM, RegState::ImplicitDefine); 12223 12224 // Perform addition. 12225 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12226 .addReg(Src1) 12227 .addReg(Src2); 12228 if (MI.getFlag(MachineInstr::NoFPExcept)) 12229 MIB.setMIFlag(MachineInstr::NoFPExcept); 12230 12231 // Restore FPSCR value. 12232 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12233 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12234 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12235 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12236 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12237 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12238 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12239 ? PPC::ANDI8_rec 12240 : PPC::ANDI_rec; 12241 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12242 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12243 12244 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12245 Register Dest = RegInfo.createVirtualRegister( 12246 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12247 12248 DebugLoc Dl = MI.getDebugLoc(); 12249 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12250 .addReg(MI.getOperand(1).getReg()) 12251 .addImm(1); 12252 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12253 MI.getOperand(0).getReg()) 12254 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12255 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12256 DebugLoc Dl = MI.getDebugLoc(); 12257 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12258 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12259 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12260 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12261 MI.getOperand(0).getReg()) 12262 .addReg(CRReg); 12263 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12264 DebugLoc Dl = MI.getDebugLoc(); 12265 unsigned Imm = MI.getOperand(1).getImm(); 12266 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12267 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12268 MI.getOperand(0).getReg()) 12269 .addReg(PPC::CR0EQ); 12270 } else if (MI.getOpcode() == PPC::SETRNDi) { 12271 DebugLoc dl = MI.getDebugLoc(); 12272 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12273 12274 // Save FPSCR value. 12275 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12276 12277 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12278 // the following settings: 12279 // 00 Round to nearest 12280 // 01 Round to 0 12281 // 10 Round to +inf 12282 // 11 Round to -inf 12283 12284 // When the operand is immediate, using the two least significant bits of 12285 // the immediate to set the bits 62:63 of FPSCR. 12286 unsigned Mode = MI.getOperand(1).getImm(); 12287 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12288 .addImm(31) 12289 .addReg(PPC::RM, RegState::ImplicitDefine); 12290 12291 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12292 .addImm(30) 12293 .addReg(PPC::RM, RegState::ImplicitDefine); 12294 } else if (MI.getOpcode() == PPC::SETRND) { 12295 DebugLoc dl = MI.getDebugLoc(); 12296 12297 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12298 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12299 // If the target doesn't have DirectMove, we should use stack to do the 12300 // conversion, because the target doesn't have the instructions like mtvsrd 12301 // or mfvsrd to do this conversion directly. 12302 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12303 if (Subtarget.hasDirectMove()) { 12304 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12305 .addReg(SrcReg); 12306 } else { 12307 // Use stack to do the register copy. 12308 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12309 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12310 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12311 if (RC == &PPC::F8RCRegClass) { 12312 // Copy register from F8RCRegClass to G8RCRegclass. 12313 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12314 "Unsupported RegClass."); 12315 12316 StoreOp = PPC::STFD; 12317 LoadOp = PPC::LD; 12318 } else { 12319 // Copy register from G8RCRegClass to F8RCRegclass. 12320 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12321 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12322 "Unsupported RegClass."); 12323 } 12324 12325 MachineFrameInfo &MFI = F->getFrameInfo(); 12326 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12327 12328 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12329 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12330 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12331 MFI.getObjectAlign(FrameIdx)); 12332 12333 // Store the SrcReg into the stack. 12334 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12335 .addReg(SrcReg) 12336 .addImm(0) 12337 .addFrameIndex(FrameIdx) 12338 .addMemOperand(MMOStore); 12339 12340 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12341 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12342 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12343 MFI.getObjectAlign(FrameIdx)); 12344 12345 // Load from the stack where SrcReg is stored, and save to DestReg, 12346 // so we have done the RegClass conversion from RegClass::SrcReg to 12347 // RegClass::DestReg. 12348 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12349 .addImm(0) 12350 .addFrameIndex(FrameIdx) 12351 .addMemOperand(MMOLoad); 12352 } 12353 }; 12354 12355 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12356 12357 // Save FPSCR value. 12358 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12359 12360 // When the operand is gprc register, use two least significant bits of the 12361 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12362 // 12363 // copy OldFPSCRTmpReg, OldFPSCRReg 12364 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12365 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12366 // copy NewFPSCRReg, NewFPSCRTmpReg 12367 // mtfsf 255, NewFPSCRReg 12368 MachineOperand SrcOp = MI.getOperand(1); 12369 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12370 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12371 12372 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12373 12374 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12375 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12376 12377 // The first operand of INSERT_SUBREG should be a register which has 12378 // subregisters, we only care about its RegClass, so we should use an 12379 // IMPLICIT_DEF register. 12380 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12381 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12382 .addReg(ImDefReg) 12383 .add(SrcOp) 12384 .addImm(1); 12385 12386 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12387 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12388 .addReg(OldFPSCRTmpReg) 12389 .addReg(ExtSrcReg) 12390 .addImm(0) 12391 .addImm(62); 12392 12393 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12394 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12395 12396 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12397 // bits of FPSCR. 12398 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12399 .addImm(255) 12400 .addReg(NewFPSCRReg) 12401 .addImm(0) 12402 .addImm(0); 12403 } else if (MI.getOpcode() == PPC::SETFLM) { 12404 DebugLoc Dl = MI.getDebugLoc(); 12405 12406 // Result of setflm is previous FPSCR content, so we need to save it first. 12407 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12408 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12409 12410 // Put bits in 32:63 to FPSCR. 12411 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12412 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12413 .addImm(255) 12414 .addReg(NewFPSCRReg) 12415 .addImm(0) 12416 .addImm(0); 12417 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12418 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12419 return emitProbedAlloca(MI, BB); 12420 } else { 12421 llvm_unreachable("Unexpected instr type to insert"); 12422 } 12423 12424 MI.eraseFromParent(); // The pseudo instruction is gone now. 12425 return BB; 12426 } 12427 12428 //===----------------------------------------------------------------------===// 12429 // Target Optimization Hooks 12430 //===----------------------------------------------------------------------===// 12431 12432 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12433 // For the estimates, convergence is quadratic, so we essentially double the 12434 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12435 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12436 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12437 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12438 if (VT.getScalarType() == MVT::f64) 12439 RefinementSteps++; 12440 return RefinementSteps; 12441 } 12442 12443 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12444 int Enabled, int &RefinementSteps, 12445 bool &UseOneConstNR, 12446 bool Reciprocal) const { 12447 EVT VT = Operand.getValueType(); 12448 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12449 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12450 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12451 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12452 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12453 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12454 12455 // The Newton-Raphson computation with a single constant does not provide 12456 // enough accuracy on some CPUs. 12457 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12458 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12459 } 12460 return SDValue(); 12461 } 12462 12463 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12464 int Enabled, 12465 int &RefinementSteps) const { 12466 EVT VT = Operand.getValueType(); 12467 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12468 (VT == MVT::f64 && Subtarget.hasFRE()) || 12469 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12470 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12471 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12472 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12473 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12474 } 12475 return SDValue(); 12476 } 12477 12478 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12479 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12480 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12481 // enabled for division), this functionality is redundant with the default 12482 // combiner logic (once the division -> reciprocal/multiply transformation 12483 // has taken place). As a result, this matters more for older cores than for 12484 // newer ones. 12485 12486 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12487 // reciprocal if there are two or more FDIVs (for embedded cores with only 12488 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12489 switch (Subtarget.getCPUDirective()) { 12490 default: 12491 return 3; 12492 case PPC::DIR_440: 12493 case PPC::DIR_A2: 12494 case PPC::DIR_E500: 12495 case PPC::DIR_E500mc: 12496 case PPC::DIR_E5500: 12497 return 2; 12498 } 12499 } 12500 12501 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12502 // collapsed, and so we need to look through chains of them. 12503 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12504 int64_t& Offset, SelectionDAG &DAG) { 12505 if (DAG.isBaseWithConstantOffset(Loc)) { 12506 Base = Loc.getOperand(0); 12507 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12508 12509 // The base might itself be a base plus an offset, and if so, accumulate 12510 // that as well. 12511 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12512 } 12513 } 12514 12515 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12516 unsigned Bytes, int Dist, 12517 SelectionDAG &DAG) { 12518 if (VT.getSizeInBits() / 8 != Bytes) 12519 return false; 12520 12521 SDValue BaseLoc = Base->getBasePtr(); 12522 if (Loc.getOpcode() == ISD::FrameIndex) { 12523 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12524 return false; 12525 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12526 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12527 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12528 int FS = MFI.getObjectSize(FI); 12529 int BFS = MFI.getObjectSize(BFI); 12530 if (FS != BFS || FS != (int)Bytes) return false; 12531 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12532 } 12533 12534 SDValue Base1 = Loc, Base2 = BaseLoc; 12535 int64_t Offset1 = 0, Offset2 = 0; 12536 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12537 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12538 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12539 return true; 12540 12541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12542 const GlobalValue *GV1 = nullptr; 12543 const GlobalValue *GV2 = nullptr; 12544 Offset1 = 0; 12545 Offset2 = 0; 12546 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12547 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12548 if (isGA1 && isGA2 && GV1 == GV2) 12549 return Offset1 == (Offset2 + Dist*Bytes); 12550 return false; 12551 } 12552 12553 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12554 // not enforce equality of the chain operands. 12555 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12556 unsigned Bytes, int Dist, 12557 SelectionDAG &DAG) { 12558 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12559 EVT VT = LS->getMemoryVT(); 12560 SDValue Loc = LS->getBasePtr(); 12561 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12562 } 12563 12564 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12565 EVT VT; 12566 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12567 default: return false; 12568 case Intrinsic::ppc_altivec_lvx: 12569 case Intrinsic::ppc_altivec_lvxl: 12570 case Intrinsic::ppc_vsx_lxvw4x: 12571 case Intrinsic::ppc_vsx_lxvw4x_be: 12572 VT = MVT::v4i32; 12573 break; 12574 case Intrinsic::ppc_vsx_lxvd2x: 12575 case Intrinsic::ppc_vsx_lxvd2x_be: 12576 VT = MVT::v2f64; 12577 break; 12578 case Intrinsic::ppc_altivec_lvebx: 12579 VT = MVT::i8; 12580 break; 12581 case Intrinsic::ppc_altivec_lvehx: 12582 VT = MVT::i16; 12583 break; 12584 case Intrinsic::ppc_altivec_lvewx: 12585 VT = MVT::i32; 12586 break; 12587 } 12588 12589 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12590 } 12591 12592 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12593 EVT VT; 12594 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12595 default: return false; 12596 case Intrinsic::ppc_altivec_stvx: 12597 case Intrinsic::ppc_altivec_stvxl: 12598 case Intrinsic::ppc_vsx_stxvw4x: 12599 VT = MVT::v4i32; 12600 break; 12601 case Intrinsic::ppc_vsx_stxvd2x: 12602 VT = MVT::v2f64; 12603 break; 12604 case Intrinsic::ppc_vsx_stxvw4x_be: 12605 VT = MVT::v4i32; 12606 break; 12607 case Intrinsic::ppc_vsx_stxvd2x_be: 12608 VT = MVT::v2f64; 12609 break; 12610 case Intrinsic::ppc_altivec_stvebx: 12611 VT = MVT::i8; 12612 break; 12613 case Intrinsic::ppc_altivec_stvehx: 12614 VT = MVT::i16; 12615 break; 12616 case Intrinsic::ppc_altivec_stvewx: 12617 VT = MVT::i32; 12618 break; 12619 } 12620 12621 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12622 } 12623 12624 return false; 12625 } 12626 12627 // Return true is there is a nearyby consecutive load to the one provided 12628 // (regardless of alignment). We search up and down the chain, looking though 12629 // token factors and other loads (but nothing else). As a result, a true result 12630 // indicates that it is safe to create a new consecutive load adjacent to the 12631 // load provided. 12632 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12633 SDValue Chain = LD->getChain(); 12634 EVT VT = LD->getMemoryVT(); 12635 12636 SmallSet<SDNode *, 16> LoadRoots; 12637 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12638 SmallSet<SDNode *, 16> Visited; 12639 12640 // First, search up the chain, branching to follow all token-factor operands. 12641 // If we find a consecutive load, then we're done, otherwise, record all 12642 // nodes just above the top-level loads and token factors. 12643 while (!Queue.empty()) { 12644 SDNode *ChainNext = Queue.pop_back_val(); 12645 if (!Visited.insert(ChainNext).second) 12646 continue; 12647 12648 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12649 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12650 return true; 12651 12652 if (!Visited.count(ChainLD->getChain().getNode())) 12653 Queue.push_back(ChainLD->getChain().getNode()); 12654 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12655 for (const SDUse &O : ChainNext->ops()) 12656 if (!Visited.count(O.getNode())) 12657 Queue.push_back(O.getNode()); 12658 } else 12659 LoadRoots.insert(ChainNext); 12660 } 12661 12662 // Second, search down the chain, starting from the top-level nodes recorded 12663 // in the first phase. These top-level nodes are the nodes just above all 12664 // loads and token factors. Starting with their uses, recursively look though 12665 // all loads (just the chain uses) and token factors to find a consecutive 12666 // load. 12667 Visited.clear(); 12668 Queue.clear(); 12669 12670 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12671 IE = LoadRoots.end(); I != IE; ++I) { 12672 Queue.push_back(*I); 12673 12674 while (!Queue.empty()) { 12675 SDNode *LoadRoot = Queue.pop_back_val(); 12676 if (!Visited.insert(LoadRoot).second) 12677 continue; 12678 12679 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12680 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12681 return true; 12682 12683 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12684 UE = LoadRoot->use_end(); UI != UE; ++UI) 12685 if (((isa<MemSDNode>(*UI) && 12686 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12687 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12688 Queue.push_back(*UI); 12689 } 12690 } 12691 12692 return false; 12693 } 12694 12695 /// This function is called when we have proved that a SETCC node can be replaced 12696 /// by subtraction (and other supporting instructions) so that the result of 12697 /// comparison is kept in a GPR instead of CR. This function is purely for 12698 /// codegen purposes and has some flags to guide the codegen process. 12699 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12700 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12701 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12702 12703 // Zero extend the operands to the largest legal integer. Originally, they 12704 // must be of a strictly smaller size. 12705 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12706 DAG.getConstant(Size, DL, MVT::i32)); 12707 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12708 DAG.getConstant(Size, DL, MVT::i32)); 12709 12710 // Swap if needed. Depends on the condition code. 12711 if (Swap) 12712 std::swap(Op0, Op1); 12713 12714 // Subtract extended integers. 12715 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12716 12717 // Move the sign bit to the least significant position and zero out the rest. 12718 // Now the least significant bit carries the result of original comparison. 12719 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12720 DAG.getConstant(Size - 1, DL, MVT::i32)); 12721 auto Final = Shifted; 12722 12723 // Complement the result if needed. Based on the condition code. 12724 if (Complement) 12725 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12726 DAG.getConstant(1, DL, MVT::i64)); 12727 12728 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12729 } 12730 12731 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12732 DAGCombinerInfo &DCI) const { 12733 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12734 12735 SelectionDAG &DAG = DCI.DAG; 12736 SDLoc DL(N); 12737 12738 // Size of integers being compared has a critical role in the following 12739 // analysis, so we prefer to do this when all types are legal. 12740 if (!DCI.isAfterLegalizeDAG()) 12741 return SDValue(); 12742 12743 // If all users of SETCC extend its value to a legal integer type 12744 // then we replace SETCC with a subtraction 12745 for (SDNode::use_iterator UI = N->use_begin(), 12746 UE = N->use_end(); UI != UE; ++UI) { 12747 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12748 return SDValue(); 12749 } 12750 12751 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12752 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12753 12754 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12755 12756 if (OpSize < Size) { 12757 switch (CC) { 12758 default: break; 12759 case ISD::SETULT: 12760 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12761 case ISD::SETULE: 12762 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12763 case ISD::SETUGT: 12764 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12765 case ISD::SETUGE: 12766 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12767 } 12768 } 12769 12770 return SDValue(); 12771 } 12772 12773 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12774 DAGCombinerInfo &DCI) const { 12775 SelectionDAG &DAG = DCI.DAG; 12776 SDLoc dl(N); 12777 12778 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12779 // If we're tracking CR bits, we need to be careful that we don't have: 12780 // trunc(binary-ops(zext(x), zext(y))) 12781 // or 12782 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12783 // such that we're unnecessarily moving things into GPRs when it would be 12784 // better to keep them in CR bits. 12785 12786 // Note that trunc here can be an actual i1 trunc, or can be the effective 12787 // truncation that comes from a setcc or select_cc. 12788 if (N->getOpcode() == ISD::TRUNCATE && 12789 N->getValueType(0) != MVT::i1) 12790 return SDValue(); 12791 12792 if (N->getOperand(0).getValueType() != MVT::i32 && 12793 N->getOperand(0).getValueType() != MVT::i64) 12794 return SDValue(); 12795 12796 if (N->getOpcode() == ISD::SETCC || 12797 N->getOpcode() == ISD::SELECT_CC) { 12798 // If we're looking at a comparison, then we need to make sure that the 12799 // high bits (all except for the first) don't matter the result. 12800 ISD::CondCode CC = 12801 cast<CondCodeSDNode>(N->getOperand( 12802 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12803 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12804 12805 if (ISD::isSignedIntSetCC(CC)) { 12806 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12807 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12808 return SDValue(); 12809 } else if (ISD::isUnsignedIntSetCC(CC)) { 12810 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12811 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12812 !DAG.MaskedValueIsZero(N->getOperand(1), 12813 APInt::getHighBitsSet(OpBits, OpBits-1))) 12814 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12815 : SDValue()); 12816 } else { 12817 // This is neither a signed nor an unsigned comparison, just make sure 12818 // that the high bits are equal. 12819 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12820 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12821 12822 // We don't really care about what is known about the first bit (if 12823 // anything), so clear it in all masks prior to comparing them. 12824 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12825 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12826 12827 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12828 return SDValue(); 12829 } 12830 } 12831 12832 // We now know that the higher-order bits are irrelevant, we just need to 12833 // make sure that all of the intermediate operations are bit operations, and 12834 // all inputs are extensions. 12835 if (N->getOperand(0).getOpcode() != ISD::AND && 12836 N->getOperand(0).getOpcode() != ISD::OR && 12837 N->getOperand(0).getOpcode() != ISD::XOR && 12838 N->getOperand(0).getOpcode() != ISD::SELECT && 12839 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12840 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12841 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12842 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12843 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12844 return SDValue(); 12845 12846 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12847 N->getOperand(1).getOpcode() != ISD::AND && 12848 N->getOperand(1).getOpcode() != ISD::OR && 12849 N->getOperand(1).getOpcode() != ISD::XOR && 12850 N->getOperand(1).getOpcode() != ISD::SELECT && 12851 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12852 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12853 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12854 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12855 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12856 return SDValue(); 12857 12858 SmallVector<SDValue, 4> Inputs; 12859 SmallVector<SDValue, 8> BinOps, PromOps; 12860 SmallPtrSet<SDNode *, 16> Visited; 12861 12862 for (unsigned i = 0; i < 2; ++i) { 12863 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12864 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12865 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12866 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12867 isa<ConstantSDNode>(N->getOperand(i))) 12868 Inputs.push_back(N->getOperand(i)); 12869 else 12870 BinOps.push_back(N->getOperand(i)); 12871 12872 if (N->getOpcode() == ISD::TRUNCATE) 12873 break; 12874 } 12875 12876 // Visit all inputs, collect all binary operations (and, or, xor and 12877 // select) that are all fed by extensions. 12878 while (!BinOps.empty()) { 12879 SDValue BinOp = BinOps.back(); 12880 BinOps.pop_back(); 12881 12882 if (!Visited.insert(BinOp.getNode()).second) 12883 continue; 12884 12885 PromOps.push_back(BinOp); 12886 12887 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12888 // The condition of the select is not promoted. 12889 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12890 continue; 12891 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12892 continue; 12893 12894 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12895 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12896 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12897 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12898 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12899 Inputs.push_back(BinOp.getOperand(i)); 12900 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12901 BinOp.getOperand(i).getOpcode() == ISD::OR || 12902 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12903 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12904 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12905 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12906 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12907 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12908 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12909 BinOps.push_back(BinOp.getOperand(i)); 12910 } else { 12911 // We have an input that is not an extension or another binary 12912 // operation; we'll abort this transformation. 12913 return SDValue(); 12914 } 12915 } 12916 } 12917 12918 // Make sure that this is a self-contained cluster of operations (which 12919 // is not quite the same thing as saying that everything has only one 12920 // use). 12921 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12922 if (isa<ConstantSDNode>(Inputs[i])) 12923 continue; 12924 12925 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12926 UE = Inputs[i].getNode()->use_end(); 12927 UI != UE; ++UI) { 12928 SDNode *User = *UI; 12929 if (User != N && !Visited.count(User)) 12930 return SDValue(); 12931 12932 // Make sure that we're not going to promote the non-output-value 12933 // operand(s) or SELECT or SELECT_CC. 12934 // FIXME: Although we could sometimes handle this, and it does occur in 12935 // practice that one of the condition inputs to the select is also one of 12936 // the outputs, we currently can't deal with this. 12937 if (User->getOpcode() == ISD::SELECT) { 12938 if (User->getOperand(0) == Inputs[i]) 12939 return SDValue(); 12940 } else if (User->getOpcode() == ISD::SELECT_CC) { 12941 if (User->getOperand(0) == Inputs[i] || 12942 User->getOperand(1) == Inputs[i]) 12943 return SDValue(); 12944 } 12945 } 12946 } 12947 12948 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12949 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12950 UE = PromOps[i].getNode()->use_end(); 12951 UI != UE; ++UI) { 12952 SDNode *User = *UI; 12953 if (User != N && !Visited.count(User)) 12954 return SDValue(); 12955 12956 // Make sure that we're not going to promote the non-output-value 12957 // operand(s) or SELECT or SELECT_CC. 12958 // FIXME: Although we could sometimes handle this, and it does occur in 12959 // practice that one of the condition inputs to the select is also one of 12960 // the outputs, we currently can't deal with this. 12961 if (User->getOpcode() == ISD::SELECT) { 12962 if (User->getOperand(0) == PromOps[i]) 12963 return SDValue(); 12964 } else if (User->getOpcode() == ISD::SELECT_CC) { 12965 if (User->getOperand(0) == PromOps[i] || 12966 User->getOperand(1) == PromOps[i]) 12967 return SDValue(); 12968 } 12969 } 12970 } 12971 12972 // Replace all inputs with the extension operand. 12973 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12974 // Constants may have users outside the cluster of to-be-promoted nodes, 12975 // and so we need to replace those as we do the promotions. 12976 if (isa<ConstantSDNode>(Inputs[i])) 12977 continue; 12978 else 12979 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12980 } 12981 12982 std::list<HandleSDNode> PromOpHandles; 12983 for (auto &PromOp : PromOps) 12984 PromOpHandles.emplace_back(PromOp); 12985 12986 // Replace all operations (these are all the same, but have a different 12987 // (i1) return type). DAG.getNode will validate that the types of 12988 // a binary operator match, so go through the list in reverse so that 12989 // we've likely promoted both operands first. Any intermediate truncations or 12990 // extensions disappear. 12991 while (!PromOpHandles.empty()) { 12992 SDValue PromOp = PromOpHandles.back().getValue(); 12993 PromOpHandles.pop_back(); 12994 12995 if (PromOp.getOpcode() == ISD::TRUNCATE || 12996 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12997 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12998 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12999 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13000 PromOp.getOperand(0).getValueType() != MVT::i1) { 13001 // The operand is not yet ready (see comment below). 13002 PromOpHandles.emplace_front(PromOp); 13003 continue; 13004 } 13005 13006 SDValue RepValue = PromOp.getOperand(0); 13007 if (isa<ConstantSDNode>(RepValue)) 13008 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13009 13010 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13011 continue; 13012 } 13013 13014 unsigned C; 13015 switch (PromOp.getOpcode()) { 13016 default: C = 0; break; 13017 case ISD::SELECT: C = 1; break; 13018 case ISD::SELECT_CC: C = 2; break; 13019 } 13020 13021 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13022 PromOp.getOperand(C).getValueType() != MVT::i1) || 13023 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13024 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13025 // The to-be-promoted operands of this node have not yet been 13026 // promoted (this should be rare because we're going through the 13027 // list backward, but if one of the operands has several users in 13028 // this cluster of to-be-promoted nodes, it is possible). 13029 PromOpHandles.emplace_front(PromOp); 13030 continue; 13031 } 13032 13033 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13034 PromOp.getNode()->op_end()); 13035 13036 // If there are any constant inputs, make sure they're replaced now. 13037 for (unsigned i = 0; i < 2; ++i) 13038 if (isa<ConstantSDNode>(Ops[C+i])) 13039 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13040 13041 DAG.ReplaceAllUsesOfValueWith(PromOp, 13042 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13043 } 13044 13045 // Now we're left with the initial truncation itself. 13046 if (N->getOpcode() == ISD::TRUNCATE) 13047 return N->getOperand(0); 13048 13049 // Otherwise, this is a comparison. The operands to be compared have just 13050 // changed type (to i1), but everything else is the same. 13051 return SDValue(N, 0); 13052 } 13053 13054 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13055 DAGCombinerInfo &DCI) const { 13056 SelectionDAG &DAG = DCI.DAG; 13057 SDLoc dl(N); 13058 13059 // If we're tracking CR bits, we need to be careful that we don't have: 13060 // zext(binary-ops(trunc(x), trunc(y))) 13061 // or 13062 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13063 // such that we're unnecessarily moving things into CR bits that can more 13064 // efficiently stay in GPRs. Note that if we're not certain that the high 13065 // bits are set as required by the final extension, we still may need to do 13066 // some masking to get the proper behavior. 13067 13068 // This same functionality is important on PPC64 when dealing with 13069 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13070 // the return values of functions. Because it is so similar, it is handled 13071 // here as well. 13072 13073 if (N->getValueType(0) != MVT::i32 && 13074 N->getValueType(0) != MVT::i64) 13075 return SDValue(); 13076 13077 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13078 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13079 return SDValue(); 13080 13081 if (N->getOperand(0).getOpcode() != ISD::AND && 13082 N->getOperand(0).getOpcode() != ISD::OR && 13083 N->getOperand(0).getOpcode() != ISD::XOR && 13084 N->getOperand(0).getOpcode() != ISD::SELECT && 13085 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13086 return SDValue(); 13087 13088 SmallVector<SDValue, 4> Inputs; 13089 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13090 SmallPtrSet<SDNode *, 16> Visited; 13091 13092 // Visit all inputs, collect all binary operations (and, or, xor and 13093 // select) that are all fed by truncations. 13094 while (!BinOps.empty()) { 13095 SDValue BinOp = BinOps.back(); 13096 BinOps.pop_back(); 13097 13098 if (!Visited.insert(BinOp.getNode()).second) 13099 continue; 13100 13101 PromOps.push_back(BinOp); 13102 13103 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13104 // The condition of the select is not promoted. 13105 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13106 continue; 13107 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13108 continue; 13109 13110 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13111 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13112 Inputs.push_back(BinOp.getOperand(i)); 13113 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13114 BinOp.getOperand(i).getOpcode() == ISD::OR || 13115 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13116 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13117 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13118 BinOps.push_back(BinOp.getOperand(i)); 13119 } else { 13120 // We have an input that is not a truncation or another binary 13121 // operation; we'll abort this transformation. 13122 return SDValue(); 13123 } 13124 } 13125 } 13126 13127 // The operands of a select that must be truncated when the select is 13128 // promoted because the operand is actually part of the to-be-promoted set. 13129 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13130 13131 // Make sure that this is a self-contained cluster of operations (which 13132 // is not quite the same thing as saying that everything has only one 13133 // use). 13134 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13135 if (isa<ConstantSDNode>(Inputs[i])) 13136 continue; 13137 13138 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13139 UE = Inputs[i].getNode()->use_end(); 13140 UI != UE; ++UI) { 13141 SDNode *User = *UI; 13142 if (User != N && !Visited.count(User)) 13143 return SDValue(); 13144 13145 // If we're going to promote the non-output-value operand(s) or SELECT or 13146 // SELECT_CC, record them for truncation. 13147 if (User->getOpcode() == ISD::SELECT) { 13148 if (User->getOperand(0) == Inputs[i]) 13149 SelectTruncOp[0].insert(std::make_pair(User, 13150 User->getOperand(0).getValueType())); 13151 } else if (User->getOpcode() == ISD::SELECT_CC) { 13152 if (User->getOperand(0) == Inputs[i]) 13153 SelectTruncOp[0].insert(std::make_pair(User, 13154 User->getOperand(0).getValueType())); 13155 if (User->getOperand(1) == Inputs[i]) 13156 SelectTruncOp[1].insert(std::make_pair(User, 13157 User->getOperand(1).getValueType())); 13158 } 13159 } 13160 } 13161 13162 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13163 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13164 UE = PromOps[i].getNode()->use_end(); 13165 UI != UE; ++UI) { 13166 SDNode *User = *UI; 13167 if (User != N && !Visited.count(User)) 13168 return SDValue(); 13169 13170 // If we're going to promote the non-output-value operand(s) or SELECT or 13171 // SELECT_CC, record them for truncation. 13172 if (User->getOpcode() == ISD::SELECT) { 13173 if (User->getOperand(0) == PromOps[i]) 13174 SelectTruncOp[0].insert(std::make_pair(User, 13175 User->getOperand(0).getValueType())); 13176 } else if (User->getOpcode() == ISD::SELECT_CC) { 13177 if (User->getOperand(0) == PromOps[i]) 13178 SelectTruncOp[0].insert(std::make_pair(User, 13179 User->getOperand(0).getValueType())); 13180 if (User->getOperand(1) == PromOps[i]) 13181 SelectTruncOp[1].insert(std::make_pair(User, 13182 User->getOperand(1).getValueType())); 13183 } 13184 } 13185 } 13186 13187 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13188 bool ReallyNeedsExt = false; 13189 if (N->getOpcode() != ISD::ANY_EXTEND) { 13190 // If all of the inputs are not already sign/zero extended, then 13191 // we'll still need to do that at the end. 13192 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13193 if (isa<ConstantSDNode>(Inputs[i])) 13194 continue; 13195 13196 unsigned OpBits = 13197 Inputs[i].getOperand(0).getValueSizeInBits(); 13198 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13199 13200 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13201 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13202 APInt::getHighBitsSet(OpBits, 13203 OpBits-PromBits))) || 13204 (N->getOpcode() == ISD::SIGN_EXTEND && 13205 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13206 (OpBits-(PromBits-1)))) { 13207 ReallyNeedsExt = true; 13208 break; 13209 } 13210 } 13211 } 13212 13213 // Replace all inputs, either with the truncation operand, or a 13214 // truncation or extension to the final output type. 13215 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13216 // Constant inputs need to be replaced with the to-be-promoted nodes that 13217 // use them because they might have users outside of the cluster of 13218 // promoted nodes. 13219 if (isa<ConstantSDNode>(Inputs[i])) 13220 continue; 13221 13222 SDValue InSrc = Inputs[i].getOperand(0); 13223 if (Inputs[i].getValueType() == N->getValueType(0)) 13224 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13225 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13226 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13227 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13228 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13229 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13230 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13231 else 13232 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13233 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13234 } 13235 13236 std::list<HandleSDNode> PromOpHandles; 13237 for (auto &PromOp : PromOps) 13238 PromOpHandles.emplace_back(PromOp); 13239 13240 // Replace all operations (these are all the same, but have a different 13241 // (promoted) return type). DAG.getNode will validate that the types of 13242 // a binary operator match, so go through the list in reverse so that 13243 // we've likely promoted both operands first. 13244 while (!PromOpHandles.empty()) { 13245 SDValue PromOp = PromOpHandles.back().getValue(); 13246 PromOpHandles.pop_back(); 13247 13248 unsigned C; 13249 switch (PromOp.getOpcode()) { 13250 default: C = 0; break; 13251 case ISD::SELECT: C = 1; break; 13252 case ISD::SELECT_CC: C = 2; break; 13253 } 13254 13255 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13256 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13257 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13258 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13259 // The to-be-promoted operands of this node have not yet been 13260 // promoted (this should be rare because we're going through the 13261 // list backward, but if one of the operands has several users in 13262 // this cluster of to-be-promoted nodes, it is possible). 13263 PromOpHandles.emplace_front(PromOp); 13264 continue; 13265 } 13266 13267 // For SELECT and SELECT_CC nodes, we do a similar check for any 13268 // to-be-promoted comparison inputs. 13269 if (PromOp.getOpcode() == ISD::SELECT || 13270 PromOp.getOpcode() == ISD::SELECT_CC) { 13271 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13272 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13273 (SelectTruncOp[1].count(PromOp.getNode()) && 13274 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13275 PromOpHandles.emplace_front(PromOp); 13276 continue; 13277 } 13278 } 13279 13280 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13281 PromOp.getNode()->op_end()); 13282 13283 // If this node has constant inputs, then they'll need to be promoted here. 13284 for (unsigned i = 0; i < 2; ++i) { 13285 if (!isa<ConstantSDNode>(Ops[C+i])) 13286 continue; 13287 if (Ops[C+i].getValueType() == N->getValueType(0)) 13288 continue; 13289 13290 if (N->getOpcode() == ISD::SIGN_EXTEND) 13291 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13292 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13293 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13294 else 13295 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13296 } 13297 13298 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13299 // truncate them again to the original value type. 13300 if (PromOp.getOpcode() == ISD::SELECT || 13301 PromOp.getOpcode() == ISD::SELECT_CC) { 13302 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13303 if (SI0 != SelectTruncOp[0].end()) 13304 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13305 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13306 if (SI1 != SelectTruncOp[1].end()) 13307 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13308 } 13309 13310 DAG.ReplaceAllUsesOfValueWith(PromOp, 13311 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13312 } 13313 13314 // Now we're left with the initial extension itself. 13315 if (!ReallyNeedsExt) 13316 return N->getOperand(0); 13317 13318 // To zero extend, just mask off everything except for the first bit (in the 13319 // i1 case). 13320 if (N->getOpcode() == ISD::ZERO_EXTEND) 13321 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13322 DAG.getConstant(APInt::getLowBitsSet( 13323 N->getValueSizeInBits(0), PromBits), 13324 dl, N->getValueType(0))); 13325 13326 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13327 "Invalid extension type"); 13328 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13329 SDValue ShiftCst = 13330 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13331 return DAG.getNode( 13332 ISD::SRA, dl, N->getValueType(0), 13333 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13334 ShiftCst); 13335 } 13336 13337 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13338 DAGCombinerInfo &DCI) const { 13339 assert(N->getOpcode() == ISD::SETCC && 13340 "Should be called with a SETCC node"); 13341 13342 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13343 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13344 SDValue LHS = N->getOperand(0); 13345 SDValue RHS = N->getOperand(1); 13346 13347 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13348 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13349 LHS.hasOneUse()) 13350 std::swap(LHS, RHS); 13351 13352 // x == 0-y --> x+y == 0 13353 // x != 0-y --> x+y != 0 13354 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13355 RHS.hasOneUse()) { 13356 SDLoc DL(N); 13357 SelectionDAG &DAG = DCI.DAG; 13358 EVT VT = N->getValueType(0); 13359 EVT OpVT = LHS.getValueType(); 13360 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13361 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13362 } 13363 } 13364 13365 return DAGCombineTruncBoolExt(N, DCI); 13366 } 13367 13368 // Is this an extending load from an f32 to an f64? 13369 static bool isFPExtLoad(SDValue Op) { 13370 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13371 return LD->getExtensionType() == ISD::EXTLOAD && 13372 Op.getValueType() == MVT::f64; 13373 return false; 13374 } 13375 13376 /// Reduces the number of fp-to-int conversion when building a vector. 13377 /// 13378 /// If this vector is built out of floating to integer conversions, 13379 /// transform it to a vector built out of floating point values followed by a 13380 /// single floating to integer conversion of the vector. 13381 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13382 /// becomes (fptosi (build_vector ($A, $B, ...))) 13383 SDValue PPCTargetLowering:: 13384 combineElementTruncationToVectorTruncation(SDNode *N, 13385 DAGCombinerInfo &DCI) const { 13386 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13387 "Should be called with a BUILD_VECTOR node"); 13388 13389 SelectionDAG &DAG = DCI.DAG; 13390 SDLoc dl(N); 13391 13392 SDValue FirstInput = N->getOperand(0); 13393 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13394 "The input operand must be an fp-to-int conversion."); 13395 13396 // This combine happens after legalization so the fp_to_[su]i nodes are 13397 // already converted to PPCSISD nodes. 13398 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13399 if (FirstConversion == PPCISD::FCTIDZ || 13400 FirstConversion == PPCISD::FCTIDUZ || 13401 FirstConversion == PPCISD::FCTIWZ || 13402 FirstConversion == PPCISD::FCTIWUZ) { 13403 bool IsSplat = true; 13404 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13405 FirstConversion == PPCISD::FCTIWUZ; 13406 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13407 SmallVector<SDValue, 4> Ops; 13408 EVT TargetVT = N->getValueType(0); 13409 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13410 SDValue NextOp = N->getOperand(i); 13411 if (NextOp.getOpcode() != PPCISD::MFVSR) 13412 return SDValue(); 13413 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13414 if (NextConversion != FirstConversion) 13415 return SDValue(); 13416 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13417 // This is not valid if the input was originally double precision. It is 13418 // also not profitable to do unless this is an extending load in which 13419 // case doing this combine will allow us to combine consecutive loads. 13420 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13421 return SDValue(); 13422 if (N->getOperand(i) != FirstInput) 13423 IsSplat = false; 13424 } 13425 13426 // If this is a splat, we leave it as-is since there will be only a single 13427 // fp-to-int conversion followed by a splat of the integer. This is better 13428 // for 32-bit and smaller ints and neutral for 64-bit ints. 13429 if (IsSplat) 13430 return SDValue(); 13431 13432 // Now that we know we have the right type of node, get its operands 13433 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13434 SDValue In = N->getOperand(i).getOperand(0); 13435 if (Is32Bit) { 13436 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13437 // here, we know that all inputs are extending loads so this is safe). 13438 if (In.isUndef()) 13439 Ops.push_back(DAG.getUNDEF(SrcVT)); 13440 else { 13441 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13442 MVT::f32, In.getOperand(0), 13443 DAG.getIntPtrConstant(1, dl)); 13444 Ops.push_back(Trunc); 13445 } 13446 } else 13447 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13448 } 13449 13450 unsigned Opcode; 13451 if (FirstConversion == PPCISD::FCTIDZ || 13452 FirstConversion == PPCISD::FCTIWZ) 13453 Opcode = ISD::FP_TO_SINT; 13454 else 13455 Opcode = ISD::FP_TO_UINT; 13456 13457 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13458 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13459 return DAG.getNode(Opcode, dl, TargetVT, BV); 13460 } 13461 return SDValue(); 13462 } 13463 13464 /// Reduce the number of loads when building a vector. 13465 /// 13466 /// Building a vector out of multiple loads can be converted to a load 13467 /// of the vector type if the loads are consecutive. If the loads are 13468 /// consecutive but in descending order, a shuffle is added at the end 13469 /// to reorder the vector. 13470 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13471 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13472 "Should be called with a BUILD_VECTOR node"); 13473 13474 SDLoc dl(N); 13475 13476 // Return early for non byte-sized type, as they can't be consecutive. 13477 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13478 return SDValue(); 13479 13480 bool InputsAreConsecutiveLoads = true; 13481 bool InputsAreReverseConsecutive = true; 13482 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13483 SDValue FirstInput = N->getOperand(0); 13484 bool IsRoundOfExtLoad = false; 13485 13486 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13487 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13488 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13489 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13490 } 13491 // Not a build vector of (possibly fp_rounded) loads. 13492 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13493 N->getNumOperands() == 1) 13494 return SDValue(); 13495 13496 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13497 // If any inputs are fp_round(extload), they all must be. 13498 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13499 return SDValue(); 13500 13501 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13502 N->getOperand(i); 13503 if (NextInput.getOpcode() != ISD::LOAD) 13504 return SDValue(); 13505 13506 SDValue PreviousInput = 13507 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13508 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13509 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13510 13511 // If any inputs are fp_round(extload), they all must be. 13512 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13513 return SDValue(); 13514 13515 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13516 InputsAreConsecutiveLoads = false; 13517 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13518 InputsAreReverseConsecutive = false; 13519 13520 // Exit early if the loads are neither consecutive nor reverse consecutive. 13521 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13522 return SDValue(); 13523 } 13524 13525 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13526 "The loads cannot be both consecutive and reverse consecutive."); 13527 13528 SDValue FirstLoadOp = 13529 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13530 SDValue LastLoadOp = 13531 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13532 N->getOperand(N->getNumOperands()-1); 13533 13534 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13535 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13536 if (InputsAreConsecutiveLoads) { 13537 assert(LD1 && "Input needs to be a LoadSDNode."); 13538 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13539 LD1->getBasePtr(), LD1->getPointerInfo(), 13540 LD1->getAlignment()); 13541 } 13542 if (InputsAreReverseConsecutive) { 13543 assert(LDL && "Input needs to be a LoadSDNode."); 13544 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13545 LDL->getBasePtr(), LDL->getPointerInfo(), 13546 LDL->getAlignment()); 13547 SmallVector<int, 16> Ops; 13548 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13549 Ops.push_back(i); 13550 13551 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13552 DAG.getUNDEF(N->getValueType(0)), Ops); 13553 } 13554 return SDValue(); 13555 } 13556 13557 // This function adds the required vector_shuffle needed to get 13558 // the elements of the vector extract in the correct position 13559 // as specified by the CorrectElems encoding. 13560 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13561 SDValue Input, uint64_t Elems, 13562 uint64_t CorrectElems) { 13563 SDLoc dl(N); 13564 13565 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13566 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13567 13568 // Knowing the element indices being extracted from the original 13569 // vector and the order in which they're being inserted, just put 13570 // them at element indices required for the instruction. 13571 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13572 if (DAG.getDataLayout().isLittleEndian()) 13573 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13574 else 13575 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13576 CorrectElems = CorrectElems >> 8; 13577 Elems = Elems >> 8; 13578 } 13579 13580 SDValue Shuffle = 13581 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13582 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13583 13584 EVT VT = N->getValueType(0); 13585 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13586 13587 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13588 Input.getValueType().getVectorElementType(), 13589 VT.getVectorNumElements()); 13590 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13591 DAG.getValueType(ExtVT)); 13592 } 13593 13594 // Look for build vector patterns where input operands come from sign 13595 // extended vector_extract elements of specific indices. If the correct indices 13596 // aren't used, add a vector shuffle to fix up the indices and create 13597 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13598 // during instruction selection. 13599 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13600 // This array encodes the indices that the vector sign extend instructions 13601 // extract from when extending from one type to another for both BE and LE. 13602 // The right nibble of each byte corresponds to the LE incides. 13603 // and the left nibble of each byte corresponds to the BE incides. 13604 // For example: 0x3074B8FC byte->word 13605 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13606 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13607 // For example: 0x000070F8 byte->double word 13608 // For LE: the allowed indices are: 0x0,0x8 13609 // For BE: the allowed indices are: 0x7,0xF 13610 uint64_t TargetElems[] = { 13611 0x3074B8FC, // b->w 13612 0x000070F8, // b->d 13613 0x10325476, // h->w 13614 0x00003074, // h->d 13615 0x00001032, // w->d 13616 }; 13617 13618 uint64_t Elems = 0; 13619 int Index; 13620 SDValue Input; 13621 13622 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13623 if (!Op) 13624 return false; 13625 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13626 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13627 return false; 13628 13629 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13630 // of the right width. 13631 SDValue Extract = Op.getOperand(0); 13632 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13633 Extract = Extract.getOperand(0); 13634 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13635 return false; 13636 13637 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13638 if (!ExtOp) 13639 return false; 13640 13641 Index = ExtOp->getZExtValue(); 13642 if (Input && Input != Extract.getOperand(0)) 13643 return false; 13644 13645 if (!Input) 13646 Input = Extract.getOperand(0); 13647 13648 Elems = Elems << 8; 13649 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13650 Elems |= Index; 13651 13652 return true; 13653 }; 13654 13655 // If the build vector operands aren't sign extended vector extracts, 13656 // of the same input vector, then return. 13657 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13658 if (!isSExtOfVecExtract(N->getOperand(i))) { 13659 return SDValue(); 13660 } 13661 } 13662 13663 // If the vector extract indicies are not correct, add the appropriate 13664 // vector_shuffle. 13665 int TgtElemArrayIdx; 13666 int InputSize = Input.getValueType().getScalarSizeInBits(); 13667 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13668 if (InputSize + OutputSize == 40) 13669 TgtElemArrayIdx = 0; 13670 else if (InputSize + OutputSize == 72) 13671 TgtElemArrayIdx = 1; 13672 else if (InputSize + OutputSize == 48) 13673 TgtElemArrayIdx = 2; 13674 else if (InputSize + OutputSize == 80) 13675 TgtElemArrayIdx = 3; 13676 else if (InputSize + OutputSize == 96) 13677 TgtElemArrayIdx = 4; 13678 else 13679 return SDValue(); 13680 13681 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13682 CorrectElems = DAG.getDataLayout().isLittleEndian() 13683 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13684 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13685 if (Elems != CorrectElems) { 13686 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13687 } 13688 13689 // Regular lowering will catch cases where a shuffle is not needed. 13690 return SDValue(); 13691 } 13692 13693 // Look for the pattern of a load from a narrow width to i128, feeding 13694 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 13695 // (LXVRZX). This node represents a zero extending load that will be matched 13696 // to the Load VSX Vector Rightmost instructions. 13697 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 13698 SDLoc DL(N); 13699 13700 // This combine is only eligible for a BUILD_VECTOR of v1i128. 13701 if (N->getValueType(0) != MVT::v1i128) 13702 return SDValue(); 13703 13704 SDValue Operand = N->getOperand(0); 13705 // Proceed with the transformation if the operand to the BUILD_VECTOR 13706 // is a load instruction. 13707 if (Operand.getOpcode() != ISD::LOAD) 13708 return SDValue(); 13709 13710 LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand); 13711 EVT MemoryType = LD->getMemoryVT(); 13712 13713 // This transformation is only valid if the we are loading either a byte, 13714 // halfword, word, or doubleword. 13715 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 13716 MemoryType == MVT::i32 || MemoryType == MVT::i64; 13717 13718 // Ensure that the load from the narrow width is being zero extended to i128. 13719 if (!ValidLDType || 13720 (LD->getExtensionType() != ISD::ZEXTLOAD && 13721 LD->getExtensionType() != ISD::EXTLOAD)) 13722 return SDValue(); 13723 13724 SDValue LoadOps[] = { 13725 LD->getChain(), LD->getBasePtr(), 13726 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 13727 13728 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 13729 DAG.getVTList(MVT::v1i128, MVT::Other), 13730 LoadOps, MemoryType, LD->getMemOperand()); 13731 } 13732 13733 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13734 DAGCombinerInfo &DCI) const { 13735 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13736 "Should be called with a BUILD_VECTOR node"); 13737 13738 SelectionDAG &DAG = DCI.DAG; 13739 SDLoc dl(N); 13740 13741 if (!Subtarget.hasVSX()) 13742 return SDValue(); 13743 13744 // The target independent DAG combiner will leave a build_vector of 13745 // float-to-int conversions intact. We can generate MUCH better code for 13746 // a float-to-int conversion of a vector of floats. 13747 SDValue FirstInput = N->getOperand(0); 13748 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13749 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13750 if (Reduced) 13751 return Reduced; 13752 } 13753 13754 // If we're building a vector out of consecutive loads, just load that 13755 // vector type. 13756 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13757 if (Reduced) 13758 return Reduced; 13759 13760 // If we're building a vector out of extended elements from another vector 13761 // we have P9 vector integer extend instructions. The code assumes legal 13762 // input types (i.e. it can't handle things like v4i16) so do not run before 13763 // legalization. 13764 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13765 Reduced = combineBVOfVecSExt(N, DAG); 13766 if (Reduced) 13767 return Reduced; 13768 } 13769 13770 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 13771 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 13772 // is a load from <valid narrow width> to i128. 13773 if (Subtarget.isISA3_1()) { 13774 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 13775 if (BVOfZLoad) 13776 return BVOfZLoad; 13777 } 13778 13779 if (N->getValueType(0) != MVT::v2f64) 13780 return SDValue(); 13781 13782 // Looking for: 13783 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13784 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13785 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13786 return SDValue(); 13787 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13788 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13789 return SDValue(); 13790 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13791 return SDValue(); 13792 13793 SDValue Ext1 = FirstInput.getOperand(0); 13794 SDValue Ext2 = N->getOperand(1).getOperand(0); 13795 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13796 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13797 return SDValue(); 13798 13799 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13800 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13801 if (!Ext1Op || !Ext2Op) 13802 return SDValue(); 13803 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13804 Ext1.getOperand(0) != Ext2.getOperand(0)) 13805 return SDValue(); 13806 13807 int FirstElem = Ext1Op->getZExtValue(); 13808 int SecondElem = Ext2Op->getZExtValue(); 13809 int SubvecIdx; 13810 if (FirstElem == 0 && SecondElem == 1) 13811 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13812 else if (FirstElem == 2 && SecondElem == 3) 13813 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13814 else 13815 return SDValue(); 13816 13817 SDValue SrcVec = Ext1.getOperand(0); 13818 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13819 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13820 return DAG.getNode(NodeType, dl, MVT::v2f64, 13821 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13822 } 13823 13824 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13825 DAGCombinerInfo &DCI) const { 13826 assert((N->getOpcode() == ISD::SINT_TO_FP || 13827 N->getOpcode() == ISD::UINT_TO_FP) && 13828 "Need an int -> FP conversion node here"); 13829 13830 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13831 return SDValue(); 13832 13833 SelectionDAG &DAG = DCI.DAG; 13834 SDLoc dl(N); 13835 SDValue Op(N, 0); 13836 13837 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13838 // from the hardware. 13839 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13840 return SDValue(); 13841 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13842 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13843 return SDValue(); 13844 13845 SDValue FirstOperand(Op.getOperand(0)); 13846 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13847 (FirstOperand.getValueType() == MVT::i8 || 13848 FirstOperand.getValueType() == MVT::i16); 13849 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13850 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13851 bool DstDouble = Op.getValueType() == MVT::f64; 13852 unsigned ConvOp = Signed ? 13853 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13854 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13855 SDValue WidthConst = 13856 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13857 dl, false); 13858 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13859 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13860 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13861 DAG.getVTList(MVT::f64, MVT::Other), 13862 Ops, MVT::i8, LDN->getMemOperand()); 13863 13864 // For signed conversion, we need to sign-extend the value in the VSR 13865 if (Signed) { 13866 SDValue ExtOps[] = { Ld, WidthConst }; 13867 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13868 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13869 } else 13870 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13871 } 13872 13873 13874 // For i32 intermediate values, unfortunately, the conversion functions 13875 // leave the upper 32 bits of the value are undefined. Within the set of 13876 // scalar instructions, we have no method for zero- or sign-extending the 13877 // value. Thus, we cannot handle i32 intermediate values here. 13878 if (Op.getOperand(0).getValueType() == MVT::i32) 13879 return SDValue(); 13880 13881 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13882 "UINT_TO_FP is supported only with FPCVT"); 13883 13884 // If we have FCFIDS, then use it when converting to single-precision. 13885 // Otherwise, convert to double-precision and then round. 13886 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13887 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13888 : PPCISD::FCFIDS) 13889 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13890 : PPCISD::FCFID); 13891 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13892 ? MVT::f32 13893 : MVT::f64; 13894 13895 // If we're converting from a float, to an int, and back to a float again, 13896 // then we don't need the store/load pair at all. 13897 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13898 Subtarget.hasFPCVT()) || 13899 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13900 SDValue Src = Op.getOperand(0).getOperand(0); 13901 if (Src.getValueType() == MVT::f32) { 13902 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13903 DCI.AddToWorklist(Src.getNode()); 13904 } else if (Src.getValueType() != MVT::f64) { 13905 // Make sure that we don't pick up a ppc_fp128 source value. 13906 return SDValue(); 13907 } 13908 13909 unsigned FCTOp = 13910 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13911 PPCISD::FCTIDUZ; 13912 13913 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13914 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13915 13916 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13917 FP = DAG.getNode(ISD::FP_ROUND, dl, 13918 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13919 DCI.AddToWorklist(FP.getNode()); 13920 } 13921 13922 return FP; 13923 } 13924 13925 return SDValue(); 13926 } 13927 13928 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13929 // builtins) into loads with swaps. 13930 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13931 DAGCombinerInfo &DCI) const { 13932 SelectionDAG &DAG = DCI.DAG; 13933 SDLoc dl(N); 13934 SDValue Chain; 13935 SDValue Base; 13936 MachineMemOperand *MMO; 13937 13938 switch (N->getOpcode()) { 13939 default: 13940 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13941 case ISD::LOAD: { 13942 LoadSDNode *LD = cast<LoadSDNode>(N); 13943 Chain = LD->getChain(); 13944 Base = LD->getBasePtr(); 13945 MMO = LD->getMemOperand(); 13946 // If the MMO suggests this isn't a load of a full vector, leave 13947 // things alone. For a built-in, we have to make the change for 13948 // correctness, so if there is a size problem that will be a bug. 13949 if (MMO->getSize() < 16) 13950 return SDValue(); 13951 break; 13952 } 13953 case ISD::INTRINSIC_W_CHAIN: { 13954 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13955 Chain = Intrin->getChain(); 13956 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13957 // us what we want. Get operand 2 instead. 13958 Base = Intrin->getOperand(2); 13959 MMO = Intrin->getMemOperand(); 13960 break; 13961 } 13962 } 13963 13964 MVT VecTy = N->getValueType(0).getSimpleVT(); 13965 13966 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13967 // aligned and the type is a vector with elements up to 4 bytes 13968 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13969 VecTy.getScalarSizeInBits() <= 32) { 13970 return SDValue(); 13971 } 13972 13973 SDValue LoadOps[] = { Chain, Base }; 13974 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13975 DAG.getVTList(MVT::v2f64, MVT::Other), 13976 LoadOps, MVT::v2f64, MMO); 13977 13978 DCI.AddToWorklist(Load.getNode()); 13979 Chain = Load.getValue(1); 13980 SDValue Swap = DAG.getNode( 13981 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13982 DCI.AddToWorklist(Swap.getNode()); 13983 13984 // Add a bitcast if the resulting load type doesn't match v2f64. 13985 if (VecTy != MVT::v2f64) { 13986 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13987 DCI.AddToWorklist(N.getNode()); 13988 // Package {bitcast value, swap's chain} to match Load's shape. 13989 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13990 N, Swap.getValue(1)); 13991 } 13992 13993 return Swap; 13994 } 13995 13996 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13997 // builtins) into stores with swaps. 13998 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13999 DAGCombinerInfo &DCI) const { 14000 SelectionDAG &DAG = DCI.DAG; 14001 SDLoc dl(N); 14002 SDValue Chain; 14003 SDValue Base; 14004 unsigned SrcOpnd; 14005 MachineMemOperand *MMO; 14006 14007 switch (N->getOpcode()) { 14008 default: 14009 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14010 case ISD::STORE: { 14011 StoreSDNode *ST = cast<StoreSDNode>(N); 14012 Chain = ST->getChain(); 14013 Base = ST->getBasePtr(); 14014 MMO = ST->getMemOperand(); 14015 SrcOpnd = 1; 14016 // If the MMO suggests this isn't a store of a full vector, leave 14017 // things alone. For a built-in, we have to make the change for 14018 // correctness, so if there is a size problem that will be a bug. 14019 if (MMO->getSize() < 16) 14020 return SDValue(); 14021 break; 14022 } 14023 case ISD::INTRINSIC_VOID: { 14024 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14025 Chain = Intrin->getChain(); 14026 // Intrin->getBasePtr() oddly does not get what we want. 14027 Base = Intrin->getOperand(3); 14028 MMO = Intrin->getMemOperand(); 14029 SrcOpnd = 2; 14030 break; 14031 } 14032 } 14033 14034 SDValue Src = N->getOperand(SrcOpnd); 14035 MVT VecTy = Src.getValueType().getSimpleVT(); 14036 14037 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14038 // aligned and the type is a vector with elements up to 4 bytes 14039 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14040 VecTy.getScalarSizeInBits() <= 32) { 14041 return SDValue(); 14042 } 14043 14044 // All stores are done as v2f64 and possible bit cast. 14045 if (VecTy != MVT::v2f64) { 14046 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14047 DCI.AddToWorklist(Src.getNode()); 14048 } 14049 14050 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14051 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14052 DCI.AddToWorklist(Swap.getNode()); 14053 Chain = Swap.getValue(1); 14054 SDValue StoreOps[] = { Chain, Swap, Base }; 14055 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14056 DAG.getVTList(MVT::Other), 14057 StoreOps, VecTy, MMO); 14058 DCI.AddToWorklist(Store.getNode()); 14059 return Store; 14060 } 14061 14062 // Handle DAG combine for STORE (FP_TO_INT F). 14063 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14064 DAGCombinerInfo &DCI) const { 14065 14066 SelectionDAG &DAG = DCI.DAG; 14067 SDLoc dl(N); 14068 unsigned Opcode = N->getOperand(1).getOpcode(); 14069 14070 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14071 && "Not a FP_TO_INT Instruction!"); 14072 14073 SDValue Val = N->getOperand(1).getOperand(0); 14074 EVT Op1VT = N->getOperand(1).getValueType(); 14075 EVT ResVT = Val.getValueType(); 14076 14077 // Floating point types smaller than 32 bits are not legal on Power. 14078 if (ResVT.getScalarSizeInBits() < 32) 14079 return SDValue(); 14080 14081 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14082 bool ValidTypeForStoreFltAsInt = 14083 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14084 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14085 14086 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14087 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14088 return SDValue(); 14089 14090 // Extend f32 values to f64 14091 if (ResVT.getScalarSizeInBits() == 32) { 14092 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14093 DCI.AddToWorklist(Val.getNode()); 14094 } 14095 14096 // Set signed or unsigned conversion opcode. 14097 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14098 PPCISD::FP_TO_SINT_IN_VSR : 14099 PPCISD::FP_TO_UINT_IN_VSR; 14100 14101 Val = DAG.getNode(ConvOpcode, 14102 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14103 DCI.AddToWorklist(Val.getNode()); 14104 14105 // Set number of bytes being converted. 14106 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14107 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14108 DAG.getIntPtrConstant(ByteSize, dl, false), 14109 DAG.getValueType(Op1VT) }; 14110 14111 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14112 DAG.getVTList(MVT::Other), Ops, 14113 cast<StoreSDNode>(N)->getMemoryVT(), 14114 cast<StoreSDNode>(N)->getMemOperand()); 14115 14116 DCI.AddToWorklist(Val.getNode()); 14117 return Val; 14118 } 14119 14120 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14121 // Check that the source of the element keeps flipping 14122 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14123 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14124 for (int i = 1, e = Mask.size(); i < e; i++) { 14125 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14126 return false; 14127 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14128 return false; 14129 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14130 } 14131 return true; 14132 } 14133 14134 static bool isSplatBV(SDValue Op) { 14135 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14136 return false; 14137 SDValue FirstOp; 14138 14139 // Find first non-undef input. 14140 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14141 FirstOp = Op.getOperand(i); 14142 if (!FirstOp.isUndef()) 14143 break; 14144 } 14145 14146 // All inputs are undef or the same as the first non-undef input. 14147 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14148 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14149 return false; 14150 return true; 14151 } 14152 14153 static SDValue isScalarToVec(SDValue Op) { 14154 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14155 return Op; 14156 if (Op.getOpcode() != ISD::BITCAST) 14157 return SDValue(); 14158 Op = Op.getOperand(0); 14159 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14160 return Op; 14161 return SDValue(); 14162 } 14163 14164 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14165 int LHSMaxIdx, int RHSMinIdx, 14166 int RHSMaxIdx, int HalfVec) { 14167 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14168 int Idx = ShuffV[i]; 14169 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14170 ShuffV[i] += HalfVec; 14171 } 14172 return; 14173 } 14174 14175 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14176 // the original is: 14177 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14178 // In such a case, just change the shuffle mask to extract the element 14179 // from the permuted index. 14180 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14181 SDLoc dl(OrigSToV); 14182 EVT VT = OrigSToV.getValueType(); 14183 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14184 "Expecting a SCALAR_TO_VECTOR here"); 14185 SDValue Input = OrigSToV.getOperand(0); 14186 14187 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14188 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14189 SDValue OrigVector = Input.getOperand(0); 14190 14191 // Can't handle non-const element indices or different vector types 14192 // for the input to the extract and the output of the scalar_to_vector. 14193 if (Idx && VT == OrigVector.getValueType()) { 14194 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14195 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14196 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14197 } 14198 } 14199 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14200 OrigSToV.getOperand(0)); 14201 } 14202 14203 // On little endian subtargets, combine shuffles such as: 14204 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14205 // into: 14206 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14207 // because the latter can be matched to a single instruction merge. 14208 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14209 // to put the value into element zero. Adjust the shuffle mask so that the 14210 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14211 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14212 SelectionDAG &DAG) const { 14213 SDValue LHS = SVN->getOperand(0); 14214 SDValue RHS = SVN->getOperand(1); 14215 auto Mask = SVN->getMask(); 14216 int NumElts = LHS.getValueType().getVectorNumElements(); 14217 SDValue Res(SVN, 0); 14218 SDLoc dl(SVN); 14219 14220 // None of these combines are useful on big endian systems since the ISA 14221 // already has a big endian bias. 14222 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14223 return Res; 14224 14225 // If this is not a shuffle of a shuffle and the first element comes from 14226 // the second vector, canonicalize to the commuted form. This will make it 14227 // more likely to match one of the single instruction patterns. 14228 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14229 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14230 std::swap(LHS, RHS); 14231 Res = DAG.getCommutedVectorShuffle(*SVN); 14232 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14233 } 14234 14235 // Adjust the shuffle mask if either input vector comes from a 14236 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14237 // form (to prevent the need for a swap). 14238 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14239 SDValue SToVLHS = isScalarToVec(LHS); 14240 SDValue SToVRHS = isScalarToVec(RHS); 14241 if (SToVLHS || SToVRHS) { 14242 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14243 : SToVRHS.getValueType().getVectorNumElements(); 14244 int NumEltsOut = ShuffV.size(); 14245 14246 // Initially assume that neither input is permuted. These will be adjusted 14247 // accordingly if either input is. 14248 int LHSMaxIdx = -1; 14249 int RHSMinIdx = -1; 14250 int RHSMaxIdx = -1; 14251 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14252 14253 // Get the permuted scalar to vector nodes for the source(s) that come from 14254 // ISD::SCALAR_TO_VECTOR. 14255 if (SToVLHS) { 14256 // Set up the values for the shuffle vector fixup. 14257 LHSMaxIdx = NumEltsOut / NumEltsIn; 14258 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14259 if (SToVLHS.getValueType() != LHS.getValueType()) 14260 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14261 LHS = SToVLHS; 14262 } 14263 if (SToVRHS) { 14264 RHSMinIdx = NumEltsOut; 14265 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14266 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14267 if (SToVRHS.getValueType() != RHS.getValueType()) 14268 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14269 RHS = SToVRHS; 14270 } 14271 14272 // Fix up the shuffle mask to reflect where the desired element actually is. 14273 // The minimum and maximum indices that correspond to element zero for both 14274 // the LHS and RHS are computed and will control which shuffle mask entries 14275 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14276 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14277 // HalfVec to refer to the corresponding element in the permuted vector. 14278 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14279 HalfVec); 14280 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14281 14282 // We may have simplified away the shuffle. We won't be able to do anything 14283 // further with it here. 14284 if (!isa<ShuffleVectorSDNode>(Res)) 14285 return Res; 14286 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14287 } 14288 14289 // The common case after we commuted the shuffle is that the RHS is a splat 14290 // and we have elements coming in from the splat at indices that are not 14291 // conducive to using a merge. 14292 // Example: 14293 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14294 if (!isSplatBV(RHS)) 14295 return Res; 14296 14297 // We are looking for a mask such that all even elements are from 14298 // one vector and all odd elements from the other. 14299 if (!isAlternatingShuffMask(Mask, NumElts)) 14300 return Res; 14301 14302 // Adjust the mask so we are pulling in the same index from the splat 14303 // as the index from the interesting vector in consecutive elements. 14304 // Example (even elements from first vector): 14305 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14306 if (Mask[0] < NumElts) 14307 for (int i = 1, e = Mask.size(); i < e; i += 2) 14308 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14309 // Example (odd elements from first vector): 14310 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14311 else 14312 for (int i = 0, e = Mask.size(); i < e; i += 2) 14313 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14314 14315 // If the RHS has undefs, we need to remove them since we may have created 14316 // a shuffle that adds those instead of the splat value. 14317 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14318 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14319 14320 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14321 return Res; 14322 } 14323 14324 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14325 LSBaseSDNode *LSBase, 14326 DAGCombinerInfo &DCI) const { 14327 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14328 "Not a reverse memop pattern!"); 14329 14330 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14331 auto Mask = SVN->getMask(); 14332 int i = 0; 14333 auto I = Mask.rbegin(); 14334 auto E = Mask.rend(); 14335 14336 for (; I != E; ++I) { 14337 if (*I != i) 14338 return false; 14339 i++; 14340 } 14341 return true; 14342 }; 14343 14344 SelectionDAG &DAG = DCI.DAG; 14345 EVT VT = SVN->getValueType(0); 14346 14347 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14348 return SDValue(); 14349 14350 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14351 // See comment in PPCVSXSwapRemoval.cpp. 14352 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14353 if (!Subtarget.hasP9Vector()) 14354 return SDValue(); 14355 14356 if(!IsElementReverse(SVN)) 14357 return SDValue(); 14358 14359 if (LSBase->getOpcode() == ISD::LOAD) { 14360 SDLoc dl(SVN); 14361 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14362 return DAG.getMemIntrinsicNode( 14363 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14364 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14365 } 14366 14367 if (LSBase->getOpcode() == ISD::STORE) { 14368 SDLoc dl(LSBase); 14369 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14370 LSBase->getBasePtr()}; 14371 return DAG.getMemIntrinsicNode( 14372 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14373 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14374 } 14375 14376 llvm_unreachable("Expected a load or store node here"); 14377 } 14378 14379 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14380 DAGCombinerInfo &DCI) const { 14381 SelectionDAG &DAG = DCI.DAG; 14382 SDLoc dl(N); 14383 switch (N->getOpcode()) { 14384 default: break; 14385 case ISD::ADD: 14386 return combineADD(N, DCI); 14387 case ISD::SHL: 14388 return combineSHL(N, DCI); 14389 case ISD::SRA: 14390 return combineSRA(N, DCI); 14391 case ISD::SRL: 14392 return combineSRL(N, DCI); 14393 case ISD::MUL: 14394 return combineMUL(N, DCI); 14395 case ISD::FMA: 14396 case PPCISD::FNMSUB: 14397 return combineFMALike(N, DCI); 14398 case PPCISD::SHL: 14399 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14400 return N->getOperand(0); 14401 break; 14402 case PPCISD::SRL: 14403 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14404 return N->getOperand(0); 14405 break; 14406 case PPCISD::SRA: 14407 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14408 if (C->isNullValue() || // 0 >>s V -> 0. 14409 C->isAllOnesValue()) // -1 >>s V -> -1. 14410 return N->getOperand(0); 14411 } 14412 break; 14413 case ISD::SIGN_EXTEND: 14414 case ISD::ZERO_EXTEND: 14415 case ISD::ANY_EXTEND: 14416 return DAGCombineExtBoolTrunc(N, DCI); 14417 case ISD::TRUNCATE: 14418 return combineTRUNCATE(N, DCI); 14419 case ISD::SETCC: 14420 if (SDValue CSCC = combineSetCC(N, DCI)) 14421 return CSCC; 14422 LLVM_FALLTHROUGH; 14423 case ISD::SELECT_CC: 14424 return DAGCombineTruncBoolExt(N, DCI); 14425 case ISD::SINT_TO_FP: 14426 case ISD::UINT_TO_FP: 14427 return combineFPToIntToFP(N, DCI); 14428 case ISD::VECTOR_SHUFFLE: 14429 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14430 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14431 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14432 } 14433 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14434 case ISD::STORE: { 14435 14436 EVT Op1VT = N->getOperand(1).getValueType(); 14437 unsigned Opcode = N->getOperand(1).getOpcode(); 14438 14439 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14440 SDValue Val= combineStoreFPToInt(N, DCI); 14441 if (Val) 14442 return Val; 14443 } 14444 14445 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14446 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14447 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14448 if (Val) 14449 return Val; 14450 } 14451 14452 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14453 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14454 N->getOperand(1).getNode()->hasOneUse() && 14455 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14456 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14457 14458 // STBRX can only handle simple types and it makes no sense to store less 14459 // two bytes in byte-reversed order. 14460 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14461 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14462 break; 14463 14464 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14465 // Do an any-extend to 32-bits if this is a half-word input. 14466 if (BSwapOp.getValueType() == MVT::i16) 14467 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14468 14469 // If the type of BSWAP operand is wider than stored memory width 14470 // it need to be shifted to the right side before STBRX. 14471 if (Op1VT.bitsGT(mVT)) { 14472 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14473 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14474 DAG.getConstant(Shift, dl, MVT::i32)); 14475 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14476 if (Op1VT == MVT::i64) 14477 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14478 } 14479 14480 SDValue Ops[] = { 14481 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14482 }; 14483 return 14484 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14485 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14486 cast<StoreSDNode>(N)->getMemOperand()); 14487 } 14488 14489 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14490 // So it can increase the chance of CSE constant construction. 14491 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14492 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14493 // Need to sign-extended to 64-bits to handle negative values. 14494 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14495 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14496 MemVT.getSizeInBits()); 14497 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14498 14499 // DAG.getTruncStore() can't be used here because it doesn't accept 14500 // the general (base + offset) addressing mode. 14501 // So we use UpdateNodeOperands and setTruncatingStore instead. 14502 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14503 N->getOperand(3)); 14504 cast<StoreSDNode>(N)->setTruncatingStore(true); 14505 return SDValue(N, 0); 14506 } 14507 14508 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14509 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14510 if (Op1VT.isSimple()) { 14511 MVT StoreVT = Op1VT.getSimpleVT(); 14512 if (Subtarget.needsSwapsForVSXMemOps() && 14513 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14514 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14515 return expandVSXStoreForLE(N, DCI); 14516 } 14517 break; 14518 } 14519 case ISD::LOAD: { 14520 LoadSDNode *LD = cast<LoadSDNode>(N); 14521 EVT VT = LD->getValueType(0); 14522 14523 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14524 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14525 if (VT.isSimple()) { 14526 MVT LoadVT = VT.getSimpleVT(); 14527 if (Subtarget.needsSwapsForVSXMemOps() && 14528 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14529 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14530 return expandVSXLoadForLE(N, DCI); 14531 } 14532 14533 // We sometimes end up with a 64-bit integer load, from which we extract 14534 // two single-precision floating-point numbers. This happens with 14535 // std::complex<float>, and other similar structures, because of the way we 14536 // canonicalize structure copies. However, if we lack direct moves, 14537 // then the final bitcasts from the extracted integer values to the 14538 // floating-point numbers turn into store/load pairs. Even with direct moves, 14539 // just loading the two floating-point numbers is likely better. 14540 auto ReplaceTwoFloatLoad = [&]() { 14541 if (VT != MVT::i64) 14542 return false; 14543 14544 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14545 LD->isVolatile()) 14546 return false; 14547 14548 // We're looking for a sequence like this: 14549 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14550 // t16: i64 = srl t13, Constant:i32<32> 14551 // t17: i32 = truncate t16 14552 // t18: f32 = bitcast t17 14553 // t19: i32 = truncate t13 14554 // t20: f32 = bitcast t19 14555 14556 if (!LD->hasNUsesOfValue(2, 0)) 14557 return false; 14558 14559 auto UI = LD->use_begin(); 14560 while (UI.getUse().getResNo() != 0) ++UI; 14561 SDNode *Trunc = *UI++; 14562 while (UI.getUse().getResNo() != 0) ++UI; 14563 SDNode *RightShift = *UI; 14564 if (Trunc->getOpcode() != ISD::TRUNCATE) 14565 std::swap(Trunc, RightShift); 14566 14567 if (Trunc->getOpcode() != ISD::TRUNCATE || 14568 Trunc->getValueType(0) != MVT::i32 || 14569 !Trunc->hasOneUse()) 14570 return false; 14571 if (RightShift->getOpcode() != ISD::SRL || 14572 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14573 RightShift->getConstantOperandVal(1) != 32 || 14574 !RightShift->hasOneUse()) 14575 return false; 14576 14577 SDNode *Trunc2 = *RightShift->use_begin(); 14578 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14579 Trunc2->getValueType(0) != MVT::i32 || 14580 !Trunc2->hasOneUse()) 14581 return false; 14582 14583 SDNode *Bitcast = *Trunc->use_begin(); 14584 SDNode *Bitcast2 = *Trunc2->use_begin(); 14585 14586 if (Bitcast->getOpcode() != ISD::BITCAST || 14587 Bitcast->getValueType(0) != MVT::f32) 14588 return false; 14589 if (Bitcast2->getOpcode() != ISD::BITCAST || 14590 Bitcast2->getValueType(0) != MVT::f32) 14591 return false; 14592 14593 if (Subtarget.isLittleEndian()) 14594 std::swap(Bitcast, Bitcast2); 14595 14596 // Bitcast has the second float (in memory-layout order) and Bitcast2 14597 // has the first one. 14598 14599 SDValue BasePtr = LD->getBasePtr(); 14600 if (LD->isIndexed()) { 14601 assert(LD->getAddressingMode() == ISD::PRE_INC && 14602 "Non-pre-inc AM on PPC?"); 14603 BasePtr = 14604 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14605 LD->getOffset()); 14606 } 14607 14608 auto MMOFlags = 14609 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14610 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14611 LD->getPointerInfo(), LD->getAlignment(), 14612 MMOFlags, LD->getAAInfo()); 14613 SDValue AddPtr = 14614 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14615 BasePtr, DAG.getIntPtrConstant(4, dl)); 14616 SDValue FloatLoad2 = DAG.getLoad( 14617 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14618 LD->getPointerInfo().getWithOffset(4), 14619 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14620 14621 if (LD->isIndexed()) { 14622 // Note that DAGCombine should re-form any pre-increment load(s) from 14623 // what is produced here if that makes sense. 14624 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14625 } 14626 14627 DCI.CombineTo(Bitcast2, FloatLoad); 14628 DCI.CombineTo(Bitcast, FloatLoad2); 14629 14630 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14631 SDValue(FloatLoad2.getNode(), 1)); 14632 return true; 14633 }; 14634 14635 if (ReplaceTwoFloatLoad()) 14636 return SDValue(N, 0); 14637 14638 EVT MemVT = LD->getMemoryVT(); 14639 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14640 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14641 if (LD->isUnindexed() && VT.isVector() && 14642 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14643 // P8 and later hardware should just use LOAD. 14644 !Subtarget.hasP8Vector() && 14645 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14646 VT == MVT::v4f32))) && 14647 LD->getAlign() < ABIAlignment) { 14648 // This is a type-legal unaligned Altivec load. 14649 SDValue Chain = LD->getChain(); 14650 SDValue Ptr = LD->getBasePtr(); 14651 bool isLittleEndian = Subtarget.isLittleEndian(); 14652 14653 // This implements the loading of unaligned vectors as described in 14654 // the venerable Apple Velocity Engine overview. Specifically: 14655 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14656 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14657 // 14658 // The general idea is to expand a sequence of one or more unaligned 14659 // loads into an alignment-based permutation-control instruction (lvsl 14660 // or lvsr), a series of regular vector loads (which always truncate 14661 // their input address to an aligned address), and a series of 14662 // permutations. The results of these permutations are the requested 14663 // loaded values. The trick is that the last "extra" load is not taken 14664 // from the address you might suspect (sizeof(vector) bytes after the 14665 // last requested load), but rather sizeof(vector) - 1 bytes after the 14666 // last requested vector. The point of this is to avoid a page fault if 14667 // the base address happened to be aligned. This works because if the 14668 // base address is aligned, then adding less than a full vector length 14669 // will cause the last vector in the sequence to be (re)loaded. 14670 // Otherwise, the next vector will be fetched as you might suspect was 14671 // necessary. 14672 14673 // We might be able to reuse the permutation generation from 14674 // a different base address offset from this one by an aligned amount. 14675 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14676 // optimization later. 14677 Intrinsic::ID Intr, IntrLD, IntrPerm; 14678 MVT PermCntlTy, PermTy, LDTy; 14679 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14680 : Intrinsic::ppc_altivec_lvsl; 14681 IntrLD = Intrinsic::ppc_altivec_lvx; 14682 IntrPerm = Intrinsic::ppc_altivec_vperm; 14683 PermCntlTy = MVT::v16i8; 14684 PermTy = MVT::v4i32; 14685 LDTy = MVT::v4i32; 14686 14687 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14688 14689 // Create the new MMO for the new base load. It is like the original MMO, 14690 // but represents an area in memory almost twice the vector size centered 14691 // on the original address. If the address is unaligned, we might start 14692 // reading up to (sizeof(vector)-1) bytes below the address of the 14693 // original unaligned load. 14694 MachineFunction &MF = DAG.getMachineFunction(); 14695 MachineMemOperand *BaseMMO = 14696 MF.getMachineMemOperand(LD->getMemOperand(), 14697 -(long)MemVT.getStoreSize()+1, 14698 2*MemVT.getStoreSize()-1); 14699 14700 // Create the new base load. 14701 SDValue LDXIntID = 14702 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14703 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14704 SDValue BaseLoad = 14705 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14706 DAG.getVTList(PermTy, MVT::Other), 14707 BaseLoadOps, LDTy, BaseMMO); 14708 14709 // Note that the value of IncOffset (which is provided to the next 14710 // load's pointer info offset value, and thus used to calculate the 14711 // alignment), and the value of IncValue (which is actually used to 14712 // increment the pointer value) are different! This is because we 14713 // require the next load to appear to be aligned, even though it 14714 // is actually offset from the base pointer by a lesser amount. 14715 int IncOffset = VT.getSizeInBits() / 8; 14716 int IncValue = IncOffset; 14717 14718 // Walk (both up and down) the chain looking for another load at the real 14719 // (aligned) offset (the alignment of the other load does not matter in 14720 // this case). If found, then do not use the offset reduction trick, as 14721 // that will prevent the loads from being later combined (as they would 14722 // otherwise be duplicates). 14723 if (!findConsecutiveLoad(LD, DAG)) 14724 --IncValue; 14725 14726 SDValue Increment = 14727 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14728 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14729 14730 MachineMemOperand *ExtraMMO = 14731 MF.getMachineMemOperand(LD->getMemOperand(), 14732 1, 2*MemVT.getStoreSize()-1); 14733 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14734 SDValue ExtraLoad = 14735 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14736 DAG.getVTList(PermTy, MVT::Other), 14737 ExtraLoadOps, LDTy, ExtraMMO); 14738 14739 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14740 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14741 14742 // Because vperm has a big-endian bias, we must reverse the order 14743 // of the input vectors and complement the permute control vector 14744 // when generating little endian code. We have already handled the 14745 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14746 // and ExtraLoad here. 14747 SDValue Perm; 14748 if (isLittleEndian) 14749 Perm = BuildIntrinsicOp(IntrPerm, 14750 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14751 else 14752 Perm = BuildIntrinsicOp(IntrPerm, 14753 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14754 14755 if (VT != PermTy) 14756 Perm = Subtarget.hasAltivec() 14757 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14758 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14759 DAG.getTargetConstant(1, dl, MVT::i64)); 14760 // second argument is 1 because this rounding 14761 // is always exact. 14762 14763 // The output of the permutation is our loaded result, the TokenFactor is 14764 // our new chain. 14765 DCI.CombineTo(N, Perm, TF); 14766 return SDValue(N, 0); 14767 } 14768 } 14769 break; 14770 case ISD::INTRINSIC_WO_CHAIN: { 14771 bool isLittleEndian = Subtarget.isLittleEndian(); 14772 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14773 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14774 : Intrinsic::ppc_altivec_lvsl); 14775 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14776 SDValue Add = N->getOperand(1); 14777 14778 int Bits = 4 /* 16 byte alignment */; 14779 14780 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14781 APInt::getAllOnesValue(Bits /* alignment */) 14782 .zext(Add.getScalarValueSizeInBits()))) { 14783 SDNode *BasePtr = Add->getOperand(0).getNode(); 14784 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14785 UE = BasePtr->use_end(); 14786 UI != UE; ++UI) { 14787 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14788 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14789 IID) { 14790 // We've found another LVSL/LVSR, and this address is an aligned 14791 // multiple of that one. The results will be the same, so use the 14792 // one we've just found instead. 14793 14794 return SDValue(*UI, 0); 14795 } 14796 } 14797 } 14798 14799 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14800 SDNode *BasePtr = Add->getOperand(0).getNode(); 14801 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14802 UE = BasePtr->use_end(); UI != UE; ++UI) { 14803 if (UI->getOpcode() == ISD::ADD && 14804 isa<ConstantSDNode>(UI->getOperand(1)) && 14805 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14806 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14807 (1ULL << Bits) == 0) { 14808 SDNode *OtherAdd = *UI; 14809 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14810 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14811 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14812 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14813 return SDValue(*VI, 0); 14814 } 14815 } 14816 } 14817 } 14818 } 14819 } 14820 14821 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14822 // Expose the vabsduw/h/b opportunity for down stream 14823 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14824 (IID == Intrinsic::ppc_altivec_vmaxsw || 14825 IID == Intrinsic::ppc_altivec_vmaxsh || 14826 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14827 SDValue V1 = N->getOperand(1); 14828 SDValue V2 = N->getOperand(2); 14829 if ((V1.getSimpleValueType() == MVT::v4i32 || 14830 V1.getSimpleValueType() == MVT::v8i16 || 14831 V1.getSimpleValueType() == MVT::v16i8) && 14832 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14833 // (0-a, a) 14834 if (V1.getOpcode() == ISD::SUB && 14835 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14836 V1.getOperand(1) == V2) { 14837 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14838 } 14839 // (a, 0-a) 14840 if (V2.getOpcode() == ISD::SUB && 14841 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14842 V2.getOperand(1) == V1) { 14843 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14844 } 14845 // (x-y, y-x) 14846 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14847 V1.getOperand(0) == V2.getOperand(1) && 14848 V1.getOperand(1) == V2.getOperand(0)) { 14849 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14850 } 14851 } 14852 } 14853 } 14854 14855 break; 14856 case ISD::INTRINSIC_W_CHAIN: 14857 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14858 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14859 if (Subtarget.needsSwapsForVSXMemOps()) { 14860 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14861 default: 14862 break; 14863 case Intrinsic::ppc_vsx_lxvw4x: 14864 case Intrinsic::ppc_vsx_lxvd2x: 14865 return expandVSXLoadForLE(N, DCI); 14866 } 14867 } 14868 break; 14869 case ISD::INTRINSIC_VOID: 14870 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14871 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14872 if (Subtarget.needsSwapsForVSXMemOps()) { 14873 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14874 default: 14875 break; 14876 case Intrinsic::ppc_vsx_stxvw4x: 14877 case Intrinsic::ppc_vsx_stxvd2x: 14878 return expandVSXStoreForLE(N, DCI); 14879 } 14880 } 14881 break; 14882 case ISD::BSWAP: 14883 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14884 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14885 N->getOperand(0).hasOneUse() && 14886 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14887 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14888 N->getValueType(0) == MVT::i64))) { 14889 SDValue Load = N->getOperand(0); 14890 LoadSDNode *LD = cast<LoadSDNode>(Load); 14891 // Create the byte-swapping load. 14892 SDValue Ops[] = { 14893 LD->getChain(), // Chain 14894 LD->getBasePtr(), // Ptr 14895 DAG.getValueType(N->getValueType(0)) // VT 14896 }; 14897 SDValue BSLoad = 14898 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14899 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14900 MVT::i64 : MVT::i32, MVT::Other), 14901 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14902 14903 // If this is an i16 load, insert the truncate. 14904 SDValue ResVal = BSLoad; 14905 if (N->getValueType(0) == MVT::i16) 14906 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14907 14908 // First, combine the bswap away. This makes the value produced by the 14909 // load dead. 14910 DCI.CombineTo(N, ResVal); 14911 14912 // Next, combine the load away, we give it a bogus result value but a real 14913 // chain result. The result value is dead because the bswap is dead. 14914 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14915 14916 // Return N so it doesn't get rechecked! 14917 return SDValue(N, 0); 14918 } 14919 break; 14920 case PPCISD::VCMP: 14921 // If a VCMPo node already exists with exactly the same operands as this 14922 // node, use its result instead of this node (VCMPo computes both a CR6 and 14923 // a normal output). 14924 // 14925 if (!N->getOperand(0).hasOneUse() && 14926 !N->getOperand(1).hasOneUse() && 14927 !N->getOperand(2).hasOneUse()) { 14928 14929 // Scan all of the users of the LHS, looking for VCMPo's that match. 14930 SDNode *VCMPoNode = nullptr; 14931 14932 SDNode *LHSN = N->getOperand(0).getNode(); 14933 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14934 UI != E; ++UI) 14935 if (UI->getOpcode() == PPCISD::VCMPo && 14936 UI->getOperand(1) == N->getOperand(1) && 14937 UI->getOperand(2) == N->getOperand(2) && 14938 UI->getOperand(0) == N->getOperand(0)) { 14939 VCMPoNode = *UI; 14940 break; 14941 } 14942 14943 // If there is no VCMPo node, or if the flag value has a single use, don't 14944 // transform this. 14945 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14946 break; 14947 14948 // Look at the (necessarily single) use of the flag value. If it has a 14949 // chain, this transformation is more complex. Note that multiple things 14950 // could use the value result, which we should ignore. 14951 SDNode *FlagUser = nullptr; 14952 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14953 FlagUser == nullptr; ++UI) { 14954 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14955 SDNode *User = *UI; 14956 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14957 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14958 FlagUser = User; 14959 break; 14960 } 14961 } 14962 } 14963 14964 // If the user is a MFOCRF instruction, we know this is safe. 14965 // Otherwise we give up for right now. 14966 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14967 return SDValue(VCMPoNode, 0); 14968 } 14969 break; 14970 case ISD::BRCOND: { 14971 SDValue Cond = N->getOperand(1); 14972 SDValue Target = N->getOperand(2); 14973 14974 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14975 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14976 Intrinsic::loop_decrement) { 14977 14978 // We now need to make the intrinsic dead (it cannot be instruction 14979 // selected). 14980 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14981 assert(Cond.getNode()->hasOneUse() && 14982 "Counter decrement has more than one use"); 14983 14984 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14985 N->getOperand(0), Target); 14986 } 14987 } 14988 break; 14989 case ISD::BR_CC: { 14990 // If this is a branch on an altivec predicate comparison, lower this so 14991 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14992 // lowering is done pre-legalize, because the legalizer lowers the predicate 14993 // compare down to code that is difficult to reassemble. 14994 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14995 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14996 14997 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14998 // value. If so, pass-through the AND to get to the intrinsic. 14999 if (LHS.getOpcode() == ISD::AND && 15000 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15001 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15002 Intrinsic::loop_decrement && 15003 isa<ConstantSDNode>(LHS.getOperand(1)) && 15004 !isNullConstant(LHS.getOperand(1))) 15005 LHS = LHS.getOperand(0); 15006 15007 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15008 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15009 Intrinsic::loop_decrement && 15010 isa<ConstantSDNode>(RHS)) { 15011 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15012 "Counter decrement comparison is not EQ or NE"); 15013 15014 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15015 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15016 (CC == ISD::SETNE && !Val); 15017 15018 // We now need to make the intrinsic dead (it cannot be instruction 15019 // selected). 15020 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15021 assert(LHS.getNode()->hasOneUse() && 15022 "Counter decrement has more than one use"); 15023 15024 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15025 N->getOperand(0), N->getOperand(4)); 15026 } 15027 15028 int CompareOpc; 15029 bool isDot; 15030 15031 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15032 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15033 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15034 assert(isDot && "Can't compare against a vector result!"); 15035 15036 // If this is a comparison against something other than 0/1, then we know 15037 // that the condition is never/always true. 15038 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15039 if (Val != 0 && Val != 1) { 15040 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15041 return N->getOperand(0); 15042 // Always !=, turn it into an unconditional branch. 15043 return DAG.getNode(ISD::BR, dl, MVT::Other, 15044 N->getOperand(0), N->getOperand(4)); 15045 } 15046 15047 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15048 15049 // Create the PPCISD altivec 'dot' comparison node. 15050 SDValue Ops[] = { 15051 LHS.getOperand(2), // LHS of compare 15052 LHS.getOperand(3), // RHS of compare 15053 DAG.getConstant(CompareOpc, dl, MVT::i32) 15054 }; 15055 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15056 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15057 15058 // Unpack the result based on how the target uses it. 15059 PPC::Predicate CompOpc; 15060 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15061 default: // Can't happen, don't crash on invalid number though. 15062 case 0: // Branch on the value of the EQ bit of CR6. 15063 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15064 break; 15065 case 1: // Branch on the inverted value of the EQ bit of CR6. 15066 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15067 break; 15068 case 2: // Branch on the value of the LT bit of CR6. 15069 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15070 break; 15071 case 3: // Branch on the inverted value of the LT bit of CR6. 15072 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15073 break; 15074 } 15075 15076 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15077 DAG.getConstant(CompOpc, dl, MVT::i32), 15078 DAG.getRegister(PPC::CR6, MVT::i32), 15079 N->getOperand(4), CompNode.getValue(1)); 15080 } 15081 break; 15082 } 15083 case ISD::BUILD_VECTOR: 15084 return DAGCombineBuildVector(N, DCI); 15085 case ISD::ABS: 15086 return combineABS(N, DCI); 15087 case ISD::VSELECT: 15088 return combineVSelect(N, DCI); 15089 } 15090 15091 return SDValue(); 15092 } 15093 15094 SDValue 15095 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15096 SelectionDAG &DAG, 15097 SmallVectorImpl<SDNode *> &Created) const { 15098 // fold (sdiv X, pow2) 15099 EVT VT = N->getValueType(0); 15100 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15101 return SDValue(); 15102 if ((VT != MVT::i32 && VT != MVT::i64) || 15103 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15104 return SDValue(); 15105 15106 SDLoc DL(N); 15107 SDValue N0 = N->getOperand(0); 15108 15109 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15110 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15111 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15112 15113 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15114 Created.push_back(Op.getNode()); 15115 15116 if (IsNegPow2) { 15117 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15118 Created.push_back(Op.getNode()); 15119 } 15120 15121 return Op; 15122 } 15123 15124 //===----------------------------------------------------------------------===// 15125 // Inline Assembly Support 15126 //===----------------------------------------------------------------------===// 15127 15128 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15129 KnownBits &Known, 15130 const APInt &DemandedElts, 15131 const SelectionDAG &DAG, 15132 unsigned Depth) const { 15133 Known.resetAll(); 15134 switch (Op.getOpcode()) { 15135 default: break; 15136 case PPCISD::LBRX: { 15137 // lhbrx is known to have the top bits cleared out. 15138 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15139 Known.Zero = 0xFFFF0000; 15140 break; 15141 } 15142 case ISD::INTRINSIC_WO_CHAIN: { 15143 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15144 default: break; 15145 case Intrinsic::ppc_altivec_vcmpbfp_p: 15146 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15147 case Intrinsic::ppc_altivec_vcmpequb_p: 15148 case Intrinsic::ppc_altivec_vcmpequh_p: 15149 case Intrinsic::ppc_altivec_vcmpequw_p: 15150 case Intrinsic::ppc_altivec_vcmpequd_p: 15151 case Intrinsic::ppc_altivec_vcmpgefp_p: 15152 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15153 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15154 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15155 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15156 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15157 case Intrinsic::ppc_altivec_vcmpgtub_p: 15158 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15159 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15160 case Intrinsic::ppc_altivec_vcmpgtud_p: 15161 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15162 break; 15163 } 15164 } 15165 } 15166 } 15167 15168 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15169 switch (Subtarget.getCPUDirective()) { 15170 default: break; 15171 case PPC::DIR_970: 15172 case PPC::DIR_PWR4: 15173 case PPC::DIR_PWR5: 15174 case PPC::DIR_PWR5X: 15175 case PPC::DIR_PWR6: 15176 case PPC::DIR_PWR6X: 15177 case PPC::DIR_PWR7: 15178 case PPC::DIR_PWR8: 15179 case PPC::DIR_PWR9: 15180 case PPC::DIR_PWR10: 15181 case PPC::DIR_PWR_FUTURE: { 15182 if (!ML) 15183 break; 15184 15185 if (!DisableInnermostLoopAlign32) { 15186 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15187 // so that we can decrease cache misses and branch-prediction misses. 15188 // Actual alignment of the loop will depend on the hotness check and other 15189 // logic in alignBlocks. 15190 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15191 return Align(32); 15192 } 15193 15194 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15195 15196 // For small loops (between 5 and 8 instructions), align to a 32-byte 15197 // boundary so that the entire loop fits in one instruction-cache line. 15198 uint64_t LoopSize = 0; 15199 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15200 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15201 LoopSize += TII->getInstSizeInBytes(*J); 15202 if (LoopSize > 32) 15203 break; 15204 } 15205 15206 if (LoopSize > 16 && LoopSize <= 32) 15207 return Align(32); 15208 15209 break; 15210 } 15211 } 15212 15213 return TargetLowering::getPrefLoopAlignment(ML); 15214 } 15215 15216 /// getConstraintType - Given a constraint, return the type of 15217 /// constraint it is for this target. 15218 PPCTargetLowering::ConstraintType 15219 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15220 if (Constraint.size() == 1) { 15221 switch (Constraint[0]) { 15222 default: break; 15223 case 'b': 15224 case 'r': 15225 case 'f': 15226 case 'd': 15227 case 'v': 15228 case 'y': 15229 return C_RegisterClass; 15230 case 'Z': 15231 // FIXME: While Z does indicate a memory constraint, it specifically 15232 // indicates an r+r address (used in conjunction with the 'y' modifier 15233 // in the replacement string). Currently, we're forcing the base 15234 // register to be r0 in the asm printer (which is interpreted as zero) 15235 // and forming the complete address in the second register. This is 15236 // suboptimal. 15237 return C_Memory; 15238 } 15239 } else if (Constraint == "wc") { // individual CR bits. 15240 return C_RegisterClass; 15241 } else if (Constraint == "wa" || Constraint == "wd" || 15242 Constraint == "wf" || Constraint == "ws" || 15243 Constraint == "wi" || Constraint == "ww") { 15244 return C_RegisterClass; // VSX registers. 15245 } 15246 return TargetLowering::getConstraintType(Constraint); 15247 } 15248 15249 /// Examine constraint type and operand type and determine a weight value. 15250 /// This object must already have been set up with the operand type 15251 /// and the current alternative constraint selected. 15252 TargetLowering::ConstraintWeight 15253 PPCTargetLowering::getSingleConstraintMatchWeight( 15254 AsmOperandInfo &info, const char *constraint) const { 15255 ConstraintWeight weight = CW_Invalid; 15256 Value *CallOperandVal = info.CallOperandVal; 15257 // If we don't have a value, we can't do a match, 15258 // but allow it at the lowest weight. 15259 if (!CallOperandVal) 15260 return CW_Default; 15261 Type *type = CallOperandVal->getType(); 15262 15263 // Look at the constraint type. 15264 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15265 return CW_Register; // an individual CR bit. 15266 else if ((StringRef(constraint) == "wa" || 15267 StringRef(constraint) == "wd" || 15268 StringRef(constraint) == "wf") && 15269 type->isVectorTy()) 15270 return CW_Register; 15271 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15272 return CW_Register; // just hold 64-bit integers data. 15273 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15274 return CW_Register; 15275 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15276 return CW_Register; 15277 15278 switch (*constraint) { 15279 default: 15280 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15281 break; 15282 case 'b': 15283 if (type->isIntegerTy()) 15284 weight = CW_Register; 15285 break; 15286 case 'f': 15287 if (type->isFloatTy()) 15288 weight = CW_Register; 15289 break; 15290 case 'd': 15291 if (type->isDoubleTy()) 15292 weight = CW_Register; 15293 break; 15294 case 'v': 15295 if (type->isVectorTy()) 15296 weight = CW_Register; 15297 break; 15298 case 'y': 15299 weight = CW_Register; 15300 break; 15301 case 'Z': 15302 weight = CW_Memory; 15303 break; 15304 } 15305 return weight; 15306 } 15307 15308 std::pair<unsigned, const TargetRegisterClass *> 15309 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15310 StringRef Constraint, 15311 MVT VT) const { 15312 if (Constraint.size() == 1) { 15313 // GCC RS6000 Constraint Letters 15314 switch (Constraint[0]) { 15315 case 'b': // R1-R31 15316 if (VT == MVT::i64 && Subtarget.isPPC64()) 15317 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15318 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15319 case 'r': // R0-R31 15320 if (VT == MVT::i64 && Subtarget.isPPC64()) 15321 return std::make_pair(0U, &PPC::G8RCRegClass); 15322 return std::make_pair(0U, &PPC::GPRCRegClass); 15323 // 'd' and 'f' constraints are both defined to be "the floating point 15324 // registers", where one is for 32-bit and the other for 64-bit. We don't 15325 // really care overly much here so just give them all the same reg classes. 15326 case 'd': 15327 case 'f': 15328 if (Subtarget.hasSPE()) { 15329 if (VT == MVT::f32 || VT == MVT::i32) 15330 return std::make_pair(0U, &PPC::GPRCRegClass); 15331 if (VT == MVT::f64 || VT == MVT::i64) 15332 return std::make_pair(0U, &PPC::SPERCRegClass); 15333 } else { 15334 if (VT == MVT::f32 || VT == MVT::i32) 15335 return std::make_pair(0U, &PPC::F4RCRegClass); 15336 if (VT == MVT::f64 || VT == MVT::i64) 15337 return std::make_pair(0U, &PPC::F8RCRegClass); 15338 } 15339 break; 15340 case 'v': 15341 if (Subtarget.hasAltivec()) 15342 return std::make_pair(0U, &PPC::VRRCRegClass); 15343 break; 15344 case 'y': // crrc 15345 return std::make_pair(0U, &PPC::CRRCRegClass); 15346 } 15347 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15348 // An individual CR bit. 15349 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15350 } else if ((Constraint == "wa" || Constraint == "wd" || 15351 Constraint == "wf" || Constraint == "wi") && 15352 Subtarget.hasVSX()) { 15353 return std::make_pair(0U, &PPC::VSRCRegClass); 15354 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15355 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15356 return std::make_pair(0U, &PPC::VSSRCRegClass); 15357 else 15358 return std::make_pair(0U, &PPC::VSFRCRegClass); 15359 } 15360 15361 // If we name a VSX register, we can't defer to the base class because it 15362 // will not recognize the correct register (their names will be VSL{0-31} 15363 // and V{0-31} so they won't match). So we match them here. 15364 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15365 int VSNum = atoi(Constraint.data() + 3); 15366 assert(VSNum >= 0 && VSNum <= 63 && 15367 "Attempted to access a vsr out of range"); 15368 if (VSNum < 32) 15369 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15370 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15371 } 15372 std::pair<unsigned, const TargetRegisterClass *> R = 15373 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15374 15375 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15376 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15377 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15378 // register. 15379 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15380 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15381 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15382 PPC::GPRCRegClass.contains(R.first)) 15383 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15384 PPC::sub_32, &PPC::G8RCRegClass), 15385 &PPC::G8RCRegClass); 15386 15387 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15388 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15389 R.first = PPC::CR0; 15390 R.second = &PPC::CRRCRegClass; 15391 } 15392 15393 return R; 15394 } 15395 15396 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15397 /// vector. If it is invalid, don't add anything to Ops. 15398 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15399 std::string &Constraint, 15400 std::vector<SDValue>&Ops, 15401 SelectionDAG &DAG) const { 15402 SDValue Result; 15403 15404 // Only support length 1 constraints. 15405 if (Constraint.length() > 1) return; 15406 15407 char Letter = Constraint[0]; 15408 switch (Letter) { 15409 default: break; 15410 case 'I': 15411 case 'J': 15412 case 'K': 15413 case 'L': 15414 case 'M': 15415 case 'N': 15416 case 'O': 15417 case 'P': { 15418 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15419 if (!CST) return; // Must be an immediate to match. 15420 SDLoc dl(Op); 15421 int64_t Value = CST->getSExtValue(); 15422 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15423 // numbers are printed as such. 15424 switch (Letter) { 15425 default: llvm_unreachable("Unknown constraint letter!"); 15426 case 'I': // "I" is a signed 16-bit constant. 15427 if (isInt<16>(Value)) 15428 Result = DAG.getTargetConstant(Value, dl, TCVT); 15429 break; 15430 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15431 if (isShiftedUInt<16, 16>(Value)) 15432 Result = DAG.getTargetConstant(Value, dl, TCVT); 15433 break; 15434 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15435 if (isShiftedInt<16, 16>(Value)) 15436 Result = DAG.getTargetConstant(Value, dl, TCVT); 15437 break; 15438 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15439 if (isUInt<16>(Value)) 15440 Result = DAG.getTargetConstant(Value, dl, TCVT); 15441 break; 15442 case 'M': // "M" is a constant that is greater than 31. 15443 if (Value > 31) 15444 Result = DAG.getTargetConstant(Value, dl, TCVT); 15445 break; 15446 case 'N': // "N" is a positive constant that is an exact power of two. 15447 if (Value > 0 && isPowerOf2_64(Value)) 15448 Result = DAG.getTargetConstant(Value, dl, TCVT); 15449 break; 15450 case 'O': // "O" is the constant zero. 15451 if (Value == 0) 15452 Result = DAG.getTargetConstant(Value, dl, TCVT); 15453 break; 15454 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15455 if (isInt<16>(-Value)) 15456 Result = DAG.getTargetConstant(Value, dl, TCVT); 15457 break; 15458 } 15459 break; 15460 } 15461 } 15462 15463 if (Result.getNode()) { 15464 Ops.push_back(Result); 15465 return; 15466 } 15467 15468 // Handle standard constraint letters. 15469 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15470 } 15471 15472 // isLegalAddressingMode - Return true if the addressing mode represented 15473 // by AM is legal for this target, for a load/store of the specified type. 15474 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15475 const AddrMode &AM, Type *Ty, 15476 unsigned AS, 15477 Instruction *I) const { 15478 // Vector type r+i form is supported since power9 as DQ form. We don't check 15479 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15480 // imm form is preferred and the offset can be adjusted to use imm form later 15481 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15482 // max offset to check legal addressing mode, we should be a little aggressive 15483 // to contain other offsets for that LSRUse. 15484 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15485 return false; 15486 15487 // PPC allows a sign-extended 16-bit immediate field. 15488 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15489 return false; 15490 15491 // No global is ever allowed as a base. 15492 if (AM.BaseGV) 15493 return false; 15494 15495 // PPC only support r+r, 15496 switch (AM.Scale) { 15497 case 0: // "r+i" or just "i", depending on HasBaseReg. 15498 break; 15499 case 1: 15500 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15501 return false; 15502 // Otherwise we have r+r or r+i. 15503 break; 15504 case 2: 15505 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15506 return false; 15507 // Allow 2*r as r+r. 15508 break; 15509 default: 15510 // No other scales are supported. 15511 return false; 15512 } 15513 15514 return true; 15515 } 15516 15517 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15518 SelectionDAG &DAG) const { 15519 MachineFunction &MF = DAG.getMachineFunction(); 15520 MachineFrameInfo &MFI = MF.getFrameInfo(); 15521 MFI.setReturnAddressIsTaken(true); 15522 15523 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15524 return SDValue(); 15525 15526 SDLoc dl(Op); 15527 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15528 15529 // Make sure the function does not optimize away the store of the RA to 15530 // the stack. 15531 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15532 FuncInfo->setLRStoreRequired(); 15533 bool isPPC64 = Subtarget.isPPC64(); 15534 auto PtrVT = getPointerTy(MF.getDataLayout()); 15535 15536 if (Depth > 0) { 15537 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15538 SDValue Offset = 15539 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15540 isPPC64 ? MVT::i64 : MVT::i32); 15541 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15542 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15543 MachinePointerInfo()); 15544 } 15545 15546 // Just load the return address off the stack. 15547 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15548 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15549 MachinePointerInfo()); 15550 } 15551 15552 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15553 SelectionDAG &DAG) const { 15554 SDLoc dl(Op); 15555 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15556 15557 MachineFunction &MF = DAG.getMachineFunction(); 15558 MachineFrameInfo &MFI = MF.getFrameInfo(); 15559 MFI.setFrameAddressIsTaken(true); 15560 15561 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15562 bool isPPC64 = PtrVT == MVT::i64; 15563 15564 // Naked functions never have a frame pointer, and so we use r1. For all 15565 // other functions, this decision must be delayed until during PEI. 15566 unsigned FrameReg; 15567 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15568 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15569 else 15570 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15571 15572 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15573 PtrVT); 15574 while (Depth--) 15575 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15576 FrameAddr, MachinePointerInfo()); 15577 return FrameAddr; 15578 } 15579 15580 // FIXME? Maybe this could be a TableGen attribute on some registers and 15581 // this table could be generated automatically from RegInfo. 15582 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15583 const MachineFunction &MF) const { 15584 bool isPPC64 = Subtarget.isPPC64(); 15585 15586 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15587 if (!is64Bit && VT != LLT::scalar(32)) 15588 report_fatal_error("Invalid register global variable type"); 15589 15590 Register Reg = StringSwitch<Register>(RegName) 15591 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15592 .Case("r2", isPPC64 ? Register() : PPC::R2) 15593 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15594 .Default(Register()); 15595 15596 if (Reg) 15597 return Reg; 15598 report_fatal_error("Invalid register name global variable"); 15599 } 15600 15601 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15602 // 32-bit SVR4 ABI access everything as got-indirect. 15603 if (Subtarget.is32BitELFABI()) 15604 return true; 15605 15606 // AIX accesses everything indirectly through the TOC, which is similar to 15607 // the GOT. 15608 if (Subtarget.isAIXABI()) 15609 return true; 15610 15611 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15612 // If it is small or large code model, module locals are accessed 15613 // indirectly by loading their address from .toc/.got. 15614 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15615 return true; 15616 15617 // JumpTable and BlockAddress are accessed as got-indirect. 15618 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15619 return true; 15620 15621 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15622 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15623 15624 return false; 15625 } 15626 15627 bool 15628 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15629 // The PowerPC target isn't yet aware of offsets. 15630 return false; 15631 } 15632 15633 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15634 const CallInst &I, 15635 MachineFunction &MF, 15636 unsigned Intrinsic) const { 15637 switch (Intrinsic) { 15638 case Intrinsic::ppc_altivec_lvx: 15639 case Intrinsic::ppc_altivec_lvxl: 15640 case Intrinsic::ppc_altivec_lvebx: 15641 case Intrinsic::ppc_altivec_lvehx: 15642 case Intrinsic::ppc_altivec_lvewx: 15643 case Intrinsic::ppc_vsx_lxvd2x: 15644 case Intrinsic::ppc_vsx_lxvw4x: { 15645 EVT VT; 15646 switch (Intrinsic) { 15647 case Intrinsic::ppc_altivec_lvebx: 15648 VT = MVT::i8; 15649 break; 15650 case Intrinsic::ppc_altivec_lvehx: 15651 VT = MVT::i16; 15652 break; 15653 case Intrinsic::ppc_altivec_lvewx: 15654 VT = MVT::i32; 15655 break; 15656 case Intrinsic::ppc_vsx_lxvd2x: 15657 VT = MVT::v2f64; 15658 break; 15659 default: 15660 VT = MVT::v4i32; 15661 break; 15662 } 15663 15664 Info.opc = ISD::INTRINSIC_W_CHAIN; 15665 Info.memVT = VT; 15666 Info.ptrVal = I.getArgOperand(0); 15667 Info.offset = -VT.getStoreSize()+1; 15668 Info.size = 2*VT.getStoreSize()-1; 15669 Info.align = Align(1); 15670 Info.flags = MachineMemOperand::MOLoad; 15671 return true; 15672 } 15673 case Intrinsic::ppc_altivec_stvx: 15674 case Intrinsic::ppc_altivec_stvxl: 15675 case Intrinsic::ppc_altivec_stvebx: 15676 case Intrinsic::ppc_altivec_stvehx: 15677 case Intrinsic::ppc_altivec_stvewx: 15678 case Intrinsic::ppc_vsx_stxvd2x: 15679 case Intrinsic::ppc_vsx_stxvw4x: { 15680 EVT VT; 15681 switch (Intrinsic) { 15682 case Intrinsic::ppc_altivec_stvebx: 15683 VT = MVT::i8; 15684 break; 15685 case Intrinsic::ppc_altivec_stvehx: 15686 VT = MVT::i16; 15687 break; 15688 case Intrinsic::ppc_altivec_stvewx: 15689 VT = MVT::i32; 15690 break; 15691 case Intrinsic::ppc_vsx_stxvd2x: 15692 VT = MVT::v2f64; 15693 break; 15694 default: 15695 VT = MVT::v4i32; 15696 break; 15697 } 15698 15699 Info.opc = ISD::INTRINSIC_VOID; 15700 Info.memVT = VT; 15701 Info.ptrVal = I.getArgOperand(1); 15702 Info.offset = -VT.getStoreSize()+1; 15703 Info.size = 2*VT.getStoreSize()-1; 15704 Info.align = Align(1); 15705 Info.flags = MachineMemOperand::MOStore; 15706 return true; 15707 } 15708 default: 15709 break; 15710 } 15711 15712 return false; 15713 } 15714 15715 /// It returns EVT::Other if the type should be determined using generic 15716 /// target-independent logic. 15717 EVT PPCTargetLowering::getOptimalMemOpType( 15718 const MemOp &Op, const AttributeList &FuncAttributes) const { 15719 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15720 // We should use Altivec/VSX loads and stores when available. For unaligned 15721 // addresses, unaligned VSX loads are only fast starting with the P8. 15722 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15723 (Op.isAligned(Align(16)) || 15724 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15725 return MVT::v4i32; 15726 } 15727 15728 if (Subtarget.isPPC64()) { 15729 return MVT::i64; 15730 } 15731 15732 return MVT::i32; 15733 } 15734 15735 /// Returns true if it is beneficial to convert a load of a constant 15736 /// to just the constant itself. 15737 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15738 Type *Ty) const { 15739 assert(Ty->isIntegerTy()); 15740 15741 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15742 return !(BitSize == 0 || BitSize > 64); 15743 } 15744 15745 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15746 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15747 return false; 15748 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15749 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15750 return NumBits1 == 64 && NumBits2 == 32; 15751 } 15752 15753 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15754 if (!VT1.isInteger() || !VT2.isInteger()) 15755 return false; 15756 unsigned NumBits1 = VT1.getSizeInBits(); 15757 unsigned NumBits2 = VT2.getSizeInBits(); 15758 return NumBits1 == 64 && NumBits2 == 32; 15759 } 15760 15761 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15762 // Generally speaking, zexts are not free, but they are free when they can be 15763 // folded with other operations. 15764 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15765 EVT MemVT = LD->getMemoryVT(); 15766 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15767 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15768 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15769 LD->getExtensionType() == ISD::ZEXTLOAD)) 15770 return true; 15771 } 15772 15773 // FIXME: Add other cases... 15774 // - 32-bit shifts with a zext to i64 15775 // - zext after ctlz, bswap, etc. 15776 // - zext after and by a constant mask 15777 15778 return TargetLowering::isZExtFree(Val, VT2); 15779 } 15780 15781 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15782 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15783 "invalid fpext types"); 15784 // Extending to float128 is not free. 15785 if (DestVT == MVT::f128) 15786 return false; 15787 return true; 15788 } 15789 15790 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15791 return isInt<16>(Imm) || isUInt<16>(Imm); 15792 } 15793 15794 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15795 return isInt<16>(Imm) || isUInt<16>(Imm); 15796 } 15797 15798 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15799 unsigned, 15800 unsigned, 15801 MachineMemOperand::Flags, 15802 bool *Fast) const { 15803 if (DisablePPCUnaligned) 15804 return false; 15805 15806 // PowerPC supports unaligned memory access for simple non-vector types. 15807 // Although accessing unaligned addresses is not as efficient as accessing 15808 // aligned addresses, it is generally more efficient than manual expansion, 15809 // and generally only traps for software emulation when crossing page 15810 // boundaries. 15811 15812 if (!VT.isSimple()) 15813 return false; 15814 15815 if (VT.isFloatingPoint() && !VT.isVector() && 15816 !Subtarget.allowsUnalignedFPAccess()) 15817 return false; 15818 15819 if (VT.getSimpleVT().isVector()) { 15820 if (Subtarget.hasVSX()) { 15821 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15822 VT != MVT::v4f32 && VT != MVT::v4i32) 15823 return false; 15824 } else { 15825 return false; 15826 } 15827 } 15828 15829 if (VT == MVT::ppcf128) 15830 return false; 15831 15832 if (Fast) 15833 *Fast = true; 15834 15835 return true; 15836 } 15837 15838 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15839 EVT VT) const { 15840 return isFMAFasterThanFMulAndFAdd( 15841 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15842 } 15843 15844 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15845 Type *Ty) const { 15846 switch (Ty->getScalarType()->getTypeID()) { 15847 case Type::FloatTyID: 15848 case Type::DoubleTyID: 15849 return true; 15850 case Type::FP128TyID: 15851 return Subtarget.hasP9Vector(); 15852 default: 15853 return false; 15854 } 15855 } 15856 15857 // FIXME: add more patterns which are not profitable to hoist. 15858 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15859 if (!I->hasOneUse()) 15860 return true; 15861 15862 Instruction *User = I->user_back(); 15863 assert(User && "A single use instruction with no uses."); 15864 15865 switch (I->getOpcode()) { 15866 case Instruction::FMul: { 15867 // Don't break FMA, PowerPC prefers FMA. 15868 if (User->getOpcode() != Instruction::FSub && 15869 User->getOpcode() != Instruction::FAdd) 15870 return true; 15871 15872 const TargetOptions &Options = getTargetMachine().Options; 15873 const Function *F = I->getFunction(); 15874 const DataLayout &DL = F->getParent()->getDataLayout(); 15875 Type *Ty = User->getOperand(0)->getType(); 15876 15877 return !( 15878 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15879 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15880 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15881 } 15882 case Instruction::Load: { 15883 // Don't break "store (load float*)" pattern, this pattern will be combined 15884 // to "store (load int32)" in later InstCombine pass. See function 15885 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15886 // cycles than loading a 32 bit integer. 15887 LoadInst *LI = cast<LoadInst>(I); 15888 // For the loads that combineLoadToOperationType does nothing, like 15889 // ordered load, it should be profitable to hoist them. 15890 // For swifterror load, it can only be used for pointer to pointer type, so 15891 // later type check should get rid of this case. 15892 if (!LI->isUnordered()) 15893 return true; 15894 15895 if (User->getOpcode() != Instruction::Store) 15896 return true; 15897 15898 if (I->getType()->getTypeID() != Type::FloatTyID) 15899 return true; 15900 15901 return false; 15902 } 15903 default: 15904 return true; 15905 } 15906 return true; 15907 } 15908 15909 const MCPhysReg * 15910 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15911 // LR is a callee-save register, but we must treat it as clobbered by any call 15912 // site. Hence we include LR in the scratch registers, which are in turn added 15913 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15914 // to CTR, which is used by any indirect call. 15915 static const MCPhysReg ScratchRegs[] = { 15916 PPC::X12, PPC::LR8, PPC::CTR8, 0 15917 }; 15918 15919 return ScratchRegs; 15920 } 15921 15922 Register PPCTargetLowering::getExceptionPointerRegister( 15923 const Constant *PersonalityFn) const { 15924 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15925 } 15926 15927 Register PPCTargetLowering::getExceptionSelectorRegister( 15928 const Constant *PersonalityFn) const { 15929 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15930 } 15931 15932 bool 15933 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15934 EVT VT , unsigned DefinedValues) const { 15935 if (VT == MVT::v2i64) 15936 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15937 15938 if (Subtarget.hasVSX()) 15939 return true; 15940 15941 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15942 } 15943 15944 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15945 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15946 return TargetLowering::getSchedulingPreference(N); 15947 15948 return Sched::ILP; 15949 } 15950 15951 // Create a fast isel object. 15952 FastISel * 15953 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15954 const TargetLibraryInfo *LibInfo) const { 15955 return PPC::createFastISel(FuncInfo, LibInfo); 15956 } 15957 15958 // 'Inverted' means the FMA opcode after negating one multiplicand. 15959 // For example, (fma -a b c) = (fnmsub a b c) 15960 static unsigned invertFMAOpcode(unsigned Opc) { 15961 switch (Opc) { 15962 default: 15963 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15964 case ISD::FMA: 15965 return PPCISD::FNMSUB; 15966 case PPCISD::FNMSUB: 15967 return ISD::FMA; 15968 } 15969 } 15970 15971 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15972 bool LegalOps, bool OptForSize, 15973 NegatibleCost &Cost, 15974 unsigned Depth) const { 15975 if (Depth > SelectionDAG::MaxRecursionDepth) 15976 return SDValue(); 15977 15978 unsigned Opc = Op.getOpcode(); 15979 EVT VT = Op.getValueType(); 15980 SDNodeFlags Flags = Op.getNode()->getFlags(); 15981 15982 switch (Opc) { 15983 case PPCISD::FNMSUB: 15984 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15985 break; 15986 15987 const TargetOptions &Options = getTargetMachine().Options; 15988 SDValue N0 = Op.getOperand(0); 15989 SDValue N1 = Op.getOperand(1); 15990 SDValue N2 = Op.getOperand(2); 15991 SDLoc Loc(Op); 15992 15993 NegatibleCost N2Cost = NegatibleCost::Expensive; 15994 SDValue NegN2 = 15995 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15996 15997 if (!NegN2) 15998 return SDValue(); 15999 16000 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16001 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16002 // These transformations may change sign of zeroes. For example, 16003 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16004 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16005 // Try and choose the cheaper one to negate. 16006 NegatibleCost N0Cost = NegatibleCost::Expensive; 16007 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16008 N0Cost, Depth + 1); 16009 16010 NegatibleCost N1Cost = NegatibleCost::Expensive; 16011 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16012 N1Cost, Depth + 1); 16013 16014 if (NegN0 && N0Cost <= N1Cost) { 16015 Cost = std::min(N0Cost, N2Cost); 16016 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16017 } else if (NegN1) { 16018 Cost = std::min(N1Cost, N2Cost); 16019 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16020 } 16021 } 16022 16023 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16024 if (isOperationLegal(ISD::FMA, VT)) { 16025 Cost = N2Cost; 16026 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16027 } 16028 16029 break; 16030 } 16031 16032 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16033 Cost, Depth); 16034 } 16035 16036 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16037 bool PPCTargetLowering::useLoadStackGuardNode() const { 16038 if (!Subtarget.isTargetLinux()) 16039 return TargetLowering::useLoadStackGuardNode(); 16040 return true; 16041 } 16042 16043 // Override to disable global variable loading on Linux. 16044 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16045 if (!Subtarget.isTargetLinux()) 16046 return TargetLowering::insertSSPDeclarations(M); 16047 } 16048 16049 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16050 bool ForCodeSize) const { 16051 if (!VT.isSimple() || !Subtarget.hasVSX()) 16052 return false; 16053 16054 switch(VT.getSimpleVT().SimpleTy) { 16055 default: 16056 // For FP types that are currently not supported by PPC backend, return 16057 // false. Examples: f16, f80. 16058 return false; 16059 case MVT::f32: 16060 case MVT::f64: 16061 if (Subtarget.hasPrefixInstrs()) { 16062 // With prefixed instructions, we can materialize anything that can be 16063 // represented with a 32-bit immediate, not just positive zero. 16064 APFloat APFloatOfImm = Imm; 16065 return convertToNonDenormSingle(APFloatOfImm); 16066 } 16067 LLVM_FALLTHROUGH; 16068 case MVT::ppcf128: 16069 return Imm.isPosZero(); 16070 } 16071 } 16072 16073 // For vector shift operation op, fold 16074 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16075 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16076 SelectionDAG &DAG) { 16077 SDValue N0 = N->getOperand(0); 16078 SDValue N1 = N->getOperand(1); 16079 EVT VT = N0.getValueType(); 16080 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16081 unsigned Opcode = N->getOpcode(); 16082 unsigned TargetOpcode; 16083 16084 switch (Opcode) { 16085 default: 16086 llvm_unreachable("Unexpected shift operation"); 16087 case ISD::SHL: 16088 TargetOpcode = PPCISD::SHL; 16089 break; 16090 case ISD::SRL: 16091 TargetOpcode = PPCISD::SRL; 16092 break; 16093 case ISD::SRA: 16094 TargetOpcode = PPCISD::SRA; 16095 break; 16096 } 16097 16098 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16099 N1->getOpcode() == ISD::AND) 16100 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16101 if (Mask->getZExtValue() == OpSizeInBits - 1) 16102 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16103 16104 return SDValue(); 16105 } 16106 16107 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16108 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16109 return Value; 16110 16111 SDValue N0 = N->getOperand(0); 16112 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16113 if (!Subtarget.isISA3_0() || 16114 N0.getOpcode() != ISD::SIGN_EXTEND || 16115 N0.getOperand(0).getValueType() != MVT::i32 || 16116 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16117 return SDValue(); 16118 16119 // We can't save an operation here if the value is already extended, and 16120 // the existing shift is easier to combine. 16121 SDValue ExtsSrc = N0.getOperand(0); 16122 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16123 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16124 return SDValue(); 16125 16126 SDLoc DL(N0); 16127 SDValue ShiftBy = SDValue(CN1, 0); 16128 // We want the shift amount to be i32 on the extswli, but the shift could 16129 // have an i64. 16130 if (ShiftBy.getValueType() == MVT::i64) 16131 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16132 16133 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16134 ShiftBy); 16135 } 16136 16137 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16138 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16139 return Value; 16140 16141 return SDValue(); 16142 } 16143 16144 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16145 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16146 return Value; 16147 16148 return SDValue(); 16149 } 16150 16151 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16152 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16153 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16154 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16155 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16156 const PPCSubtarget &Subtarget) { 16157 if (!Subtarget.isPPC64()) 16158 return SDValue(); 16159 16160 SDValue LHS = N->getOperand(0); 16161 SDValue RHS = N->getOperand(1); 16162 16163 auto isZextOfCompareWithConstant = [](SDValue Op) { 16164 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16165 Op.getValueType() != MVT::i64) 16166 return false; 16167 16168 SDValue Cmp = Op.getOperand(0); 16169 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16170 Cmp.getOperand(0).getValueType() != MVT::i64) 16171 return false; 16172 16173 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16174 int64_t NegConstant = 0 - Constant->getSExtValue(); 16175 // Due to the limitations of the addi instruction, 16176 // -C is required to be [-32768, 32767]. 16177 return isInt<16>(NegConstant); 16178 } 16179 16180 return false; 16181 }; 16182 16183 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16184 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16185 16186 // If there is a pattern, canonicalize a zext operand to the RHS. 16187 if (LHSHasPattern && !RHSHasPattern) 16188 std::swap(LHS, RHS); 16189 else if (!LHSHasPattern && !RHSHasPattern) 16190 return SDValue(); 16191 16192 SDLoc DL(N); 16193 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16194 SDValue Cmp = RHS.getOperand(0); 16195 SDValue Z = Cmp.getOperand(0); 16196 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16197 16198 assert(Constant && "Constant Should not be a null pointer."); 16199 int64_t NegConstant = 0 - Constant->getSExtValue(); 16200 16201 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16202 default: break; 16203 case ISD::SETNE: { 16204 // when C == 0 16205 // --> addze X, (addic Z, -1).carry 16206 // / 16207 // add X, (zext(setne Z, C))-- 16208 // \ when -32768 <= -C <= 32767 && C != 0 16209 // --> addze X, (addic (addi Z, -C), -1).carry 16210 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16211 DAG.getConstant(NegConstant, DL, MVT::i64)); 16212 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16213 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16214 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16215 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16216 SDValue(Addc.getNode(), 1)); 16217 } 16218 case ISD::SETEQ: { 16219 // when C == 0 16220 // --> addze X, (subfic Z, 0).carry 16221 // / 16222 // add X, (zext(sete Z, C))-- 16223 // \ when -32768 <= -C <= 32767 && C != 0 16224 // --> addze X, (subfic (addi Z, -C), 0).carry 16225 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16226 DAG.getConstant(NegConstant, DL, MVT::i64)); 16227 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16228 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16229 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16230 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16231 SDValue(Subc.getNode(), 1)); 16232 } 16233 } 16234 16235 return SDValue(); 16236 } 16237 16238 // Transform 16239 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16240 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16241 // In this case both C1 and C2 must be known constants. 16242 // C1+C2 must fit into a 34 bit signed integer. 16243 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16244 const PPCSubtarget &Subtarget) { 16245 if (!Subtarget.isUsingPCRelativeCalls()) 16246 return SDValue(); 16247 16248 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16249 // If we find that node try to cast the Global Address and the Constant. 16250 SDValue LHS = N->getOperand(0); 16251 SDValue RHS = N->getOperand(1); 16252 16253 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16254 std::swap(LHS, RHS); 16255 16256 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16257 return SDValue(); 16258 16259 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16260 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16261 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16262 16263 // Check that both casts succeeded. 16264 if (!GSDN || !ConstNode) 16265 return SDValue(); 16266 16267 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16268 SDLoc DL(GSDN); 16269 16270 // The signed int offset needs to fit in 34 bits. 16271 if (!isInt<34>(NewOffset)) 16272 return SDValue(); 16273 16274 // The new global address is a copy of the old global address except 16275 // that it has the updated Offset. 16276 SDValue GA = 16277 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16278 NewOffset, GSDN->getTargetFlags()); 16279 SDValue MatPCRel = 16280 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16281 return MatPCRel; 16282 } 16283 16284 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16285 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16286 return Value; 16287 16288 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16289 return Value; 16290 16291 return SDValue(); 16292 } 16293 16294 // Detect TRUNCATE operations on bitcasts of float128 values. 16295 // What we are looking for here is the situtation where we extract a subset 16296 // of bits from a 128 bit float. 16297 // This can be of two forms: 16298 // 1) BITCAST of f128 feeding TRUNCATE 16299 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16300 // The reason this is required is because we do not have a legal i128 type 16301 // and so we want to prevent having to store the f128 and then reload part 16302 // of it. 16303 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16304 DAGCombinerInfo &DCI) const { 16305 // If we are using CRBits then try that first. 16306 if (Subtarget.useCRBits()) { 16307 // Check if CRBits did anything and return that if it did. 16308 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16309 return CRTruncValue; 16310 } 16311 16312 SDLoc dl(N); 16313 SDValue Op0 = N->getOperand(0); 16314 16315 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16316 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16317 EVT VT = N->getValueType(0); 16318 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16319 return SDValue(); 16320 SDValue Sub = Op0.getOperand(0); 16321 if (Sub.getOpcode() == ISD::SUB) { 16322 SDValue SubOp0 = Sub.getOperand(0); 16323 SDValue SubOp1 = Sub.getOperand(1); 16324 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16325 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16326 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16327 SubOp1.getOperand(0), 16328 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16329 } 16330 } 16331 } 16332 16333 // Looking for a truncate of i128 to i64. 16334 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16335 return SDValue(); 16336 16337 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16338 16339 // SRL feeding TRUNCATE. 16340 if (Op0.getOpcode() == ISD::SRL) { 16341 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16342 // The right shift has to be by 64 bits. 16343 if (!ConstNode || ConstNode->getZExtValue() != 64) 16344 return SDValue(); 16345 16346 // Switch the element number to extract. 16347 EltToExtract = EltToExtract ? 0 : 1; 16348 // Update Op0 past the SRL. 16349 Op0 = Op0.getOperand(0); 16350 } 16351 16352 // BITCAST feeding a TRUNCATE possibly via SRL. 16353 if (Op0.getOpcode() == ISD::BITCAST && 16354 Op0.getValueType() == MVT::i128 && 16355 Op0.getOperand(0).getValueType() == MVT::f128) { 16356 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16357 return DCI.DAG.getNode( 16358 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16359 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16360 } 16361 return SDValue(); 16362 } 16363 16364 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16365 SelectionDAG &DAG = DCI.DAG; 16366 16367 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16368 if (!ConstOpOrElement) 16369 return SDValue(); 16370 16371 // An imul is usually smaller than the alternative sequence for legal type. 16372 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16373 isOperationLegal(ISD::MUL, N->getValueType(0))) 16374 return SDValue(); 16375 16376 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16377 switch (this->Subtarget.getCPUDirective()) { 16378 default: 16379 // TODO: enhance the condition for subtarget before pwr8 16380 return false; 16381 case PPC::DIR_PWR8: 16382 // type mul add shl 16383 // scalar 4 1 1 16384 // vector 7 2 2 16385 return true; 16386 case PPC::DIR_PWR9: 16387 case PPC::DIR_PWR10: 16388 case PPC::DIR_PWR_FUTURE: 16389 // type mul add shl 16390 // scalar 5 2 2 16391 // vector 7 2 2 16392 16393 // The cycle RATIO of related operations are showed as a table above. 16394 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16395 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16396 // are 4, it is always profitable; but for 3 instrs patterns 16397 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16398 // So we should only do it for vector type. 16399 return IsAddOne && IsNeg ? VT.isVector() : true; 16400 } 16401 }; 16402 16403 EVT VT = N->getValueType(0); 16404 SDLoc DL(N); 16405 16406 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16407 bool IsNeg = MulAmt.isNegative(); 16408 APInt MulAmtAbs = MulAmt.abs(); 16409 16410 if ((MulAmtAbs - 1).isPowerOf2()) { 16411 // (mul x, 2^N + 1) => (add (shl x, N), x) 16412 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16413 16414 if (!IsProfitable(IsNeg, true, VT)) 16415 return SDValue(); 16416 16417 SDValue Op0 = N->getOperand(0); 16418 SDValue Op1 = 16419 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16420 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16421 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16422 16423 if (!IsNeg) 16424 return Res; 16425 16426 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16427 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16428 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16429 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16430 16431 if (!IsProfitable(IsNeg, false, VT)) 16432 return SDValue(); 16433 16434 SDValue Op0 = N->getOperand(0); 16435 SDValue Op1 = 16436 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16437 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16438 16439 if (!IsNeg) 16440 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16441 else 16442 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16443 16444 } else { 16445 return SDValue(); 16446 } 16447 } 16448 16449 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16450 // in combiner since we need to check SD flags and other subtarget features. 16451 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16452 DAGCombinerInfo &DCI) const { 16453 SDValue N0 = N->getOperand(0); 16454 SDValue N1 = N->getOperand(1); 16455 SDValue N2 = N->getOperand(2); 16456 SDNodeFlags Flags = N->getFlags(); 16457 EVT VT = N->getValueType(0); 16458 SelectionDAG &DAG = DCI.DAG; 16459 const TargetOptions &Options = getTargetMachine().Options; 16460 unsigned Opc = N->getOpcode(); 16461 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16462 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16463 SDLoc Loc(N); 16464 16465 if (!isOperationLegal(ISD::FMA, VT)) 16466 return SDValue(); 16467 16468 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16469 // since (fnmsub a b c)=-0 while c-ab=+0. 16470 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16471 return SDValue(); 16472 16473 // (fma (fneg a) b c) => (fnmsub a b c) 16474 // (fnmsub (fneg a) b c) => (fma a b c) 16475 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16476 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16477 16478 // (fma a (fneg b) c) => (fnmsub a b c) 16479 // (fnmsub a (fneg b) c) => (fma a b c) 16480 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16481 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16482 16483 return SDValue(); 16484 } 16485 16486 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16487 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16488 if (!Subtarget.is64BitELFABI()) 16489 return false; 16490 16491 // If not a tail call then no need to proceed. 16492 if (!CI->isTailCall()) 16493 return false; 16494 16495 // If sibling calls have been disabled and tail-calls aren't guaranteed 16496 // there is no reason to duplicate. 16497 auto &TM = getTargetMachine(); 16498 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16499 return false; 16500 16501 // Can't tail call a function called indirectly, or if it has variadic args. 16502 const Function *Callee = CI->getCalledFunction(); 16503 if (!Callee || Callee->isVarArg()) 16504 return false; 16505 16506 // Make sure the callee and caller calling conventions are eligible for tco. 16507 const Function *Caller = CI->getParent()->getParent(); 16508 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16509 CI->getCallingConv())) 16510 return false; 16511 16512 // If the function is local then we have a good chance at tail-calling it 16513 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16514 } 16515 16516 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16517 if (!Subtarget.hasVSX()) 16518 return false; 16519 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16520 return true; 16521 return VT == MVT::f32 || VT == MVT::f64 || 16522 VT == MVT::v4f32 || VT == MVT::v2f64; 16523 } 16524 16525 bool PPCTargetLowering:: 16526 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16527 const Value *Mask = AndI.getOperand(1); 16528 // If the mask is suitable for andi. or andis. we should sink the and. 16529 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16530 // Can't handle constants wider than 64-bits. 16531 if (CI->getBitWidth() > 64) 16532 return false; 16533 int64_t ConstVal = CI->getZExtValue(); 16534 return isUInt<16>(ConstVal) || 16535 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16536 } 16537 16538 // For non-constant masks, we can always use the record-form and. 16539 return true; 16540 } 16541 16542 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16543 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16544 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16545 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16546 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16547 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16548 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16549 assert(Subtarget.hasP9Altivec() && 16550 "Only combine this when P9 altivec supported!"); 16551 EVT VT = N->getValueType(0); 16552 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16553 return SDValue(); 16554 16555 SelectionDAG &DAG = DCI.DAG; 16556 SDLoc dl(N); 16557 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16558 // Even for signed integers, if it's known to be positive (as signed 16559 // integer) due to zero-extended inputs. 16560 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16561 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16562 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16563 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16564 (SubOpcd1 == ISD::ZERO_EXTEND || 16565 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16566 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16567 N->getOperand(0)->getOperand(0), 16568 N->getOperand(0)->getOperand(1), 16569 DAG.getTargetConstant(0, dl, MVT::i32)); 16570 } 16571 16572 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16573 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16574 N->getOperand(0).hasOneUse()) { 16575 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16576 N->getOperand(0)->getOperand(0), 16577 N->getOperand(0)->getOperand(1), 16578 DAG.getTargetConstant(1, dl, MVT::i32)); 16579 } 16580 } 16581 16582 return SDValue(); 16583 } 16584 16585 // For type v4i32/v8ii16/v16i8, transform 16586 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16587 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16588 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16589 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16590 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16591 DAGCombinerInfo &DCI) const { 16592 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16593 assert(Subtarget.hasP9Altivec() && 16594 "Only combine this when P9 altivec supported!"); 16595 16596 SelectionDAG &DAG = DCI.DAG; 16597 SDLoc dl(N); 16598 SDValue Cond = N->getOperand(0); 16599 SDValue TrueOpnd = N->getOperand(1); 16600 SDValue FalseOpnd = N->getOperand(2); 16601 EVT VT = N->getOperand(1).getValueType(); 16602 16603 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16604 FalseOpnd.getOpcode() != ISD::SUB) 16605 return SDValue(); 16606 16607 // ABSD only available for type v4i32/v8i16/v16i8 16608 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16609 return SDValue(); 16610 16611 // At least to save one more dependent computation 16612 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16613 return SDValue(); 16614 16615 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16616 16617 // Can only handle unsigned comparison here 16618 switch (CC) { 16619 default: 16620 return SDValue(); 16621 case ISD::SETUGT: 16622 case ISD::SETUGE: 16623 break; 16624 case ISD::SETULT: 16625 case ISD::SETULE: 16626 std::swap(TrueOpnd, FalseOpnd); 16627 break; 16628 } 16629 16630 SDValue CmpOpnd1 = Cond.getOperand(0); 16631 SDValue CmpOpnd2 = Cond.getOperand(1); 16632 16633 // SETCC CmpOpnd1 CmpOpnd2 cond 16634 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16635 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16636 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16637 TrueOpnd.getOperand(1) == CmpOpnd2 && 16638 FalseOpnd.getOperand(0) == CmpOpnd2 && 16639 FalseOpnd.getOperand(1) == CmpOpnd1) { 16640 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16641 CmpOpnd1, CmpOpnd2, 16642 DAG.getTargetConstant(0, dl, MVT::i32)); 16643 } 16644 16645 return SDValue(); 16646 } 16647