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/STLExtras.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/ADT/StringSwitch.h" 36 #include "llvm/CodeGen/CallingConvLower.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstr.h" 42 #include "llvm/CodeGen/MachineInstrBuilder.h" 43 #include "llvm/CodeGen/MachineJumpTableInfo.h" 44 #include "llvm/CodeGen/MachineLoopInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/IntrinsicsPowerPC.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSectionXCOFF.h" 77 #include "llvm/MC/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <optional> 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> EnableQuadwordAtomics( 125 "ppc-quadword-atomics", 126 cl::desc("enable quadword lock-free atomic operations"), cl::init(false), 127 cl::Hidden); 128 129 static cl::opt<bool> 130 DisablePerfectShuffle("ppc-disable-perfect-shuffle", 131 cl::desc("disable vector permute decomposition"), 132 cl::init(true), cl::Hidden); 133 134 cl::opt<bool> DisableAutoPairedVecSt( 135 "disable-auto-paired-vec-st", 136 cl::desc("disable automatically generated 32byte paired vector stores"), 137 cl::init(true), cl::Hidden); 138 139 STATISTIC(NumTailCalls, "Number of tail calls"); 140 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 141 STATISTIC(ShufflesHandledWithVPERM, 142 "Number of shuffles lowered to a VPERM or XXPERM"); 143 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 144 145 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 146 147 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 148 149 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 150 151 // FIXME: Remove this once the bug has been fixed! 152 extern cl::opt<bool> ANDIGlueBug; 153 154 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 155 const PPCSubtarget &STI) 156 : TargetLowering(TM), Subtarget(STI) { 157 // Initialize map that relates the PPC addressing modes to the computed flags 158 // of a load/store instruction. The map is used to determine the optimal 159 // addressing mode when selecting load and stores. 160 initializeAddrModeMap(); 161 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 162 // arguments are at least 4/8 bytes aligned. 163 bool isPPC64 = Subtarget.isPPC64(); 164 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 165 166 // Set up the register classes. 167 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 168 if (!useSoftFloat()) { 169 if (hasSPE()) { 170 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 171 // EFPU2 APU only supports f32 172 if (!Subtarget.hasEFPU2()) 173 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 174 } else { 175 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 176 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 177 } 178 } 179 180 // Match BITREVERSE to customized fast code sequence in the td file. 181 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 182 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 183 184 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 185 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 186 187 // Custom lower inline assembly to check for special registers. 188 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 189 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 190 191 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 192 for (MVT VT : MVT::integer_valuetypes()) { 193 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 194 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 195 } 196 197 if (Subtarget.isISA3_0()) { 198 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 199 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 200 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 201 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 202 } else { 203 // No extending loads from f16 or HW conversions back and forth. 204 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 205 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 206 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 207 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 208 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 209 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 210 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 211 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 212 } 213 214 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 215 216 // PowerPC has pre-inc load and store's. 217 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 218 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 219 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 220 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 221 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 222 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 223 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 224 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 225 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 226 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 227 if (!Subtarget.hasSPE()) { 228 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 229 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 230 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 231 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 232 } 233 234 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 235 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 236 for (MVT VT : ScalarIntVTs) { 237 setOperationAction(ISD::ADDC, VT, Legal); 238 setOperationAction(ISD::ADDE, VT, Legal); 239 setOperationAction(ISD::SUBC, VT, Legal); 240 setOperationAction(ISD::SUBE, VT, Legal); 241 } 242 243 if (Subtarget.useCRBits()) { 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 245 246 if (isPPC64 || Subtarget.hasFPCVT()) { 247 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 248 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 249 isPPC64 ? MVT::i64 : MVT::i32); 250 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 251 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 254 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 255 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 256 isPPC64 ? MVT::i64 : MVT::i32); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 258 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 259 isPPC64 ? MVT::i64 : MVT::i32); 260 261 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 262 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 263 isPPC64 ? MVT::i64 : MVT::i32); 264 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 265 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 266 isPPC64 ? MVT::i64 : MVT::i32); 267 268 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 269 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 270 isPPC64 ? MVT::i64 : MVT::i32); 271 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 272 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 273 isPPC64 ? MVT::i64 : MVT::i32); 274 } else { 275 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 276 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 277 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 278 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 279 } 280 281 // PowerPC does not support direct load/store of condition registers. 282 setOperationAction(ISD::LOAD, MVT::i1, Custom); 283 setOperationAction(ISD::STORE, MVT::i1, Custom); 284 285 // FIXME: Remove this once the ANDI glue bug is fixed: 286 if (ANDIGlueBug) 287 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 288 289 for (MVT VT : MVT::integer_valuetypes()) { 290 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 291 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 292 setTruncStoreAction(VT, MVT::i1, Expand); 293 } 294 295 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 296 } 297 298 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 299 // PPC (the libcall is not available). 300 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 301 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 302 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 303 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 304 305 // We do not currently implement these libm ops for PowerPC. 306 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 307 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 308 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 309 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 310 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 311 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 312 313 // PowerPC has no SREM/UREM instructions unless we are on P9 314 // On P9 we may use a hardware instruction to compute the remainder. 315 // When the result of both the remainder and the division is required it is 316 // more efficient to compute the remainder from the result of the division 317 // rather than use the remainder instruction. The instructions are legalized 318 // directly because the DivRemPairsPass performs the transformation at the IR 319 // level. 320 if (Subtarget.isISA3_0()) { 321 setOperationAction(ISD::SREM, MVT::i32, Legal); 322 setOperationAction(ISD::UREM, MVT::i32, Legal); 323 setOperationAction(ISD::SREM, MVT::i64, Legal); 324 setOperationAction(ISD::UREM, MVT::i64, Legal); 325 } else { 326 setOperationAction(ISD::SREM, MVT::i32, Expand); 327 setOperationAction(ISD::UREM, MVT::i32, Expand); 328 setOperationAction(ISD::SREM, MVT::i64, Expand); 329 setOperationAction(ISD::UREM, MVT::i64, Expand); 330 } 331 332 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 333 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 334 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 335 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 336 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 337 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 338 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 339 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 340 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 341 342 // Handle constrained floating-point operations of scalar. 343 // TODO: Handle SPE specific operation. 344 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 345 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 347 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 348 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 349 350 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 352 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 353 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 354 355 if (!Subtarget.hasSPE()) { 356 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 357 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 358 } 359 360 if (Subtarget.hasVSX()) { 361 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 363 } 364 365 if (Subtarget.hasFSQRT()) { 366 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 367 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 368 } 369 370 if (Subtarget.hasFPRND()) { 371 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 372 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 373 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 374 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 375 376 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 377 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 378 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 379 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 380 } 381 382 // We don't support sin/cos/sqrt/fmod/pow 383 setOperationAction(ISD::FSIN , MVT::f64, Expand); 384 setOperationAction(ISD::FCOS , MVT::f64, Expand); 385 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 386 setOperationAction(ISD::FREM , MVT::f64, Expand); 387 setOperationAction(ISD::FPOW , MVT::f64, Expand); 388 setOperationAction(ISD::FSIN , MVT::f32, Expand); 389 setOperationAction(ISD::FCOS , MVT::f32, Expand); 390 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 391 setOperationAction(ISD::FREM , MVT::f32, Expand); 392 setOperationAction(ISD::FPOW , MVT::f32, Expand); 393 394 // MASS transformation for LLVM intrinsics with replicating fast-math flag 395 // to be consistent to PPCGenScalarMASSEntries pass 396 if (TM.getOptLevel() == CodeGenOpt::Aggressive) { 397 setOperationAction(ISD::FSIN , MVT::f64, Custom); 398 setOperationAction(ISD::FCOS , MVT::f64, Custom); 399 setOperationAction(ISD::FPOW , MVT::f64, Custom); 400 setOperationAction(ISD::FLOG, MVT::f64, Custom); 401 setOperationAction(ISD::FLOG10, MVT::f64, Custom); 402 setOperationAction(ISD::FEXP, MVT::f64, Custom); 403 setOperationAction(ISD::FSIN , MVT::f32, Custom); 404 setOperationAction(ISD::FCOS , MVT::f32, Custom); 405 setOperationAction(ISD::FPOW , MVT::f32, Custom); 406 setOperationAction(ISD::FLOG, MVT::f32, Custom); 407 setOperationAction(ISD::FLOG10, MVT::f32, Custom); 408 setOperationAction(ISD::FEXP, MVT::f32, Custom); 409 } 410 411 if (Subtarget.hasSPE()) { 412 setOperationAction(ISD::FMA , MVT::f64, Expand); 413 setOperationAction(ISD::FMA , MVT::f32, Expand); 414 } else { 415 setOperationAction(ISD::FMA , MVT::f64, Legal); 416 setOperationAction(ISD::FMA , MVT::f32, Legal); 417 } 418 419 if (Subtarget.hasSPE()) 420 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 421 422 setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom); 423 424 // If we're enabling GP optimizations, use hardware square root 425 if (!Subtarget.hasFSQRT() && 426 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 427 Subtarget.hasFRE())) 428 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 429 430 if (!Subtarget.hasFSQRT() && 431 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 432 Subtarget.hasFRES())) 433 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 434 435 if (Subtarget.hasFCPSGN()) { 436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 438 } else { 439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 441 } 442 443 if (Subtarget.hasFPRND()) { 444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 445 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 446 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 447 setOperationAction(ISD::FROUND, MVT::f64, Legal); 448 449 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 450 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 451 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 452 setOperationAction(ISD::FROUND, MVT::f32, Legal); 453 } 454 455 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP 456 // instruction xxbrd to speed up scalar BSWAP64. 457 if (Subtarget.isISA3_1()) { 458 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 459 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 460 } else { 461 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 462 setOperationAction( 463 ISD::BSWAP, MVT::i64, 464 (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand); 465 } 466 467 // CTPOP or CTTZ were introduced in P8/P9 respectively 468 if (Subtarget.isISA3_0()) { 469 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 470 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 471 } else { 472 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 473 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 474 } 475 476 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 477 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 478 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 479 } else { 480 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 481 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 482 } 483 484 // PowerPC does not have ROTR 485 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 486 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 487 488 if (!Subtarget.useCRBits()) { 489 // PowerPC does not have Select 490 setOperationAction(ISD::SELECT, MVT::i32, Expand); 491 setOperationAction(ISD::SELECT, MVT::i64, Expand); 492 setOperationAction(ISD::SELECT, MVT::f32, Expand); 493 setOperationAction(ISD::SELECT, MVT::f64, Expand); 494 } 495 496 // PowerPC wants to turn select_cc of FP into fsel when possible. 497 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 498 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 499 500 // PowerPC wants to optimize integer setcc a bit 501 if (!Subtarget.useCRBits()) 502 setOperationAction(ISD::SETCC, MVT::i32, Custom); 503 504 if (Subtarget.hasFPU()) { 505 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 506 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 507 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 508 509 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 510 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 511 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 512 } 513 514 // PowerPC does not have BRCOND which requires SetCC 515 if (!Subtarget.useCRBits()) 516 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 517 518 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 519 520 if (Subtarget.hasSPE()) { 521 // SPE has built-in conversions 522 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 523 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 524 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 526 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 527 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 528 529 // SPE supports signaling compare of f32/f64. 530 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 531 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 532 } else { 533 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 534 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 535 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 536 537 // PowerPC does not have [U|S]INT_TO_FP 538 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 539 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 540 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 541 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 542 } 543 544 if (Subtarget.hasDirectMove() && isPPC64) { 545 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 546 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 547 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 548 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 549 if (TM.Options.UnsafeFPMath) { 550 setOperationAction(ISD::LRINT, MVT::f64, Legal); 551 setOperationAction(ISD::LRINT, MVT::f32, Legal); 552 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 553 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 554 setOperationAction(ISD::LROUND, MVT::f64, Legal); 555 setOperationAction(ISD::LROUND, MVT::f32, Legal); 556 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 557 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 558 } 559 } else { 560 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 561 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 562 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 563 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 564 } 565 566 // We cannot sextinreg(i1). Expand to shifts. 567 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 568 569 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 570 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 571 // support continuation, user-level threading, and etc.. As a result, no 572 // other SjLj exception interfaces are implemented and please don't build 573 // your own exception handling based on them. 574 // LLVM/Clang supports zero-cost DWARF exception handling. 575 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 576 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 577 578 // We want to legalize GlobalAddress and ConstantPool nodes into the 579 // appropriate instructions to materialize the address. 580 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 581 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 582 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 583 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 584 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 585 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 586 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 587 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 588 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 589 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 590 591 // TRAP is legal. 592 setOperationAction(ISD::TRAP, MVT::Other, Legal); 593 594 // TRAMPOLINE is custom lowered. 595 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 596 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 597 598 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 599 setOperationAction(ISD::VASTART , MVT::Other, Custom); 600 601 if (Subtarget.is64BitELFABI()) { 602 // VAARG always uses double-word chunks, so promote anything smaller. 603 setOperationAction(ISD::VAARG, MVT::i1, Promote); 604 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 605 setOperationAction(ISD::VAARG, MVT::i8, Promote); 606 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 607 setOperationAction(ISD::VAARG, MVT::i16, Promote); 608 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 609 setOperationAction(ISD::VAARG, MVT::i32, Promote); 610 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 611 setOperationAction(ISD::VAARG, MVT::Other, Expand); 612 } else if (Subtarget.is32BitELFABI()) { 613 // VAARG is custom lowered with the 32-bit SVR4 ABI. 614 setOperationAction(ISD::VAARG, MVT::Other, Custom); 615 setOperationAction(ISD::VAARG, MVT::i64, Custom); 616 } else 617 setOperationAction(ISD::VAARG, MVT::Other, Expand); 618 619 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 620 if (Subtarget.is32BitELFABI()) 621 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 622 else 623 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 624 625 // Use the default implementation. 626 setOperationAction(ISD::VAEND , MVT::Other, Expand); 627 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 628 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 629 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 630 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 631 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 632 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 633 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 634 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 635 636 // We want to custom lower some of our intrinsics. 637 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 638 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 639 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 641 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom); 642 643 // To handle counter-based loop conditions. 644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 645 646 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 647 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 648 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 649 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 650 651 // Comparisons that require checking two conditions. 652 if (Subtarget.hasSPE()) { 653 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 654 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 655 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 656 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 657 } 658 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 659 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 660 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 661 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 662 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 663 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 664 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 665 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 666 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 667 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 668 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 669 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 670 671 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 672 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 673 674 if (Subtarget.has64BitSupport()) { 675 // They also have instructions for converting between i64 and fp. 676 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 677 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 678 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 679 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 680 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 681 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 682 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 683 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 684 // This is just the low 32 bits of a (signed) fp->i64 conversion. 685 // We cannot do this with Promote because i64 is not a legal type. 686 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 687 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 688 689 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 690 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 691 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 692 } 693 } else { 694 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 695 if (Subtarget.hasSPE()) { 696 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 697 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 698 } else { 699 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 700 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 701 } 702 } 703 704 // With the instructions enabled under FPCVT, we can do everything. 705 if (Subtarget.hasFPCVT()) { 706 if (Subtarget.has64BitSupport()) { 707 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 708 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 709 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 710 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 711 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 712 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 713 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 714 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 715 } 716 717 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 718 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 719 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 720 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 721 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 722 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 723 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 724 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 725 } 726 727 if (Subtarget.use64BitRegs()) { 728 // 64-bit PowerPC implementations can support i64 types directly 729 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 730 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 731 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 732 // 64-bit PowerPC wants to expand i128 shifts itself. 733 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 734 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 735 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 736 } else { 737 // 32-bit PowerPC wants to expand i64 shifts itself. 738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 741 } 742 743 // PowerPC has better expansions for funnel shifts than the generic 744 // TargetLowering::expandFunnelShift. 745 if (Subtarget.has64BitSupport()) { 746 setOperationAction(ISD::FSHL, MVT::i64, Custom); 747 setOperationAction(ISD::FSHR, MVT::i64, Custom); 748 } 749 setOperationAction(ISD::FSHL, MVT::i32, Custom); 750 setOperationAction(ISD::FSHR, MVT::i32, Custom); 751 752 if (Subtarget.hasVSX()) { 753 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 754 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 755 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 756 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 757 } 758 759 if (Subtarget.hasAltivec()) { 760 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 761 setOperationAction(ISD::SADDSAT, VT, Legal); 762 setOperationAction(ISD::SSUBSAT, VT, Legal); 763 setOperationAction(ISD::UADDSAT, VT, Legal); 764 setOperationAction(ISD::USUBSAT, VT, Legal); 765 } 766 // First set operation action for all vector types to expand. Then we 767 // will selectively turn on ones that can be effectively codegen'd. 768 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 769 // add/sub are legal for all supported vector VT's. 770 setOperationAction(ISD::ADD, VT, Legal); 771 setOperationAction(ISD::SUB, VT, Legal); 772 773 // For v2i64, these are only valid with P8Vector. This is corrected after 774 // the loop. 775 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 776 setOperationAction(ISD::SMAX, VT, Legal); 777 setOperationAction(ISD::SMIN, VT, Legal); 778 setOperationAction(ISD::UMAX, VT, Legal); 779 setOperationAction(ISD::UMIN, VT, Legal); 780 } 781 else { 782 setOperationAction(ISD::SMAX, VT, Expand); 783 setOperationAction(ISD::SMIN, VT, Expand); 784 setOperationAction(ISD::UMAX, VT, Expand); 785 setOperationAction(ISD::UMIN, VT, Expand); 786 } 787 788 if (Subtarget.hasVSX()) { 789 setOperationAction(ISD::FMAXNUM, VT, Legal); 790 setOperationAction(ISD::FMINNUM, VT, Legal); 791 } 792 793 // Vector instructions introduced in P8 794 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 795 setOperationAction(ISD::CTPOP, VT, Legal); 796 setOperationAction(ISD::CTLZ, VT, Legal); 797 } 798 else { 799 setOperationAction(ISD::CTPOP, VT, Expand); 800 setOperationAction(ISD::CTLZ, VT, Expand); 801 } 802 803 // Vector instructions introduced in P9 804 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 805 setOperationAction(ISD::CTTZ, VT, Legal); 806 else 807 setOperationAction(ISD::CTTZ, VT, Expand); 808 809 // We promote all shuffles to v16i8. 810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 811 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 812 813 // We promote all non-typed operations to v4i32. 814 setOperationAction(ISD::AND , VT, Promote); 815 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 816 setOperationAction(ISD::OR , VT, Promote); 817 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 818 setOperationAction(ISD::XOR , VT, Promote); 819 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 820 setOperationAction(ISD::LOAD , VT, Promote); 821 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 822 setOperationAction(ISD::SELECT, VT, Promote); 823 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 824 setOperationAction(ISD::VSELECT, VT, Legal); 825 setOperationAction(ISD::SELECT_CC, VT, Promote); 826 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 827 setOperationAction(ISD::STORE, VT, Promote); 828 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 829 830 // No other operations are legal. 831 setOperationAction(ISD::MUL , VT, Expand); 832 setOperationAction(ISD::SDIV, VT, Expand); 833 setOperationAction(ISD::SREM, VT, Expand); 834 setOperationAction(ISD::UDIV, VT, Expand); 835 setOperationAction(ISD::UREM, VT, Expand); 836 setOperationAction(ISD::FDIV, VT, Expand); 837 setOperationAction(ISD::FREM, VT, Expand); 838 setOperationAction(ISD::FNEG, VT, Expand); 839 setOperationAction(ISD::FSQRT, VT, Expand); 840 setOperationAction(ISD::FLOG, VT, Expand); 841 setOperationAction(ISD::FLOG10, VT, Expand); 842 setOperationAction(ISD::FLOG2, VT, Expand); 843 setOperationAction(ISD::FEXP, VT, Expand); 844 setOperationAction(ISD::FEXP2, VT, Expand); 845 setOperationAction(ISD::FSIN, VT, Expand); 846 setOperationAction(ISD::FCOS, VT, Expand); 847 setOperationAction(ISD::FABS, VT, Expand); 848 setOperationAction(ISD::FFLOOR, VT, Expand); 849 setOperationAction(ISD::FCEIL, VT, Expand); 850 setOperationAction(ISD::FTRUNC, VT, Expand); 851 setOperationAction(ISD::FRINT, VT, Expand); 852 setOperationAction(ISD::FNEARBYINT, VT, Expand); 853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 854 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 855 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 856 setOperationAction(ISD::MULHU, VT, Expand); 857 setOperationAction(ISD::MULHS, VT, Expand); 858 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 859 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 860 setOperationAction(ISD::UDIVREM, VT, Expand); 861 setOperationAction(ISD::SDIVREM, VT, Expand); 862 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 863 setOperationAction(ISD::FPOW, VT, Expand); 864 setOperationAction(ISD::BSWAP, VT, Expand); 865 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 866 setOperationAction(ISD::ROTL, VT, Expand); 867 setOperationAction(ISD::ROTR, VT, Expand); 868 869 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 870 setTruncStoreAction(VT, InnerVT, Expand); 871 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 872 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 873 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 874 } 875 } 876 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 877 if (!Subtarget.hasP8Vector()) { 878 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 879 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 880 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 881 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 882 } 883 884 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 885 // with merges, splats, etc. 886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 887 888 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 889 // are cheap, so handle them before they get expanded to scalar. 890 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 891 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 892 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 893 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 894 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 895 896 setOperationAction(ISD::AND , MVT::v4i32, Legal); 897 setOperationAction(ISD::OR , MVT::v4i32, Legal); 898 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 899 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 900 setOperationAction(ISD::SELECT, MVT::v4i32, 901 Subtarget.useCRBits() ? Legal : Expand); 902 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 903 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 904 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 905 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 906 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 908 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 911 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 912 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 913 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 914 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 915 916 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 917 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 918 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 919 if (Subtarget.hasAltivec()) 920 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 921 setOperationAction(ISD::ROTL, VT, Legal); 922 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 923 if (Subtarget.hasP8Altivec()) 924 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 925 926 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 927 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 928 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 929 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 930 931 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 932 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 933 934 if (Subtarget.hasVSX()) { 935 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 936 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 938 } 939 940 if (Subtarget.hasP8Altivec()) 941 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 942 else 943 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 944 945 if (Subtarget.isISA3_1()) { 946 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 947 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 948 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 949 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 950 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 951 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 952 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 953 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 954 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 955 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 956 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 957 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 958 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 959 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 960 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 961 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 962 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 963 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 964 } 965 966 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 967 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 968 969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 970 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 971 972 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 973 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 974 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 975 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 976 977 // Altivec does not contain unordered floating-point compare instructions 978 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 979 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 980 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 981 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 982 983 if (Subtarget.hasVSX()) { 984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 985 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 986 if (Subtarget.hasP8Vector()) { 987 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 989 } 990 if (Subtarget.hasDirectMove() && isPPC64) { 991 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 992 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 993 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 999 } 1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 1001 1002 // The nearbyint variants are not allowed to raise the inexact exception 1003 // so we can only code-gen them with unsafe math. 1004 if (TM.Options.UnsafeFPMath) { 1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1007 } 1008 1009 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 1010 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 1011 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 1012 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 1013 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 1014 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 1015 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1016 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1017 1018 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1021 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1022 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1023 1024 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 1025 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1026 1027 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 1028 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 1029 1030 // Share the Altivec comparison restrictions. 1031 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 1032 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 1033 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 1034 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 1035 1036 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1037 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1038 1039 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 1040 1041 if (Subtarget.hasP8Vector()) 1042 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1043 1044 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1045 1046 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1047 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1048 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1049 1050 if (Subtarget.hasP8Altivec()) { 1051 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1052 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1053 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1054 1055 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1056 // SRL, but not for SRA because of the instructions available: 1057 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1058 // doing 1059 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1060 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1061 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1062 1063 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1064 } 1065 else { 1066 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1067 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1068 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1069 1070 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1071 1072 // VSX v2i64 only supports non-arithmetic operations. 1073 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1074 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1075 } 1076 1077 if (Subtarget.isISA3_1()) 1078 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1079 else 1080 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1081 1082 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1083 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1084 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1085 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1086 1087 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 1088 1089 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1090 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1091 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1092 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1093 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1094 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1095 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1096 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1097 1098 // Custom handling for partial vectors of integers converted to 1099 // floating point. We already have optimal handling for v2i32 through 1100 // the DAG combine, so those aren't necessary. 1101 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1102 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1103 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1104 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1105 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1106 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1107 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1108 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1109 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1110 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1111 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1112 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1113 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1114 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1115 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1116 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1117 1118 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1119 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1120 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1121 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1122 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1123 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1124 1125 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1126 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1127 1128 // Handle constrained floating-point operations of vector. 1129 // The predictor is `hasVSX` because altivec instruction has 1130 // no exception but VSX vector instruction has. 1131 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1132 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1133 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1134 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1135 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1136 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1137 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1138 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1139 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1140 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1141 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1142 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1143 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1144 1145 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1146 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1147 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1148 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1149 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1150 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1151 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1152 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1153 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1154 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1155 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1156 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1157 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1158 1159 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1160 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1161 1162 for (MVT FPT : MVT::fp_valuetypes()) 1163 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1164 1165 // Expand the SELECT to SELECT_CC 1166 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1167 1168 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1169 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1170 1171 // No implementation for these ops for PowerPC. 1172 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1173 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1174 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1175 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1176 setOperationAction(ISD::FREM, MVT::f128, Expand); 1177 } 1178 1179 if (Subtarget.hasP8Altivec()) { 1180 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1181 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1182 } 1183 1184 if (Subtarget.hasP9Vector()) { 1185 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1186 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1187 1188 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1189 // SRL, but not for SRA because of the instructions available: 1190 // VS{RL} and VS{RL}O. 1191 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1192 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1193 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1194 1195 setOperationAction(ISD::FADD, MVT::f128, Legal); 1196 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1197 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1198 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1199 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1200 1201 setOperationAction(ISD::FMA, MVT::f128, Legal); 1202 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1203 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1204 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1205 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1206 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1207 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1208 1209 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1210 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1211 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1212 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1213 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1214 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1215 1216 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1217 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1218 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1219 1220 // Handle constrained floating-point operations of fp128 1221 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1222 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1223 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1224 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1225 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1226 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1227 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1228 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1229 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1230 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1231 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1232 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1233 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1234 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1235 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1236 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1237 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1238 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1239 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1240 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1241 } else if (Subtarget.hasVSX()) { 1242 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1243 setOperationAction(ISD::STORE, MVT::f128, Promote); 1244 1245 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1246 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1247 1248 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1249 // fp_to_uint and int_to_fp. 1250 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1251 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1252 1253 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1254 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1255 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1256 setOperationAction(ISD::FABS, MVT::f128, Expand); 1257 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1258 setOperationAction(ISD::FMA, MVT::f128, Expand); 1259 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1260 1261 // Expand the fp_extend if the target type is fp128. 1262 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1263 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1264 1265 // Expand the fp_round if the source type is fp128. 1266 for (MVT VT : {MVT::f32, MVT::f64}) { 1267 setOperationAction(ISD::FP_ROUND, VT, Custom); 1268 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1269 } 1270 1271 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1272 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1273 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1274 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1275 1276 // Lower following f128 select_cc pattern: 1277 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1278 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1279 1280 // We need to handle f128 SELECT_CC with integer result type. 1281 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1282 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1283 } 1284 1285 if (Subtarget.hasP9Altivec()) { 1286 if (Subtarget.isISA3_1()) { 1287 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1288 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1289 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1290 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1291 } else { 1292 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1293 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1294 } 1295 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1297 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1298 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1300 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1301 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1302 1303 setOperationAction(ISD::ABDU, MVT::v16i8, Legal); 1304 setOperationAction(ISD::ABDU, MVT::v8i16, Legal); 1305 setOperationAction(ISD::ABDU, MVT::v4i32, Legal); 1306 setOperationAction(ISD::ABDS, MVT::v4i32, Legal); 1307 } 1308 1309 if (Subtarget.hasP10Vector()) { 1310 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1311 } 1312 } 1313 1314 if (Subtarget.pairedVectorMemops()) { 1315 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1316 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1317 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1318 } 1319 if (Subtarget.hasMMA()) { 1320 if (Subtarget.isISAFuture()) 1321 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass); 1322 else 1323 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1324 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1325 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1326 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1327 } 1328 1329 if (Subtarget.has64BitSupport()) 1330 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1331 1332 if (Subtarget.isISA3_1()) 1333 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1334 1335 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1336 1337 if (!isPPC64) { 1338 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1339 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1340 } 1341 1342 if (shouldInlineQuadwordAtomics()) { 1343 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1344 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1345 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1346 } 1347 1348 setBooleanContents(ZeroOrOneBooleanContent); 1349 1350 if (Subtarget.hasAltivec()) { 1351 // Altivec instructions set fields to all zeros or all ones. 1352 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1353 } 1354 1355 setLibcallName(RTLIB::MULO_I128, nullptr); 1356 if (!isPPC64) { 1357 // These libcalls are not available in 32-bit. 1358 setLibcallName(RTLIB::SHL_I128, nullptr); 1359 setLibcallName(RTLIB::SRL_I128, nullptr); 1360 setLibcallName(RTLIB::SRA_I128, nullptr); 1361 setLibcallName(RTLIB::MUL_I128, nullptr); 1362 setLibcallName(RTLIB::MULO_I64, nullptr); 1363 } 1364 1365 if (!isPPC64) 1366 setMaxAtomicSizeInBitsSupported(32); 1367 else if (shouldInlineQuadwordAtomics()) 1368 setMaxAtomicSizeInBitsSupported(128); 1369 else 1370 setMaxAtomicSizeInBitsSupported(64); 1371 1372 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1373 1374 // We have target-specific dag combine patterns for the following nodes: 1375 setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL, 1376 ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR}); 1377 if (Subtarget.hasFPCVT()) 1378 setTargetDAGCombine(ISD::UINT_TO_FP); 1379 setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC}); 1380 if (Subtarget.useCRBits()) 1381 setTargetDAGCombine(ISD::BRCOND); 1382 setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN, 1383 ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}); 1384 1385 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND}); 1386 1387 setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE}); 1388 1389 if (Subtarget.useCRBits()) { 1390 setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC}); 1391 } 1392 1393 if (Subtarget.hasP9Altivec()) { 1394 setTargetDAGCombine({ISD::VSELECT}); 1395 } 1396 1397 setLibcallName(RTLIB::LOG_F128, "logf128"); 1398 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1399 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1400 setLibcallName(RTLIB::EXP_F128, "expf128"); 1401 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1402 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1403 setLibcallName(RTLIB::COS_F128, "cosf128"); 1404 setLibcallName(RTLIB::POW_F128, "powf128"); 1405 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1406 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1407 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1408 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1409 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1410 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1411 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1412 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1413 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1414 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1415 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1416 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1417 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1418 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1419 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1420 1421 // With 32 condition bits, we don't need to sink (and duplicate) compares 1422 // aggressively in CodeGenPrep. 1423 if (Subtarget.useCRBits()) { 1424 setHasMultipleConditionRegisters(); 1425 setJumpIsExpensive(); 1426 } 1427 1428 setMinFunctionAlignment(Align(4)); 1429 1430 switch (Subtarget.getCPUDirective()) { 1431 default: break; 1432 case PPC::DIR_970: 1433 case PPC::DIR_A2: 1434 case PPC::DIR_E500: 1435 case PPC::DIR_E500mc: 1436 case PPC::DIR_E5500: 1437 case PPC::DIR_PWR4: 1438 case PPC::DIR_PWR5: 1439 case PPC::DIR_PWR5X: 1440 case PPC::DIR_PWR6: 1441 case PPC::DIR_PWR6X: 1442 case PPC::DIR_PWR7: 1443 case PPC::DIR_PWR8: 1444 case PPC::DIR_PWR9: 1445 case PPC::DIR_PWR10: 1446 case PPC::DIR_PWR_FUTURE: 1447 setPrefLoopAlignment(Align(16)); 1448 setPrefFunctionAlignment(Align(16)); 1449 break; 1450 } 1451 1452 if (Subtarget.enableMachineScheduler()) 1453 setSchedulingPreference(Sched::Source); 1454 else 1455 setSchedulingPreference(Sched::Hybrid); 1456 1457 computeRegisterProperties(STI.getRegisterInfo()); 1458 1459 // The Freescale cores do better with aggressive inlining of memcpy and 1460 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1461 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1462 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1463 MaxStoresPerMemset = 32; 1464 MaxStoresPerMemsetOptSize = 16; 1465 MaxStoresPerMemcpy = 32; 1466 MaxStoresPerMemcpyOptSize = 8; 1467 MaxStoresPerMemmove = 32; 1468 MaxStoresPerMemmoveOptSize = 8; 1469 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1470 // The A2 also benefits from (very) aggressive inlining of memcpy and 1471 // friends. The overhead of a the function call, even when warm, can be 1472 // over one hundred cycles. 1473 MaxStoresPerMemset = 128; 1474 MaxStoresPerMemcpy = 128; 1475 MaxStoresPerMemmove = 128; 1476 MaxLoadsPerMemcmp = 128; 1477 } else { 1478 MaxLoadsPerMemcmp = 8; 1479 MaxLoadsPerMemcmpOptSize = 4; 1480 } 1481 1482 IsStrictFPEnabled = true; 1483 1484 // Let the subtarget (CPU) decide if a predictable select is more expensive 1485 // than the corresponding branch. This information is used in CGP to decide 1486 // when to convert selects into branches. 1487 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1488 } 1489 1490 // *********************************** NOTE ************************************ 1491 // For selecting load and store instructions, the addressing modes are defined 1492 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1493 // patterns to match the load the store instructions. 1494 // 1495 // The TD definitions for the addressing modes correspond to their respective 1496 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1497 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1498 // address mode flags of a particular node. Afterwards, the computed address 1499 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1500 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1501 // accordingly, based on the preferred addressing mode. 1502 // 1503 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1504 // MemOpFlags contains all the possible flags that can be used to compute the 1505 // optimal addressing mode for load and store instructions. 1506 // AddrMode contains all the possible load and store addressing modes available 1507 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1508 // 1509 // When adding new load and store instructions, it is possible that new address 1510 // flags may need to be added into MemOpFlags, and a new addressing mode will 1511 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1512 // of the minimal and main distinguishing address flags for the new load/store 1513 // instructions) will need to be added into initializeAddrModeMap() below. 1514 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1515 // need to be updated to account for selecting the optimal addressing mode. 1516 // ***************************************************************************** 1517 /// Initialize the map that relates the different addressing modes of the load 1518 /// and store instructions to a set of flags. This ensures the load/store 1519 /// instruction is correctly matched during instruction selection. 1520 void PPCTargetLowering::initializeAddrModeMap() { 1521 AddrModesMap[PPC::AM_DForm] = { 1522 // LWZ, STW 1523 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1524 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1525 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1526 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1527 // LBZ, LHZ, STB, STH 1528 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1529 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1530 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1531 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1532 // LHA 1533 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1534 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1535 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1536 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1537 // LFS, LFD, STFS, STFD 1538 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1539 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1540 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1541 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1542 }; 1543 AddrModesMap[PPC::AM_DSForm] = { 1544 // LWA 1545 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1546 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1547 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1548 // LD, STD 1549 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1550 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1551 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1552 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1553 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1554 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1555 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1556 }; 1557 AddrModesMap[PPC::AM_DQForm] = { 1558 // LXV, STXV 1559 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1560 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1561 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1562 }; 1563 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 | 1564 PPC::MOF_SubtargetP10}; 1565 // TODO: Add mapping for quadword load/store. 1566 } 1567 1568 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1569 /// the desired ByVal argument alignment. 1570 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1571 if (MaxAlign == MaxMaxAlign) 1572 return; 1573 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1574 if (MaxMaxAlign >= 32 && 1575 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256) 1576 MaxAlign = Align(32); 1577 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 && 1578 MaxAlign < 16) 1579 MaxAlign = Align(16); 1580 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1581 Align EltAlign; 1582 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1583 if (EltAlign > MaxAlign) 1584 MaxAlign = EltAlign; 1585 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1586 for (auto *EltTy : STy->elements()) { 1587 Align EltAlign; 1588 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1589 if (EltAlign > MaxAlign) 1590 MaxAlign = EltAlign; 1591 if (MaxAlign == MaxMaxAlign) 1592 break; 1593 } 1594 } 1595 } 1596 1597 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1598 /// function arguments in the caller parameter area. 1599 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1600 const DataLayout &DL) const { 1601 // 16byte and wider vectors are passed on 16byte boundary. 1602 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1603 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1604 if (Subtarget.hasAltivec()) 1605 getMaxByValAlign(Ty, Alignment, Align(16)); 1606 return Alignment.value(); 1607 } 1608 1609 bool PPCTargetLowering::useSoftFloat() const { 1610 return Subtarget.useSoftFloat(); 1611 } 1612 1613 bool PPCTargetLowering::hasSPE() const { 1614 return Subtarget.hasSPE(); 1615 } 1616 1617 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1618 return VT.isScalarInteger(); 1619 } 1620 1621 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1622 switch ((PPCISD::NodeType)Opcode) { 1623 case PPCISD::FIRST_NUMBER: break; 1624 case PPCISD::FSEL: return "PPCISD::FSEL"; 1625 case PPCISD::XSMAXC: return "PPCISD::XSMAXC"; 1626 case PPCISD::XSMINC: return "PPCISD::XSMINC"; 1627 case PPCISD::FCFID: return "PPCISD::FCFID"; 1628 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1629 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1630 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1631 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1632 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1633 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1634 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1635 case PPCISD::FP_TO_UINT_IN_VSR: 1636 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1637 case PPCISD::FP_TO_SINT_IN_VSR: 1638 return "PPCISD::FP_TO_SINT_IN_VSR"; 1639 case PPCISD::FRE: return "PPCISD::FRE"; 1640 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1641 case PPCISD::FTSQRT: 1642 return "PPCISD::FTSQRT"; 1643 case PPCISD::FSQRT: 1644 return "PPCISD::FSQRT"; 1645 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1646 case PPCISD::VPERM: return "PPCISD::VPERM"; 1647 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1648 case PPCISD::XXSPLTI_SP_TO_DP: 1649 return "PPCISD::XXSPLTI_SP_TO_DP"; 1650 case PPCISD::XXSPLTI32DX: 1651 return "PPCISD::XXSPLTI32DX"; 1652 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1653 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1654 case PPCISD::XXPERM: 1655 return "PPCISD::XXPERM"; 1656 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1657 case PPCISD::CMPB: return "PPCISD::CMPB"; 1658 case PPCISD::Hi: return "PPCISD::Hi"; 1659 case PPCISD::Lo: return "PPCISD::Lo"; 1660 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1661 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1662 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1663 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1664 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1665 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1666 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1667 case PPCISD::SRL: return "PPCISD::SRL"; 1668 case PPCISD::SRA: return "PPCISD::SRA"; 1669 case PPCISD::SHL: return "PPCISD::SHL"; 1670 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1671 case PPCISD::CALL: return "PPCISD::CALL"; 1672 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1673 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1674 case PPCISD::CALL_RM: 1675 return "PPCISD::CALL_RM"; 1676 case PPCISD::CALL_NOP_RM: 1677 return "PPCISD::CALL_NOP_RM"; 1678 case PPCISD::CALL_NOTOC_RM: 1679 return "PPCISD::CALL_NOTOC_RM"; 1680 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1681 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1682 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1683 case PPCISD::BCTRL_RM: 1684 return "PPCISD::BCTRL_RM"; 1685 case PPCISD::BCTRL_LOAD_TOC_RM: 1686 return "PPCISD::BCTRL_LOAD_TOC_RM"; 1687 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1688 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1689 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1690 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1691 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1692 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1693 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1694 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1695 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1696 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1697 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1698 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1699 case PPCISD::ANDI_rec_1_EQ_BIT: 1700 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1701 case PPCISD::ANDI_rec_1_GT_BIT: 1702 return "PPCISD::ANDI_rec_1_GT_BIT"; 1703 case PPCISD::VCMP: return "PPCISD::VCMP"; 1704 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1705 case PPCISD::LBRX: return "PPCISD::LBRX"; 1706 case PPCISD::STBRX: return "PPCISD::STBRX"; 1707 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1708 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1709 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1710 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1711 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1712 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1713 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1714 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1715 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1716 case PPCISD::ST_VSR_SCAL_INT: 1717 return "PPCISD::ST_VSR_SCAL_INT"; 1718 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1719 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1720 case PPCISD::BDZ: return "PPCISD::BDZ"; 1721 case PPCISD::MFFS: return "PPCISD::MFFS"; 1722 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1723 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1724 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1725 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1726 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1727 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1728 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1729 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1730 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1731 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1732 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1733 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1734 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1735 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1736 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1737 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1738 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1739 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1740 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1741 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1742 case PPCISD::PADDI_DTPREL: 1743 return "PPCISD::PADDI_DTPREL"; 1744 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1745 case PPCISD::SC: return "PPCISD::SC"; 1746 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1747 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1748 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1749 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1750 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1751 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1752 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1753 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1754 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1755 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1756 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1757 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1758 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1759 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1760 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1761 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1762 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1763 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1764 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1765 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1766 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1767 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT"; 1768 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT"; 1769 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1770 case PPCISD::STRICT_FADDRTZ: 1771 return "PPCISD::STRICT_FADDRTZ"; 1772 case PPCISD::STRICT_FCTIDZ: 1773 return "PPCISD::STRICT_FCTIDZ"; 1774 case PPCISD::STRICT_FCTIWZ: 1775 return "PPCISD::STRICT_FCTIWZ"; 1776 case PPCISD::STRICT_FCTIDUZ: 1777 return "PPCISD::STRICT_FCTIDUZ"; 1778 case PPCISD::STRICT_FCTIWUZ: 1779 return "PPCISD::STRICT_FCTIWUZ"; 1780 case PPCISD::STRICT_FCFID: 1781 return "PPCISD::STRICT_FCFID"; 1782 case PPCISD::STRICT_FCFIDU: 1783 return "PPCISD::STRICT_FCFIDU"; 1784 case PPCISD::STRICT_FCFIDS: 1785 return "PPCISD::STRICT_FCFIDS"; 1786 case PPCISD::STRICT_FCFIDUS: 1787 return "PPCISD::STRICT_FCFIDUS"; 1788 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1789 case PPCISD::STORE_COND: 1790 return "PPCISD::STORE_COND"; 1791 } 1792 return nullptr; 1793 } 1794 1795 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1796 EVT VT) const { 1797 if (!VT.isVector()) 1798 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1799 1800 return VT.changeVectorElementTypeToInteger(); 1801 } 1802 1803 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1804 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1805 return true; 1806 } 1807 1808 //===----------------------------------------------------------------------===// 1809 // Node matching predicates, for use by the tblgen matching code. 1810 //===----------------------------------------------------------------------===// 1811 1812 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1813 static bool isFloatingPointZero(SDValue Op) { 1814 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1815 return CFP->getValueAPF().isZero(); 1816 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1817 // Maybe this has already been legalized into the constant pool? 1818 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1819 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1820 return CFP->getValueAPF().isZero(); 1821 } 1822 return false; 1823 } 1824 1825 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1826 /// true if Op is undef or if it matches the specified value. 1827 static bool isConstantOrUndef(int Op, int Val) { 1828 return Op < 0 || Op == Val; 1829 } 1830 1831 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1832 /// VPKUHUM instruction. 1833 /// The ShuffleKind distinguishes between big-endian operations with 1834 /// two different inputs (0), either-endian operations with two identical 1835 /// inputs (1), and little-endian operations with two different inputs (2). 1836 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1837 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1838 SelectionDAG &DAG) { 1839 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1840 if (ShuffleKind == 0) { 1841 if (IsLE) 1842 return false; 1843 for (unsigned i = 0; i != 16; ++i) 1844 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1845 return false; 1846 } else if (ShuffleKind == 2) { 1847 if (!IsLE) 1848 return false; 1849 for (unsigned i = 0; i != 16; ++i) 1850 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1851 return false; 1852 } else if (ShuffleKind == 1) { 1853 unsigned j = IsLE ? 0 : 1; 1854 for (unsigned i = 0; i != 8; ++i) 1855 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1856 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1857 return false; 1858 } 1859 return true; 1860 } 1861 1862 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1863 /// VPKUWUM instruction. 1864 /// The ShuffleKind distinguishes between big-endian operations with 1865 /// two different inputs (0), either-endian operations with two identical 1866 /// inputs (1), and little-endian operations with two different inputs (2). 1867 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1868 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1869 SelectionDAG &DAG) { 1870 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1871 if (ShuffleKind == 0) { 1872 if (IsLE) 1873 return false; 1874 for (unsigned i = 0; i != 16; i += 2) 1875 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1876 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1877 return false; 1878 } else if (ShuffleKind == 2) { 1879 if (!IsLE) 1880 return false; 1881 for (unsigned i = 0; i != 16; i += 2) 1882 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1883 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1884 return false; 1885 } else if (ShuffleKind == 1) { 1886 unsigned j = IsLE ? 0 : 2; 1887 for (unsigned i = 0; i != 8; i += 2) 1888 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1889 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1890 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1891 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1892 return false; 1893 } 1894 return true; 1895 } 1896 1897 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1898 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1899 /// current subtarget. 1900 /// 1901 /// The ShuffleKind distinguishes between big-endian operations with 1902 /// two different inputs (0), either-endian operations with two identical 1903 /// inputs (1), and little-endian operations with two different inputs (2). 1904 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1905 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1906 SelectionDAG &DAG) { 1907 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 1908 if (!Subtarget.hasP8Vector()) 1909 return false; 1910 1911 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1912 if (ShuffleKind == 0) { 1913 if (IsLE) 1914 return false; 1915 for (unsigned i = 0; i != 16; i += 4) 1916 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1917 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1918 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1919 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1920 return false; 1921 } else if (ShuffleKind == 2) { 1922 if (!IsLE) 1923 return false; 1924 for (unsigned i = 0; i != 16; i += 4) 1925 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1926 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1927 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1928 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1929 return false; 1930 } else if (ShuffleKind == 1) { 1931 unsigned j = IsLE ? 0 : 4; 1932 for (unsigned i = 0; i != 8; i += 4) 1933 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1934 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1935 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1936 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1937 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1938 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1939 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1940 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1941 return false; 1942 } 1943 return true; 1944 } 1945 1946 /// isVMerge - Common function, used to match vmrg* shuffles. 1947 /// 1948 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1949 unsigned LHSStart, unsigned RHSStart) { 1950 if (N->getValueType(0) != MVT::v16i8) 1951 return false; 1952 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1953 "Unsupported merge size!"); 1954 1955 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1956 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1957 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1958 LHSStart+j+i*UnitSize) || 1959 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1960 RHSStart+j+i*UnitSize)) 1961 return false; 1962 } 1963 return true; 1964 } 1965 1966 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1967 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1968 /// The ShuffleKind distinguishes between big-endian merges with two 1969 /// different inputs (0), either-endian merges with two identical inputs (1), 1970 /// and little-endian merges with two different inputs (2). For the latter, 1971 /// the input operands are swapped (see PPCInstrAltivec.td). 1972 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1973 unsigned ShuffleKind, SelectionDAG &DAG) { 1974 if (DAG.getDataLayout().isLittleEndian()) { 1975 if (ShuffleKind == 1) // unary 1976 return isVMerge(N, UnitSize, 0, 0); 1977 else if (ShuffleKind == 2) // swapped 1978 return isVMerge(N, UnitSize, 0, 16); 1979 else 1980 return false; 1981 } else { 1982 if (ShuffleKind == 1) // unary 1983 return isVMerge(N, UnitSize, 8, 8); 1984 else if (ShuffleKind == 0) // normal 1985 return isVMerge(N, UnitSize, 8, 24); 1986 else 1987 return false; 1988 } 1989 } 1990 1991 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1992 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1993 /// The ShuffleKind distinguishes between big-endian merges with two 1994 /// different inputs (0), either-endian merges with two identical inputs (1), 1995 /// and little-endian merges with two different inputs (2). For the latter, 1996 /// the input operands are swapped (see PPCInstrAltivec.td). 1997 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1998 unsigned ShuffleKind, SelectionDAG &DAG) { 1999 if (DAG.getDataLayout().isLittleEndian()) { 2000 if (ShuffleKind == 1) // unary 2001 return isVMerge(N, UnitSize, 8, 8); 2002 else if (ShuffleKind == 2) // swapped 2003 return isVMerge(N, UnitSize, 8, 24); 2004 else 2005 return false; 2006 } else { 2007 if (ShuffleKind == 1) // unary 2008 return isVMerge(N, UnitSize, 0, 0); 2009 else if (ShuffleKind == 0) // normal 2010 return isVMerge(N, UnitSize, 0, 16); 2011 else 2012 return false; 2013 } 2014 } 2015 2016 /** 2017 * Common function used to match vmrgew and vmrgow shuffles 2018 * 2019 * The indexOffset determines whether to look for even or odd words in 2020 * the shuffle mask. This is based on the of the endianness of the target 2021 * machine. 2022 * - Little Endian: 2023 * - Use offset of 0 to check for odd elements 2024 * - Use offset of 4 to check for even elements 2025 * - Big Endian: 2026 * - Use offset of 0 to check for even elements 2027 * - Use offset of 4 to check for odd elements 2028 * A detailed description of the vector element ordering for little endian and 2029 * big endian can be found at 2030 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 2031 * Targeting your applications - what little endian and big endian IBM XL C/C++ 2032 * compiler differences mean to you 2033 * 2034 * The mask to the shuffle vector instruction specifies the indices of the 2035 * elements from the two input vectors to place in the result. The elements are 2036 * numbered in array-access order, starting with the first vector. These vectors 2037 * are always of type v16i8, thus each vector will contain 16 elements of size 2038 * 8. More info on the shuffle vector can be found in the 2039 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2040 * Language Reference. 2041 * 2042 * The RHSStartValue indicates whether the same input vectors are used (unary) 2043 * or two different input vectors are used, based on the following: 2044 * - If the instruction uses the same vector for both inputs, the range of the 2045 * indices will be 0 to 15. In this case, the RHSStart value passed should 2046 * be 0. 2047 * - If the instruction has two different vectors then the range of the 2048 * indices will be 0 to 31. In this case, the RHSStart value passed should 2049 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2050 * to 31 specify elements in the second vector). 2051 * 2052 * \param[in] N The shuffle vector SD Node to analyze 2053 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2054 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2055 * vector to the shuffle_vector instruction 2056 * \return true iff this shuffle vector represents an even or odd word merge 2057 */ 2058 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2059 unsigned RHSStartValue) { 2060 if (N->getValueType(0) != MVT::v16i8) 2061 return false; 2062 2063 for (unsigned i = 0; i < 2; ++i) 2064 for (unsigned j = 0; j < 4; ++j) 2065 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2066 i*RHSStartValue+j+IndexOffset) || 2067 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2068 i*RHSStartValue+j+IndexOffset+8)) 2069 return false; 2070 return true; 2071 } 2072 2073 /** 2074 * Determine if the specified shuffle mask is suitable for the vmrgew or 2075 * vmrgow instructions. 2076 * 2077 * \param[in] N The shuffle vector SD Node to analyze 2078 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2079 * \param[in] ShuffleKind Identify the type of merge: 2080 * - 0 = big-endian merge with two different inputs; 2081 * - 1 = either-endian merge with two identical inputs; 2082 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2083 * little-endian merges). 2084 * \param[in] DAG The current SelectionDAG 2085 * \return true iff this shuffle mask 2086 */ 2087 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2088 unsigned ShuffleKind, SelectionDAG &DAG) { 2089 if (DAG.getDataLayout().isLittleEndian()) { 2090 unsigned indexOffset = CheckEven ? 4 : 0; 2091 if (ShuffleKind == 1) // Unary 2092 return isVMerge(N, indexOffset, 0); 2093 else if (ShuffleKind == 2) // swapped 2094 return isVMerge(N, indexOffset, 16); 2095 else 2096 return false; 2097 } 2098 else { 2099 unsigned indexOffset = CheckEven ? 0 : 4; 2100 if (ShuffleKind == 1) // Unary 2101 return isVMerge(N, indexOffset, 0); 2102 else if (ShuffleKind == 0) // Normal 2103 return isVMerge(N, indexOffset, 16); 2104 else 2105 return false; 2106 } 2107 return false; 2108 } 2109 2110 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2111 /// amount, otherwise return -1. 2112 /// The ShuffleKind distinguishes between big-endian operations with two 2113 /// different inputs (0), either-endian operations with two identical inputs 2114 /// (1), and little-endian operations with two different inputs (2). For the 2115 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2116 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2117 SelectionDAG &DAG) { 2118 if (N->getValueType(0) != MVT::v16i8) 2119 return -1; 2120 2121 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2122 2123 // Find the first non-undef value in the shuffle mask. 2124 unsigned i; 2125 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2126 /*search*/; 2127 2128 if (i == 16) return -1; // all undef. 2129 2130 // Otherwise, check to see if the rest of the elements are consecutively 2131 // numbered from this value. 2132 unsigned ShiftAmt = SVOp->getMaskElt(i); 2133 if (ShiftAmt < i) return -1; 2134 2135 ShiftAmt -= i; 2136 bool isLE = DAG.getDataLayout().isLittleEndian(); 2137 2138 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2139 // Check the rest of the elements to see if they are consecutive. 2140 for (++i; i != 16; ++i) 2141 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2142 return -1; 2143 } else if (ShuffleKind == 1) { 2144 // Check the rest of the elements to see if they are consecutive. 2145 for (++i; i != 16; ++i) 2146 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2147 return -1; 2148 } else 2149 return -1; 2150 2151 if (isLE) 2152 ShiftAmt = 16 - ShiftAmt; 2153 2154 return ShiftAmt; 2155 } 2156 2157 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2158 /// specifies a splat of a single element that is suitable for input to 2159 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2160 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2161 EVT VT = N->getValueType(0); 2162 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2163 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1); 2164 2165 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) && 2166 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2167 2168 // The consecutive indices need to specify an element, not part of two 2169 // different elements. So abandon ship early if this isn't the case. 2170 if (N->getMaskElt(0) % EltSize != 0) 2171 return false; 2172 2173 // This is a splat operation if each element of the permute is the same, and 2174 // if the value doesn't reference the second vector. 2175 unsigned ElementBase = N->getMaskElt(0); 2176 2177 // FIXME: Handle UNDEF elements too! 2178 if (ElementBase >= 16) 2179 return false; 2180 2181 // Check that the indices are consecutive, in the case of a multi-byte element 2182 // splatted with a v16i8 mask. 2183 for (unsigned i = 1; i != EltSize; ++i) 2184 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2185 return false; 2186 2187 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2188 if (N->getMaskElt(i) < 0) continue; 2189 for (unsigned j = 0; j != EltSize; ++j) 2190 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2191 return false; 2192 } 2193 return true; 2194 } 2195 2196 /// Check that the mask is shuffling N byte elements. Within each N byte 2197 /// element of the mask, the indices could be either in increasing or 2198 /// decreasing order as long as they are consecutive. 2199 /// \param[in] N the shuffle vector SD Node to analyze 2200 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2201 /// Word/DoubleWord/QuadWord). 2202 /// \param[in] StepLen the delta indices number among the N byte element, if 2203 /// the mask is in increasing/decreasing order then it is 1/-1. 2204 /// \return true iff the mask is shuffling N byte elements. 2205 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2206 int StepLen) { 2207 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2208 "Unexpected element width."); 2209 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2210 2211 unsigned NumOfElem = 16 / Width; 2212 unsigned MaskVal[16]; // Width is never greater than 16 2213 for (unsigned i = 0; i < NumOfElem; ++i) { 2214 MaskVal[0] = N->getMaskElt(i * Width); 2215 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2216 return false; 2217 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2218 return false; 2219 } 2220 2221 for (unsigned int j = 1; j < Width; ++j) { 2222 MaskVal[j] = N->getMaskElt(i * Width + j); 2223 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2224 return false; 2225 } 2226 } 2227 } 2228 2229 return true; 2230 } 2231 2232 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2233 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2234 if (!isNByteElemShuffleMask(N, 4, 1)) 2235 return false; 2236 2237 // Now we look at mask elements 0,4,8,12 2238 unsigned M0 = N->getMaskElt(0) / 4; 2239 unsigned M1 = N->getMaskElt(4) / 4; 2240 unsigned M2 = N->getMaskElt(8) / 4; 2241 unsigned M3 = N->getMaskElt(12) / 4; 2242 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2243 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2244 2245 // Below, let H and L be arbitrary elements of the shuffle mask 2246 // where H is in the range [4,7] and L is in the range [0,3]. 2247 // H, 1, 2, 3 or L, 5, 6, 7 2248 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2249 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2250 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2251 InsertAtByte = IsLE ? 12 : 0; 2252 Swap = M0 < 4; 2253 return true; 2254 } 2255 // 0, H, 2, 3 or 4, L, 6, 7 2256 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2257 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2258 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2259 InsertAtByte = IsLE ? 8 : 4; 2260 Swap = M1 < 4; 2261 return true; 2262 } 2263 // 0, 1, H, 3 or 4, 5, L, 7 2264 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2265 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2266 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2267 InsertAtByte = IsLE ? 4 : 8; 2268 Swap = M2 < 4; 2269 return true; 2270 } 2271 // 0, 1, 2, H or 4, 5, 6, L 2272 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2273 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2274 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2275 InsertAtByte = IsLE ? 0 : 12; 2276 Swap = M3 < 4; 2277 return true; 2278 } 2279 2280 // If both vector operands for the shuffle are the same vector, the mask will 2281 // contain only elements from the first one and the second one will be undef. 2282 if (N->getOperand(1).isUndef()) { 2283 ShiftElts = 0; 2284 Swap = true; 2285 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2286 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2287 InsertAtByte = IsLE ? 12 : 0; 2288 return true; 2289 } 2290 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2291 InsertAtByte = IsLE ? 8 : 4; 2292 return true; 2293 } 2294 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2295 InsertAtByte = IsLE ? 4 : 8; 2296 return true; 2297 } 2298 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2299 InsertAtByte = IsLE ? 0 : 12; 2300 return true; 2301 } 2302 } 2303 2304 return false; 2305 } 2306 2307 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2308 bool &Swap, bool IsLE) { 2309 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2310 // Ensure each byte index of the word is consecutive. 2311 if (!isNByteElemShuffleMask(N, 4, 1)) 2312 return false; 2313 2314 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2315 unsigned M0 = N->getMaskElt(0) / 4; 2316 unsigned M1 = N->getMaskElt(4) / 4; 2317 unsigned M2 = N->getMaskElt(8) / 4; 2318 unsigned M3 = N->getMaskElt(12) / 4; 2319 2320 // If both vector operands for the shuffle are the same vector, the mask will 2321 // contain only elements from the first one and the second one will be undef. 2322 if (N->getOperand(1).isUndef()) { 2323 assert(M0 < 4 && "Indexing into an undef vector?"); 2324 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2325 return false; 2326 2327 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2328 Swap = false; 2329 return true; 2330 } 2331 2332 // Ensure each word index of the ShuffleVector Mask is consecutive. 2333 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2334 return false; 2335 2336 if (IsLE) { 2337 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2338 // Input vectors don't need to be swapped if the leading element 2339 // of the result is one of the 3 left elements of the second vector 2340 // (or if there is no shift to be done at all). 2341 Swap = false; 2342 ShiftElts = (8 - M0) % 8; 2343 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2344 // Input vectors need to be swapped if the leading element 2345 // of the result is one of the 3 left elements of the first vector 2346 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2347 Swap = true; 2348 ShiftElts = (4 - M0) % 4; 2349 } 2350 2351 return true; 2352 } else { // BE 2353 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2354 // Input vectors don't need to be swapped if the leading element 2355 // of the result is one of the 4 elements of the first vector. 2356 Swap = false; 2357 ShiftElts = M0; 2358 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2359 // Input vectors need to be swapped if the leading element 2360 // of the result is one of the 4 elements of the right vector. 2361 Swap = true; 2362 ShiftElts = M0 - 4; 2363 } 2364 2365 return true; 2366 } 2367 } 2368 2369 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2370 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2371 2372 if (!isNByteElemShuffleMask(N, Width, -1)) 2373 return false; 2374 2375 for (int i = 0; i < 16; i += Width) 2376 if (N->getMaskElt(i) != i + Width - 1) 2377 return false; 2378 2379 return true; 2380 } 2381 2382 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2383 return isXXBRShuffleMaskHelper(N, 2); 2384 } 2385 2386 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2387 return isXXBRShuffleMaskHelper(N, 4); 2388 } 2389 2390 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2391 return isXXBRShuffleMaskHelper(N, 8); 2392 } 2393 2394 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2395 return isXXBRShuffleMaskHelper(N, 16); 2396 } 2397 2398 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2399 /// if the inputs to the instruction should be swapped and set \p DM to the 2400 /// value for the immediate. 2401 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2402 /// AND element 0 of the result comes from the first input (LE) or second input 2403 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2404 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2405 /// mask. 2406 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2407 bool &Swap, bool IsLE) { 2408 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2409 2410 // Ensure each byte index of the double word is consecutive. 2411 if (!isNByteElemShuffleMask(N, 8, 1)) 2412 return false; 2413 2414 unsigned M0 = N->getMaskElt(0) / 8; 2415 unsigned M1 = N->getMaskElt(8) / 8; 2416 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2417 2418 // If both vector operands for the shuffle are the same vector, the mask will 2419 // contain only elements from the first one and the second one will be undef. 2420 if (N->getOperand(1).isUndef()) { 2421 if ((M0 | M1) < 2) { 2422 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2423 Swap = false; 2424 return true; 2425 } else 2426 return false; 2427 } 2428 2429 if (IsLE) { 2430 if (M0 > 1 && M1 < 2) { 2431 Swap = false; 2432 } else if (M0 < 2 && M1 > 1) { 2433 M0 = (M0 + 2) % 4; 2434 M1 = (M1 + 2) % 4; 2435 Swap = true; 2436 } else 2437 return false; 2438 2439 // Note: if control flow comes here that means Swap is already set above 2440 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2441 return true; 2442 } else { // BE 2443 if (M0 < 2 && M1 > 1) { 2444 Swap = false; 2445 } else if (M0 > 1 && M1 < 2) { 2446 M0 = (M0 + 2) % 4; 2447 M1 = (M1 + 2) % 4; 2448 Swap = true; 2449 } else 2450 return false; 2451 2452 // Note: if control flow comes here that means Swap is already set above 2453 DM = (M0 << 1) + (M1 & 1); 2454 return true; 2455 } 2456 } 2457 2458 2459 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2460 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2461 /// elements are counted from the left of the vector register). 2462 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2463 SelectionDAG &DAG) { 2464 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2465 assert(isSplatShuffleMask(SVOp, EltSize)); 2466 EVT VT = SVOp->getValueType(0); 2467 2468 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2469 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0) 2470 : SVOp->getMaskElt(0); 2471 2472 if (DAG.getDataLayout().isLittleEndian()) 2473 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2474 else 2475 return SVOp->getMaskElt(0) / EltSize; 2476 } 2477 2478 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2479 /// by using a vspltis[bhw] instruction of the specified element size, return 2480 /// the constant being splatted. The ByteSize field indicates the number of 2481 /// bytes of each element [124] -> [bhw]. 2482 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2483 SDValue OpVal; 2484 2485 // If ByteSize of the splat is bigger than the element size of the 2486 // build_vector, then we have a case where we are checking for a splat where 2487 // multiple elements of the buildvector are folded together into a single 2488 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2489 unsigned EltSize = 16/N->getNumOperands(); 2490 if (EltSize < ByteSize) { 2491 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2492 SDValue UniquedVals[4]; 2493 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2494 2495 // See if all of the elements in the buildvector agree across. 2496 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2497 if (N->getOperand(i).isUndef()) continue; 2498 // If the element isn't a constant, bail fully out. 2499 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2500 2501 if (!UniquedVals[i&(Multiple-1)].getNode()) 2502 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2503 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2504 return SDValue(); // no match. 2505 } 2506 2507 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2508 // either constant or undef values that are identical for each chunk. See 2509 // if these chunks can form into a larger vspltis*. 2510 2511 // Check to see if all of the leading entries are either 0 or -1. If 2512 // neither, then this won't fit into the immediate field. 2513 bool LeadingZero = true; 2514 bool LeadingOnes = true; 2515 for (unsigned i = 0; i != Multiple-1; ++i) { 2516 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2517 2518 LeadingZero &= isNullConstant(UniquedVals[i]); 2519 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2520 } 2521 // Finally, check the least significant entry. 2522 if (LeadingZero) { 2523 if (!UniquedVals[Multiple-1].getNode()) 2524 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2525 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2526 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2527 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2528 } 2529 if (LeadingOnes) { 2530 if (!UniquedVals[Multiple-1].getNode()) 2531 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2532 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2533 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2534 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2535 } 2536 2537 return SDValue(); 2538 } 2539 2540 // Check to see if this buildvec has a single non-undef value in its elements. 2541 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2542 if (N->getOperand(i).isUndef()) continue; 2543 if (!OpVal.getNode()) 2544 OpVal = N->getOperand(i); 2545 else if (OpVal != N->getOperand(i)) 2546 return SDValue(); 2547 } 2548 2549 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2550 2551 unsigned ValSizeInBytes = EltSize; 2552 uint64_t Value = 0; 2553 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2554 Value = CN->getZExtValue(); 2555 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2556 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2557 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2558 } 2559 2560 // If the splat value is larger than the element value, then we can never do 2561 // this splat. The only case that we could fit the replicated bits into our 2562 // immediate field for would be zero, and we prefer to use vxor for it. 2563 if (ValSizeInBytes < ByteSize) return SDValue(); 2564 2565 // If the element value is larger than the splat value, check if it consists 2566 // of a repeated bit pattern of size ByteSize. 2567 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2568 return SDValue(); 2569 2570 // Properly sign extend the value. 2571 int MaskVal = SignExtend32(Value, ByteSize * 8); 2572 2573 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2574 if (MaskVal == 0) return SDValue(); 2575 2576 // Finally, if this value fits in a 5 bit sext field, return it 2577 if (SignExtend32<5>(MaskVal) == MaskVal) 2578 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2579 return SDValue(); 2580 } 2581 2582 //===----------------------------------------------------------------------===// 2583 // Addressing Mode Selection 2584 //===----------------------------------------------------------------------===// 2585 2586 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2587 /// or 64-bit immediate, and if the value can be accurately represented as a 2588 /// sign extension from a 16-bit value. If so, this returns true and the 2589 /// immediate. 2590 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2591 if (!isa<ConstantSDNode>(N)) 2592 return false; 2593 2594 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2595 if (N->getValueType(0) == MVT::i32) 2596 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2597 else 2598 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2599 } 2600 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2601 return isIntS16Immediate(Op.getNode(), Imm); 2602 } 2603 2604 /// Used when computing address flags for selecting loads and stores. 2605 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2606 /// An OR of two provably disjoint values is equivalent to an ADD. 2607 /// Most PPC load/store instructions compute the effective address as a sum, 2608 /// so doing this conversion is useful. 2609 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2610 if (N.getOpcode() != ISD::OR) 2611 return false; 2612 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2613 if (!LHSKnown.Zero.getBoolValue()) 2614 return false; 2615 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2616 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2617 } 2618 2619 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2620 /// be represented as an indexed [r+r] operation. 2621 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2622 SDValue &Index, 2623 SelectionDAG &DAG) const { 2624 for (SDNode *U : N->uses()) { 2625 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2626 if (Memop->getMemoryVT() == MVT::f64) { 2627 Base = N.getOperand(0); 2628 Index = N.getOperand(1); 2629 return true; 2630 } 2631 } 2632 } 2633 return false; 2634 } 2635 2636 /// isIntS34Immediate - This method tests if value of node given can be 2637 /// accurately represented as a sign extension from a 34-bit value. If so, 2638 /// this returns true and the immediate. 2639 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2640 if (!isa<ConstantSDNode>(N)) 2641 return false; 2642 2643 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2644 return isInt<34>(Imm); 2645 } 2646 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2647 return isIntS34Immediate(Op.getNode(), Imm); 2648 } 2649 2650 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2651 /// can be represented as an indexed [r+r] operation. Returns false if it 2652 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2653 /// non-zero and N can be represented by a base register plus a signed 16-bit 2654 /// displacement, make a more precise judgement by checking (displacement % \p 2655 /// EncodingAlignment). 2656 bool PPCTargetLowering::SelectAddressRegReg( 2657 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2658 MaybeAlign EncodingAlignment) const { 2659 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2660 // a [pc+imm]. 2661 if (SelectAddressPCRel(N, Base)) 2662 return false; 2663 2664 int16_t Imm = 0; 2665 if (N.getOpcode() == ISD::ADD) { 2666 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2667 // SPE load/store can only handle 8-bit offsets. 2668 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2669 return true; 2670 if (isIntS16Immediate(N.getOperand(1), Imm) && 2671 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2672 return false; // r+i 2673 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2674 return false; // r+i 2675 2676 Base = N.getOperand(0); 2677 Index = N.getOperand(1); 2678 return true; 2679 } else if (N.getOpcode() == ISD::OR) { 2680 if (isIntS16Immediate(N.getOperand(1), Imm) && 2681 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2682 return false; // r+i can fold it if we can. 2683 2684 // If this is an or of disjoint bitfields, we can codegen this as an add 2685 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2686 // disjoint. 2687 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2688 2689 if (LHSKnown.Zero.getBoolValue()) { 2690 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2691 // If all of the bits are known zero on the LHS or RHS, the add won't 2692 // carry. 2693 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2694 Base = N.getOperand(0); 2695 Index = N.getOperand(1); 2696 return true; 2697 } 2698 } 2699 } 2700 2701 return false; 2702 } 2703 2704 // If we happen to be doing an i64 load or store into a stack slot that has 2705 // less than a 4-byte alignment, then the frame-index elimination may need to 2706 // use an indexed load or store instruction (because the offset may not be a 2707 // multiple of 4). The extra register needed to hold the offset comes from the 2708 // register scavenger, and it is possible that the scavenger will need to use 2709 // an emergency spill slot. As a result, we need to make sure that a spill slot 2710 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2711 // stack slot. 2712 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2713 // FIXME: This does not handle the LWA case. 2714 if (VT != MVT::i64) 2715 return; 2716 2717 // NOTE: We'll exclude negative FIs here, which come from argument 2718 // lowering, because there are no known test cases triggering this problem 2719 // using packed structures (or similar). We can remove this exclusion if 2720 // we find such a test case. The reason why this is so test-case driven is 2721 // because this entire 'fixup' is only to prevent crashes (from the 2722 // register scavenger) on not-really-valid inputs. For example, if we have: 2723 // %a = alloca i1 2724 // %b = bitcast i1* %a to i64* 2725 // store i64* a, i64 b 2726 // then the store should really be marked as 'align 1', but is not. If it 2727 // were marked as 'align 1' then the indexed form would have been 2728 // instruction-selected initially, and the problem this 'fixup' is preventing 2729 // won't happen regardless. 2730 if (FrameIdx < 0) 2731 return; 2732 2733 MachineFunction &MF = DAG.getMachineFunction(); 2734 MachineFrameInfo &MFI = MF.getFrameInfo(); 2735 2736 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2737 return; 2738 2739 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2740 FuncInfo->setHasNonRISpills(); 2741 } 2742 2743 /// Returns true if the address N can be represented by a base register plus 2744 /// a signed 16-bit displacement [r+imm], and if it is not better 2745 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2746 /// displacements that are multiples of that value. 2747 bool PPCTargetLowering::SelectAddressRegImm( 2748 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2749 MaybeAlign EncodingAlignment) const { 2750 // FIXME dl should come from parent load or store, not from address 2751 SDLoc dl(N); 2752 2753 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2754 // a [pc+imm]. 2755 if (SelectAddressPCRel(N, Base)) 2756 return false; 2757 2758 // If this can be more profitably realized as r+r, fail. 2759 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2760 return false; 2761 2762 if (N.getOpcode() == ISD::ADD) { 2763 int16_t imm = 0; 2764 if (isIntS16Immediate(N.getOperand(1), imm) && 2765 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2766 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2767 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2768 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2769 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2770 } else { 2771 Base = N.getOperand(0); 2772 } 2773 return true; // [r+i] 2774 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2775 // Match LOAD (ADD (X, Lo(G))). 2776 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2777 && "Cannot handle constant offsets yet!"); 2778 Disp = N.getOperand(1).getOperand(0); // The global address. 2779 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2780 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2781 Disp.getOpcode() == ISD::TargetConstantPool || 2782 Disp.getOpcode() == ISD::TargetJumpTable); 2783 Base = N.getOperand(0); 2784 return true; // [&g+r] 2785 } 2786 } else if (N.getOpcode() == ISD::OR) { 2787 int16_t imm = 0; 2788 if (isIntS16Immediate(N.getOperand(1), imm) && 2789 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2790 // If this is an or of disjoint bitfields, we can codegen this as an add 2791 // (for better address arithmetic) if the LHS and RHS of the OR are 2792 // provably disjoint. 2793 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2794 2795 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2796 // If all of the bits are known zero on the LHS or RHS, the add won't 2797 // carry. 2798 if (FrameIndexSDNode *FI = 2799 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2800 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2801 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2802 } else { 2803 Base = N.getOperand(0); 2804 } 2805 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2806 return true; 2807 } 2808 } 2809 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2810 // Loading from a constant address. 2811 2812 // If this address fits entirely in a 16-bit sext immediate field, codegen 2813 // this as "d, 0" 2814 int16_t Imm; 2815 if (isIntS16Immediate(CN, Imm) && 2816 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2817 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2818 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2819 CN->getValueType(0)); 2820 return true; 2821 } 2822 2823 // Handle 32-bit sext immediates with LIS + addr mode. 2824 if ((CN->getValueType(0) == MVT::i32 || 2825 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2826 (!EncodingAlignment || 2827 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2828 int Addr = (int)CN->getZExtValue(); 2829 2830 // Otherwise, break this down into an LIS + disp. 2831 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2832 2833 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2834 MVT::i32); 2835 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2836 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2837 return true; 2838 } 2839 } 2840 2841 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2842 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2843 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2844 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2845 } else 2846 Base = N; 2847 return true; // [r+0] 2848 } 2849 2850 /// Similar to the 16-bit case but for instructions that take a 34-bit 2851 /// displacement field (prefixed loads/stores). 2852 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2853 SDValue &Base, 2854 SelectionDAG &DAG) const { 2855 // Only on 64-bit targets. 2856 if (N.getValueType() != MVT::i64) 2857 return false; 2858 2859 SDLoc dl(N); 2860 int64_t Imm = 0; 2861 2862 if (N.getOpcode() == ISD::ADD) { 2863 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2864 return false; 2865 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2866 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2867 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2868 else 2869 Base = N.getOperand(0); 2870 return true; 2871 } 2872 2873 if (N.getOpcode() == ISD::OR) { 2874 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2875 return false; 2876 // If this is an or of disjoint bitfields, we can codegen this as an add 2877 // (for better address arithmetic) if the LHS and RHS of the OR are 2878 // provably disjoint. 2879 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2880 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2881 return false; 2882 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2883 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2884 else 2885 Base = N.getOperand(0); 2886 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2887 return true; 2888 } 2889 2890 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2891 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2892 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2893 return true; 2894 } 2895 2896 return false; 2897 } 2898 2899 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2900 /// represented as an indexed [r+r] operation. 2901 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2902 SDValue &Index, 2903 SelectionDAG &DAG) const { 2904 // Check to see if we can easily represent this as an [r+r] address. This 2905 // will fail if it thinks that the address is more profitably represented as 2906 // reg+imm, e.g. where imm = 0. 2907 if (SelectAddressRegReg(N, Base, Index, DAG)) 2908 return true; 2909 2910 // If the address is the result of an add, we will utilize the fact that the 2911 // address calculation includes an implicit add. However, we can reduce 2912 // register pressure if we do not materialize a constant just for use as the 2913 // index register. We only get rid of the add if it is not an add of a 2914 // value and a 16-bit signed constant and both have a single use. 2915 int16_t imm = 0; 2916 if (N.getOpcode() == ISD::ADD && 2917 (!isIntS16Immediate(N.getOperand(1), imm) || 2918 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2919 Base = N.getOperand(0); 2920 Index = N.getOperand(1); 2921 return true; 2922 } 2923 2924 // Otherwise, do it the hard way, using R0 as the base register. 2925 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2926 N.getValueType()); 2927 Index = N; 2928 return true; 2929 } 2930 2931 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2932 Ty *PCRelCand = dyn_cast<Ty>(N); 2933 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2934 } 2935 2936 /// Returns true if this address is a PC Relative address. 2937 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2938 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2939 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2940 // This is a materialize PC Relative node. Always select this as PC Relative. 2941 Base = N; 2942 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2943 return true; 2944 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2945 isValidPCRelNode<GlobalAddressSDNode>(N) || 2946 isValidPCRelNode<JumpTableSDNode>(N) || 2947 isValidPCRelNode<BlockAddressSDNode>(N)) 2948 return true; 2949 return false; 2950 } 2951 2952 /// Returns true if we should use a direct load into vector instruction 2953 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2954 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2955 2956 // If there are any other uses other than scalar to vector, then we should 2957 // keep it as a scalar load -> direct move pattern to prevent multiple 2958 // loads. 2959 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2960 if (!LD) 2961 return false; 2962 2963 EVT MemVT = LD->getMemoryVT(); 2964 if (!MemVT.isSimple()) 2965 return false; 2966 switch(MemVT.getSimpleVT().SimpleTy) { 2967 case MVT::i64: 2968 break; 2969 case MVT::i32: 2970 if (!ST.hasP8Vector()) 2971 return false; 2972 break; 2973 case MVT::i16: 2974 case MVT::i8: 2975 if (!ST.hasP9Vector()) 2976 return false; 2977 break; 2978 default: 2979 return false; 2980 } 2981 2982 SDValue LoadedVal(N, 0); 2983 if (!LoadedVal.hasOneUse()) 2984 return false; 2985 2986 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2987 UI != UE; ++UI) 2988 if (UI.getUse().get().getResNo() == 0 && 2989 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2990 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2991 return false; 2992 2993 return true; 2994 } 2995 2996 /// getPreIndexedAddressParts - returns true by value, base pointer and 2997 /// offset pointer and addressing mode by reference if the node's address 2998 /// can be legally represented as pre-indexed load / store address. 2999 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 3000 SDValue &Offset, 3001 ISD::MemIndexedMode &AM, 3002 SelectionDAG &DAG) const { 3003 if (DisablePPCPreinc) return false; 3004 3005 bool isLoad = true; 3006 SDValue Ptr; 3007 EVT VT; 3008 Align Alignment; 3009 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3010 Ptr = LD->getBasePtr(); 3011 VT = LD->getMemoryVT(); 3012 Alignment = LD->getAlign(); 3013 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 3014 Ptr = ST->getBasePtr(); 3015 VT = ST->getMemoryVT(); 3016 Alignment = ST->getAlign(); 3017 isLoad = false; 3018 } else 3019 return false; 3020 3021 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 3022 // instructions because we can fold these into a more efficient instruction 3023 // instead, (such as LXSD). 3024 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 3025 return false; 3026 } 3027 3028 // PowerPC doesn't have preinc load/store instructions for vectors 3029 if (VT.isVector()) 3030 return false; 3031 3032 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 3033 // Common code will reject creating a pre-inc form if the base pointer 3034 // is a frame index, or if N is a store and the base pointer is either 3035 // the same as or a predecessor of the value being stored. Check for 3036 // those situations here, and try with swapped Base/Offset instead. 3037 bool Swap = false; 3038 3039 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 3040 Swap = true; 3041 else if (!isLoad) { 3042 SDValue Val = cast<StoreSDNode>(N)->getValue(); 3043 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 3044 Swap = true; 3045 } 3046 3047 if (Swap) 3048 std::swap(Base, Offset); 3049 3050 AM = ISD::PRE_INC; 3051 return true; 3052 } 3053 3054 // LDU/STU can only handle immediates that are a multiple of 4. 3055 if (VT != MVT::i64) { 3056 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt)) 3057 return false; 3058 } else { 3059 // LDU/STU need an address with at least 4-byte alignment. 3060 if (Alignment < Align(4)) 3061 return false; 3062 3063 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3064 return false; 3065 } 3066 3067 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3068 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3069 // sext i32 to i64 when addr mode is r+i. 3070 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3071 LD->getExtensionType() == ISD::SEXTLOAD && 3072 isa<ConstantSDNode>(Offset)) 3073 return false; 3074 } 3075 3076 AM = ISD::PRE_INC; 3077 return true; 3078 } 3079 3080 //===----------------------------------------------------------------------===// 3081 // LowerOperation implementation 3082 //===----------------------------------------------------------------------===// 3083 3084 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3085 /// and LoOpFlags to the target MO flags. 3086 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3087 unsigned &HiOpFlags, unsigned &LoOpFlags, 3088 const GlobalValue *GV = nullptr) { 3089 HiOpFlags = PPCII::MO_HA; 3090 LoOpFlags = PPCII::MO_LO; 3091 3092 // Don't use the pic base if not in PIC relocation model. 3093 if (IsPIC) { 3094 HiOpFlags |= PPCII::MO_PIC_FLAG; 3095 LoOpFlags |= PPCII::MO_PIC_FLAG; 3096 } 3097 } 3098 3099 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3100 SelectionDAG &DAG) { 3101 SDLoc DL(HiPart); 3102 EVT PtrVT = HiPart.getValueType(); 3103 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3104 3105 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3106 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3107 3108 // With PIC, the first instruction is actually "GR+hi(&G)". 3109 if (isPIC) 3110 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3111 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3112 3113 // Generate non-pic code that has direct accesses to the constant pool. 3114 // The address of the global is just (hi(&g)+lo(&g)). 3115 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3116 } 3117 3118 static void setUsesTOCBasePtr(MachineFunction &MF) { 3119 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3120 FuncInfo->setUsesTOCBasePtr(); 3121 } 3122 3123 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3124 setUsesTOCBasePtr(DAG.getMachineFunction()); 3125 } 3126 3127 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3128 SDValue GA) const { 3129 const bool Is64Bit = Subtarget.isPPC64(); 3130 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3131 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3132 : Subtarget.isAIXABI() 3133 ? DAG.getRegister(PPC::R2, VT) 3134 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3135 SDValue Ops[] = { GA, Reg }; 3136 return DAG.getMemIntrinsicNode( 3137 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3138 MachinePointerInfo::getGOT(DAG.getMachineFunction()), std::nullopt, 3139 MachineMemOperand::MOLoad); 3140 } 3141 3142 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3143 SelectionDAG &DAG) const { 3144 EVT PtrVT = Op.getValueType(); 3145 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3146 const Constant *C = CP->getConstVal(); 3147 3148 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3149 // The actual address of the GlobalValue is stored in the TOC. 3150 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3151 if (Subtarget.isUsingPCRelativeCalls()) { 3152 SDLoc DL(CP); 3153 EVT Ty = getPointerTy(DAG.getDataLayout()); 3154 SDValue ConstPool = DAG.getTargetConstantPool( 3155 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3156 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3157 } 3158 setUsesTOCBasePtr(DAG); 3159 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3160 return getTOCEntry(DAG, SDLoc(CP), GA); 3161 } 3162 3163 unsigned MOHiFlag, MOLoFlag; 3164 bool IsPIC = isPositionIndependent(); 3165 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3166 3167 if (IsPIC && Subtarget.isSVR4ABI()) { 3168 SDValue GA = 3169 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3170 return getTOCEntry(DAG, SDLoc(CP), GA); 3171 } 3172 3173 SDValue CPIHi = 3174 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3175 SDValue CPILo = 3176 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3177 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3178 } 3179 3180 // For 64-bit PowerPC, prefer the more compact relative encodings. 3181 // This trades 32 bits per jump table entry for one or two instructions 3182 // on the jump site. 3183 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3184 if (isJumpTableRelative()) 3185 return MachineJumpTableInfo::EK_LabelDifference32; 3186 3187 return TargetLowering::getJumpTableEncoding(); 3188 } 3189 3190 bool PPCTargetLowering::isJumpTableRelative() const { 3191 if (UseAbsoluteJumpTables) 3192 return false; 3193 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3194 return true; 3195 return TargetLowering::isJumpTableRelative(); 3196 } 3197 3198 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3199 SelectionDAG &DAG) const { 3200 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3201 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3202 3203 switch (getTargetMachine().getCodeModel()) { 3204 case CodeModel::Small: 3205 case CodeModel::Medium: 3206 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3207 default: 3208 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3209 getPointerTy(DAG.getDataLayout())); 3210 } 3211 } 3212 3213 const MCExpr * 3214 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3215 unsigned JTI, 3216 MCContext &Ctx) const { 3217 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3218 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3219 3220 switch (getTargetMachine().getCodeModel()) { 3221 case CodeModel::Small: 3222 case CodeModel::Medium: 3223 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3224 default: 3225 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3226 } 3227 } 3228 3229 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3230 EVT PtrVT = Op.getValueType(); 3231 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3232 3233 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3234 if (Subtarget.isUsingPCRelativeCalls()) { 3235 SDLoc DL(JT); 3236 EVT Ty = getPointerTy(DAG.getDataLayout()); 3237 SDValue GA = 3238 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3239 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3240 return MatAddr; 3241 } 3242 3243 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3244 // The actual address of the GlobalValue is stored in the TOC. 3245 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3246 setUsesTOCBasePtr(DAG); 3247 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3248 return getTOCEntry(DAG, SDLoc(JT), GA); 3249 } 3250 3251 unsigned MOHiFlag, MOLoFlag; 3252 bool IsPIC = isPositionIndependent(); 3253 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3254 3255 if (IsPIC && Subtarget.isSVR4ABI()) { 3256 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3257 PPCII::MO_PIC_FLAG); 3258 return getTOCEntry(DAG, SDLoc(GA), GA); 3259 } 3260 3261 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3262 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3263 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3264 } 3265 3266 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3267 SelectionDAG &DAG) const { 3268 EVT PtrVT = Op.getValueType(); 3269 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3270 const BlockAddress *BA = BASDN->getBlockAddress(); 3271 3272 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3273 if (Subtarget.isUsingPCRelativeCalls()) { 3274 SDLoc DL(BASDN); 3275 EVT Ty = getPointerTy(DAG.getDataLayout()); 3276 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3277 PPCII::MO_PCREL_FLAG); 3278 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3279 return MatAddr; 3280 } 3281 3282 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3283 // The actual BlockAddress is stored in the TOC. 3284 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3285 setUsesTOCBasePtr(DAG); 3286 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3287 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3288 } 3289 3290 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3291 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3292 return getTOCEntry( 3293 DAG, SDLoc(BASDN), 3294 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3295 3296 unsigned MOHiFlag, MOLoFlag; 3297 bool IsPIC = isPositionIndependent(); 3298 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3299 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3300 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3301 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3302 } 3303 3304 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3305 SelectionDAG &DAG) const { 3306 if (Subtarget.isAIXABI()) 3307 return LowerGlobalTLSAddressAIX(Op, DAG); 3308 3309 return LowerGlobalTLSAddressLinux(Op, DAG); 3310 } 3311 3312 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3313 SelectionDAG &DAG) const { 3314 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3315 3316 if (DAG.getTarget().useEmulatedTLS()) 3317 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3318 3319 SDLoc dl(GA); 3320 const GlobalValue *GV = GA->getGlobal(); 3321 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3322 3323 // The general-dynamic model is the only access model supported for now, so 3324 // all the GlobalTLSAddress nodes are lowered with this model. 3325 // We need to generate two TOC entries, one for the variable offset, one for 3326 // the region handle. The global address for the TOC entry of the region 3327 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3328 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3329 SDValue VariableOffsetTGA = 3330 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3331 SDValue RegionHandleTGA = 3332 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3333 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3334 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3335 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3336 RegionHandle); 3337 } 3338 3339 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3340 SelectionDAG &DAG) const { 3341 // FIXME: TLS addresses currently use medium model code sequences, 3342 // which is the most useful form. Eventually support for small and 3343 // large models could be added if users need it, at the cost of 3344 // additional complexity. 3345 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3346 if (DAG.getTarget().useEmulatedTLS()) 3347 return LowerToTLSEmulatedModel(GA, DAG); 3348 3349 SDLoc dl(GA); 3350 const GlobalValue *GV = GA->getGlobal(); 3351 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3352 bool is64bit = Subtarget.isPPC64(); 3353 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3354 PICLevel::Level picLevel = M->getPICLevel(); 3355 3356 const TargetMachine &TM = getTargetMachine(); 3357 TLSModel::Model Model = TM.getTLSModel(GV); 3358 3359 if (Model == TLSModel::LocalExec) { 3360 if (Subtarget.isUsingPCRelativeCalls()) { 3361 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3362 SDValue TGA = DAG.getTargetGlobalAddress( 3363 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3364 SDValue MatAddr = 3365 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3366 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3367 } 3368 3369 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3370 PPCII::MO_TPREL_HA); 3371 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3372 PPCII::MO_TPREL_LO); 3373 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3374 : DAG.getRegister(PPC::R2, MVT::i32); 3375 3376 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3377 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3378 } 3379 3380 if (Model == TLSModel::InitialExec) { 3381 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3382 SDValue TGA = DAG.getTargetGlobalAddress( 3383 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3384 SDValue TGATLS = DAG.getTargetGlobalAddress( 3385 GV, dl, PtrVT, 0, 3386 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3387 SDValue TPOffset; 3388 if (IsPCRel) { 3389 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3390 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3391 MachinePointerInfo()); 3392 } else { 3393 SDValue GOTPtr; 3394 if (is64bit) { 3395 setUsesTOCBasePtr(DAG); 3396 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3397 GOTPtr = 3398 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3399 } else { 3400 if (!TM.isPositionIndependent()) 3401 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3402 else if (picLevel == PICLevel::SmallPIC) 3403 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3404 else 3405 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3406 } 3407 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3408 } 3409 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3410 } 3411 3412 if (Model == TLSModel::GeneralDynamic) { 3413 if (Subtarget.isUsingPCRelativeCalls()) { 3414 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3415 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3416 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3417 } 3418 3419 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3420 SDValue GOTPtr; 3421 if (is64bit) { 3422 setUsesTOCBasePtr(DAG); 3423 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3424 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3425 GOTReg, TGA); 3426 } else { 3427 if (picLevel == PICLevel::SmallPIC) 3428 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3429 else 3430 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3431 } 3432 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3433 GOTPtr, TGA, TGA); 3434 } 3435 3436 if (Model == TLSModel::LocalDynamic) { 3437 if (Subtarget.isUsingPCRelativeCalls()) { 3438 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3439 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3440 SDValue MatPCRel = 3441 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3442 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3443 } 3444 3445 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3446 SDValue GOTPtr; 3447 if (is64bit) { 3448 setUsesTOCBasePtr(DAG); 3449 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3450 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3451 GOTReg, TGA); 3452 } else { 3453 if (picLevel == PICLevel::SmallPIC) 3454 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3455 else 3456 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3457 } 3458 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3459 PtrVT, GOTPtr, TGA, TGA); 3460 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3461 PtrVT, TLSAddr, TGA); 3462 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3463 } 3464 3465 llvm_unreachable("Unknown TLS model!"); 3466 } 3467 3468 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3469 SelectionDAG &DAG) const { 3470 EVT PtrVT = Op.getValueType(); 3471 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3472 SDLoc DL(GSDN); 3473 const GlobalValue *GV = GSDN->getGlobal(); 3474 3475 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3476 // The actual address of the GlobalValue is stored in the TOC. 3477 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3478 if (Subtarget.isUsingPCRelativeCalls()) { 3479 EVT Ty = getPointerTy(DAG.getDataLayout()); 3480 if (isAccessedAsGotIndirect(Op)) { 3481 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3482 PPCII::MO_PCREL_FLAG | 3483 PPCII::MO_GOT_FLAG); 3484 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3485 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3486 MachinePointerInfo()); 3487 return Load; 3488 } else { 3489 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3490 PPCII::MO_PCREL_FLAG); 3491 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3492 } 3493 } 3494 setUsesTOCBasePtr(DAG); 3495 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3496 return getTOCEntry(DAG, DL, GA); 3497 } 3498 3499 unsigned MOHiFlag, MOLoFlag; 3500 bool IsPIC = isPositionIndependent(); 3501 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3502 3503 if (IsPIC && Subtarget.isSVR4ABI()) { 3504 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3505 GSDN->getOffset(), 3506 PPCII::MO_PIC_FLAG); 3507 return getTOCEntry(DAG, DL, GA); 3508 } 3509 3510 SDValue GAHi = 3511 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3512 SDValue GALo = 3513 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3514 3515 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3516 } 3517 3518 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3519 bool IsStrict = Op->isStrictFPOpcode(); 3520 ISD::CondCode CC = 3521 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3522 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3523 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3524 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3525 EVT LHSVT = LHS.getValueType(); 3526 SDLoc dl(Op); 3527 3528 // Soften the setcc with libcall if it is fp128. 3529 if (LHSVT == MVT::f128) { 3530 assert(!Subtarget.hasP9Vector() && 3531 "SETCC for f128 is already legal under Power9!"); 3532 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3533 Op->getOpcode() == ISD::STRICT_FSETCCS); 3534 if (RHS.getNode()) 3535 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3536 DAG.getCondCode(CC)); 3537 if (IsStrict) 3538 return DAG.getMergeValues({LHS, Chain}, dl); 3539 return LHS; 3540 } 3541 3542 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3543 3544 if (Op.getValueType() == MVT::v2i64) { 3545 // When the operands themselves are v2i64 values, we need to do something 3546 // special because VSX has no underlying comparison operations for these. 3547 if (LHS.getValueType() == MVT::v2i64) { 3548 // Equality can be handled by casting to the legal type for Altivec 3549 // comparisons, everything else needs to be expanded. 3550 if (CC != ISD::SETEQ && CC != ISD::SETNE) 3551 return SDValue(); 3552 SDValue SetCC32 = DAG.getSetCC( 3553 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3554 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC); 3555 int ShuffV[] = {1, 0, 3, 2}; 3556 SDValue Shuff = 3557 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV); 3558 return DAG.getBitcast(MVT::v2i64, 3559 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR, 3560 dl, MVT::v4i32, Shuff, SetCC32)); 3561 } 3562 3563 // We handle most of these in the usual way. 3564 return Op; 3565 } 3566 3567 // If we're comparing for equality to zero, expose the fact that this is 3568 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3569 // fold the new nodes. 3570 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3571 return V; 3572 3573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3574 // Leave comparisons against 0 and -1 alone for now, since they're usually 3575 // optimized. FIXME: revisit this when we can custom lower all setcc 3576 // optimizations. 3577 if (C->isAllOnes() || C->isZero()) 3578 return SDValue(); 3579 } 3580 3581 // If we have an integer seteq/setne, turn it into a compare against zero 3582 // by xor'ing the rhs with the lhs, which is faster than setting a 3583 // condition register, reading it back out, and masking the correct bit. The 3584 // normal approach here uses sub to do this instead of xor. Using xor exposes 3585 // the result to other bit-twiddling opportunities. 3586 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3587 EVT VT = Op.getValueType(); 3588 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3589 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3590 } 3591 return SDValue(); 3592 } 3593 3594 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3595 SDNode *Node = Op.getNode(); 3596 EVT VT = Node->getValueType(0); 3597 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3598 SDValue InChain = Node->getOperand(0); 3599 SDValue VAListPtr = Node->getOperand(1); 3600 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3601 SDLoc dl(Node); 3602 3603 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3604 3605 // gpr_index 3606 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3607 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3608 InChain = GprIndex.getValue(1); 3609 3610 if (VT == MVT::i64) { 3611 // Check if GprIndex is even 3612 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3613 DAG.getConstant(1, dl, MVT::i32)); 3614 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3615 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3616 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3617 DAG.getConstant(1, dl, MVT::i32)); 3618 // Align GprIndex to be even if it isn't 3619 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3620 GprIndex); 3621 } 3622 3623 // fpr index is 1 byte after gpr 3624 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3625 DAG.getConstant(1, dl, MVT::i32)); 3626 3627 // fpr 3628 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3629 FprPtr, MachinePointerInfo(SV), MVT::i8); 3630 InChain = FprIndex.getValue(1); 3631 3632 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3633 DAG.getConstant(8, dl, MVT::i32)); 3634 3635 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3636 DAG.getConstant(4, dl, MVT::i32)); 3637 3638 // areas 3639 SDValue OverflowArea = 3640 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3641 InChain = OverflowArea.getValue(1); 3642 3643 SDValue RegSaveArea = 3644 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3645 InChain = RegSaveArea.getValue(1); 3646 3647 // select overflow_area if index > 8 3648 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3649 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3650 3651 // adjustment constant gpr_index * 4/8 3652 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3653 VT.isInteger() ? GprIndex : FprIndex, 3654 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3655 MVT::i32)); 3656 3657 // OurReg = RegSaveArea + RegConstant 3658 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3659 RegConstant); 3660 3661 // Floating types are 32 bytes into RegSaveArea 3662 if (VT.isFloatingPoint()) 3663 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3664 DAG.getConstant(32, dl, MVT::i32)); 3665 3666 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3667 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3668 VT.isInteger() ? GprIndex : FprIndex, 3669 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3670 MVT::i32)); 3671 3672 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3673 VT.isInteger() ? VAListPtr : FprPtr, 3674 MachinePointerInfo(SV), MVT::i8); 3675 3676 // determine if we should load from reg_save_area or overflow_area 3677 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3678 3679 // increase overflow_area by 4/8 if gpr/fpr > 8 3680 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3681 DAG.getConstant(VT.isInteger() ? 4 : 8, 3682 dl, MVT::i32)); 3683 3684 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3685 OverflowAreaPlusN); 3686 3687 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3688 MachinePointerInfo(), MVT::i32); 3689 3690 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3691 } 3692 3693 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3694 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3695 3696 // We have to copy the entire va_list struct: 3697 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3698 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3699 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3700 false, true, false, MachinePointerInfo(), 3701 MachinePointerInfo()); 3702 } 3703 3704 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3705 SelectionDAG &DAG) const { 3706 if (Subtarget.isAIXABI()) 3707 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3708 3709 return Op.getOperand(0); 3710 } 3711 3712 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3713 MachineFunction &MF = DAG.getMachineFunction(); 3714 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3715 3716 assert((Op.getOpcode() == ISD::INLINEASM || 3717 Op.getOpcode() == ISD::INLINEASM_BR) && 3718 "Expecting Inline ASM node."); 3719 3720 // If an LR store is already known to be required then there is not point in 3721 // checking this ASM as well. 3722 if (MFI.isLRStoreRequired()) 3723 return Op; 3724 3725 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3726 // type MVT::Glue. We want to ignore this last operand if that is the case. 3727 unsigned NumOps = Op.getNumOperands(); 3728 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3729 --NumOps; 3730 3731 // Check all operands that may contain the LR. 3732 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3733 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3734 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3735 ++i; // Skip the ID value. 3736 3737 switch (InlineAsm::getKind(Flags)) { 3738 default: 3739 llvm_unreachable("Bad flags!"); 3740 case InlineAsm::Kind_RegUse: 3741 case InlineAsm::Kind_Imm: 3742 case InlineAsm::Kind_Mem: 3743 i += NumVals; 3744 break; 3745 case InlineAsm::Kind_Clobber: 3746 case InlineAsm::Kind_RegDef: 3747 case InlineAsm::Kind_RegDefEarlyClobber: { 3748 for (; NumVals; --NumVals, ++i) { 3749 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3750 if (Reg != PPC::LR && Reg != PPC::LR8) 3751 continue; 3752 MFI.setLRStoreRequired(); 3753 return Op; 3754 } 3755 break; 3756 } 3757 } 3758 } 3759 3760 return Op; 3761 } 3762 3763 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3764 SelectionDAG &DAG) const { 3765 if (Subtarget.isAIXABI()) 3766 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3767 3768 SDValue Chain = Op.getOperand(0); 3769 SDValue Trmp = Op.getOperand(1); // trampoline 3770 SDValue FPtr = Op.getOperand(2); // nested function 3771 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3772 SDLoc dl(Op); 3773 3774 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3775 bool isPPC64 = (PtrVT == MVT::i64); 3776 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3777 3778 TargetLowering::ArgListTy Args; 3779 TargetLowering::ArgListEntry Entry; 3780 3781 Entry.Ty = IntPtrTy; 3782 Entry.Node = Trmp; Args.push_back(Entry); 3783 3784 // TrampSize == (isPPC64 ? 48 : 40); 3785 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3786 isPPC64 ? MVT::i64 : MVT::i32); 3787 Args.push_back(Entry); 3788 3789 Entry.Node = FPtr; Args.push_back(Entry); 3790 Entry.Node = Nest; Args.push_back(Entry); 3791 3792 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3793 TargetLowering::CallLoweringInfo CLI(DAG); 3794 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3795 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3796 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3797 3798 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3799 return CallResult.second; 3800 } 3801 3802 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3803 MachineFunction &MF = DAG.getMachineFunction(); 3804 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3805 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3806 3807 SDLoc dl(Op); 3808 3809 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3810 // vastart just stores the address of the VarArgsFrameIndex slot into the 3811 // memory location argument. 3812 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3813 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3814 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3815 MachinePointerInfo(SV)); 3816 } 3817 3818 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3819 // We suppose the given va_list is already allocated. 3820 // 3821 // typedef struct { 3822 // char gpr; /* index into the array of 8 GPRs 3823 // * stored in the register save area 3824 // * gpr=0 corresponds to r3, 3825 // * gpr=1 to r4, etc. 3826 // */ 3827 // char fpr; /* index into the array of 8 FPRs 3828 // * stored in the register save area 3829 // * fpr=0 corresponds to f1, 3830 // * fpr=1 to f2, etc. 3831 // */ 3832 // char *overflow_arg_area; 3833 // /* location on stack that holds 3834 // * the next overflow argument 3835 // */ 3836 // char *reg_save_area; 3837 // /* where r3:r10 and f1:f8 (if saved) 3838 // * are stored 3839 // */ 3840 // } va_list[1]; 3841 3842 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3843 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3844 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3845 PtrVT); 3846 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3847 PtrVT); 3848 3849 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3850 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3851 3852 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3853 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3854 3855 uint64_t FPROffset = 1; 3856 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3857 3858 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3859 3860 // Store first byte : number of int regs 3861 SDValue firstStore = 3862 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3863 MachinePointerInfo(SV), MVT::i8); 3864 uint64_t nextOffset = FPROffset; 3865 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3866 ConstFPROffset); 3867 3868 // Store second byte : number of float regs 3869 SDValue secondStore = 3870 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3871 MachinePointerInfo(SV, nextOffset), MVT::i8); 3872 nextOffset += StackOffset; 3873 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3874 3875 // Store second word : arguments given on stack 3876 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3877 MachinePointerInfo(SV, nextOffset)); 3878 nextOffset += FrameOffset; 3879 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3880 3881 // Store third word : arguments given in registers 3882 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3883 MachinePointerInfo(SV, nextOffset)); 3884 } 3885 3886 /// FPR - The set of FP registers that should be allocated for arguments 3887 /// on Darwin and AIX. 3888 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3889 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3890 PPC::F11, PPC::F12, PPC::F13}; 3891 3892 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3893 /// the stack. 3894 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3895 unsigned PtrByteSize) { 3896 unsigned ArgSize = ArgVT.getStoreSize(); 3897 if (Flags.isByVal()) 3898 ArgSize = Flags.getByValSize(); 3899 3900 // Round up to multiples of the pointer size, except for array members, 3901 // which are always packed. 3902 if (!Flags.isInConsecutiveRegs()) 3903 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3904 3905 return ArgSize; 3906 } 3907 3908 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3909 /// on the stack. 3910 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3911 ISD::ArgFlagsTy Flags, 3912 unsigned PtrByteSize) { 3913 Align Alignment(PtrByteSize); 3914 3915 // Altivec parameters are padded to a 16 byte boundary. 3916 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3917 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3918 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3919 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3920 Alignment = Align(16); 3921 3922 // ByVal parameters are aligned as requested. 3923 if (Flags.isByVal()) { 3924 auto BVAlign = Flags.getNonZeroByValAlign(); 3925 if (BVAlign > PtrByteSize) { 3926 if (BVAlign.value() % PtrByteSize != 0) 3927 llvm_unreachable( 3928 "ByVal alignment is not a multiple of the pointer size"); 3929 3930 Alignment = BVAlign; 3931 } 3932 } 3933 3934 // Array members are always packed to their original alignment. 3935 if (Flags.isInConsecutiveRegs()) { 3936 // If the array member was split into multiple registers, the first 3937 // needs to be aligned to the size of the full type. (Except for 3938 // ppcf128, which is only aligned as its f64 components.) 3939 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3940 Alignment = Align(OrigVT.getStoreSize()); 3941 else 3942 Alignment = Align(ArgVT.getStoreSize()); 3943 } 3944 3945 return Alignment; 3946 } 3947 3948 /// CalculateStackSlotUsed - Return whether this argument will use its 3949 /// stack slot (instead of being passed in registers). ArgOffset, 3950 /// AvailableFPRs, and AvailableVRs must hold the current argument 3951 /// position, and will be updated to account for this argument. 3952 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3953 unsigned PtrByteSize, unsigned LinkageSize, 3954 unsigned ParamAreaSize, unsigned &ArgOffset, 3955 unsigned &AvailableFPRs, 3956 unsigned &AvailableVRs) { 3957 bool UseMemory = false; 3958 3959 // Respect alignment of argument on the stack. 3960 Align Alignment = 3961 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3962 ArgOffset = alignTo(ArgOffset, Alignment); 3963 // If there's no space left in the argument save area, we must 3964 // use memory (this check also catches zero-sized arguments). 3965 if (ArgOffset >= LinkageSize + ParamAreaSize) 3966 UseMemory = true; 3967 3968 // Allocate argument on the stack. 3969 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3970 if (Flags.isInConsecutiveRegsLast()) 3971 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3972 // If we overran the argument save area, we must use memory 3973 // (this check catches arguments passed partially in memory) 3974 if (ArgOffset > LinkageSize + ParamAreaSize) 3975 UseMemory = true; 3976 3977 // However, if the argument is actually passed in an FPR or a VR, 3978 // we don't use memory after all. 3979 if (!Flags.isByVal()) { 3980 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3981 if (AvailableFPRs > 0) { 3982 --AvailableFPRs; 3983 return false; 3984 } 3985 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3986 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3987 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3988 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3989 if (AvailableVRs > 0) { 3990 --AvailableVRs; 3991 return false; 3992 } 3993 } 3994 3995 return UseMemory; 3996 } 3997 3998 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3999 /// ensure minimum alignment required for target. 4000 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 4001 unsigned NumBytes) { 4002 return alignTo(NumBytes, Lowering->getStackAlign()); 4003 } 4004 4005 SDValue PPCTargetLowering::LowerFormalArguments( 4006 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4007 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4008 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4009 if (Subtarget.isAIXABI()) 4010 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 4011 InVals); 4012 if (Subtarget.is64BitELFABI()) 4013 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 4014 InVals); 4015 assert(Subtarget.is32BitELFABI()); 4016 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 4017 InVals); 4018 } 4019 4020 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 4021 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4022 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4023 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4024 4025 // 32-bit SVR4 ABI Stack Frame Layout: 4026 // +-----------------------------------+ 4027 // +--> | Back chain | 4028 // | +-----------------------------------+ 4029 // | | Floating-point register save area | 4030 // | +-----------------------------------+ 4031 // | | General register save area | 4032 // | +-----------------------------------+ 4033 // | | CR save word | 4034 // | +-----------------------------------+ 4035 // | | VRSAVE save word | 4036 // | +-----------------------------------+ 4037 // | | Alignment padding | 4038 // | +-----------------------------------+ 4039 // | | Vector register save area | 4040 // | +-----------------------------------+ 4041 // | | Local variable space | 4042 // | +-----------------------------------+ 4043 // | | Parameter list area | 4044 // | +-----------------------------------+ 4045 // | | LR save word | 4046 // | +-----------------------------------+ 4047 // SP--> +--- | Back chain | 4048 // +-----------------------------------+ 4049 // 4050 // Specifications: 4051 // System V Application Binary Interface PowerPC Processor Supplement 4052 // AltiVec Technology Programming Interface Manual 4053 4054 MachineFunction &MF = DAG.getMachineFunction(); 4055 MachineFrameInfo &MFI = MF.getFrameInfo(); 4056 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4057 4058 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4059 // Potential tail calls could cause overwriting of argument stack slots. 4060 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4061 (CallConv == CallingConv::Fast)); 4062 const Align PtrAlign(4); 4063 4064 // Assign locations to all of the incoming arguments. 4065 SmallVector<CCValAssign, 16> ArgLocs; 4066 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4067 *DAG.getContext()); 4068 4069 // Reserve space for the linkage area on the stack. 4070 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4071 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4072 if (useSoftFloat()) 4073 CCInfo.PreAnalyzeFormalArguments(Ins); 4074 4075 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4076 CCInfo.clearWasPPCF128(); 4077 4078 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4079 CCValAssign &VA = ArgLocs[i]; 4080 4081 // Arguments stored in registers. 4082 if (VA.isRegLoc()) { 4083 const TargetRegisterClass *RC; 4084 EVT ValVT = VA.getValVT(); 4085 4086 switch (ValVT.getSimpleVT().SimpleTy) { 4087 default: 4088 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4089 case MVT::i1: 4090 case MVT::i32: 4091 RC = &PPC::GPRCRegClass; 4092 break; 4093 case MVT::f32: 4094 if (Subtarget.hasP8Vector()) 4095 RC = &PPC::VSSRCRegClass; 4096 else if (Subtarget.hasSPE()) 4097 RC = &PPC::GPRCRegClass; 4098 else 4099 RC = &PPC::F4RCRegClass; 4100 break; 4101 case MVT::f64: 4102 if (Subtarget.hasVSX()) 4103 RC = &PPC::VSFRCRegClass; 4104 else if (Subtarget.hasSPE()) 4105 // SPE passes doubles in GPR pairs. 4106 RC = &PPC::GPRCRegClass; 4107 else 4108 RC = &PPC::F8RCRegClass; 4109 break; 4110 case MVT::v16i8: 4111 case MVT::v8i16: 4112 case MVT::v4i32: 4113 RC = &PPC::VRRCRegClass; 4114 break; 4115 case MVT::v4f32: 4116 RC = &PPC::VRRCRegClass; 4117 break; 4118 case MVT::v2f64: 4119 case MVT::v2i64: 4120 RC = &PPC::VRRCRegClass; 4121 break; 4122 } 4123 4124 SDValue ArgValue; 4125 // Transform the arguments stored in physical registers into 4126 // virtual ones. 4127 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4128 assert(i + 1 < e && "No second half of double precision argument"); 4129 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4130 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4131 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4132 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4133 if (!Subtarget.isLittleEndian()) 4134 std::swap (ArgValueLo, ArgValueHi); 4135 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4136 ArgValueHi); 4137 } else { 4138 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 4139 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4140 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4141 if (ValVT == MVT::i1) 4142 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4143 } 4144 4145 InVals.push_back(ArgValue); 4146 } else { 4147 // Argument stored in memory. 4148 assert(VA.isMemLoc()); 4149 4150 // Get the extended size of the argument type in stack 4151 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4152 // Get the actual size of the argument type 4153 unsigned ObjSize = VA.getValVT().getStoreSize(); 4154 unsigned ArgOffset = VA.getLocMemOffset(); 4155 // Stack objects in PPC32 are right justified. 4156 ArgOffset += ArgSize - ObjSize; 4157 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4158 4159 // Create load nodes to retrieve arguments from the stack. 4160 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4161 InVals.push_back( 4162 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4163 } 4164 } 4165 4166 // Assign locations to all of the incoming aggregate by value arguments. 4167 // Aggregates passed by value are stored in the local variable space of the 4168 // caller's stack frame, right above the parameter list area. 4169 SmallVector<CCValAssign, 16> ByValArgLocs; 4170 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4171 ByValArgLocs, *DAG.getContext()); 4172 4173 // Reserve stack space for the allocations in CCInfo. 4174 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4175 4176 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4177 4178 // Area that is at least reserved in the caller of this function. 4179 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4180 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4181 4182 // Set the size that is at least reserved in caller of this function. Tail 4183 // call optimized function's reserved stack space needs to be aligned so that 4184 // taking the difference between two stack areas will result in an aligned 4185 // stack. 4186 MinReservedArea = 4187 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4188 FuncInfo->setMinReservedArea(MinReservedArea); 4189 4190 SmallVector<SDValue, 8> MemOps; 4191 4192 // If the function takes variable number of arguments, make a frame index for 4193 // the start of the first vararg value... for expansion of llvm.va_start. 4194 if (isVarArg) { 4195 static const MCPhysReg GPArgRegs[] = { 4196 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4197 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4198 }; 4199 const unsigned NumGPArgRegs = std::size(GPArgRegs); 4200 4201 static const MCPhysReg FPArgRegs[] = { 4202 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4203 PPC::F8 4204 }; 4205 unsigned NumFPArgRegs = std::size(FPArgRegs); 4206 4207 if (useSoftFloat() || hasSPE()) 4208 NumFPArgRegs = 0; 4209 4210 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4211 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4212 4213 // Make room for NumGPArgRegs and NumFPArgRegs. 4214 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4215 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4216 4217 FuncInfo->setVarArgsStackOffset( 4218 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4219 CCInfo.getNextStackOffset(), true)); 4220 4221 FuncInfo->setVarArgsFrameIndex( 4222 MFI.CreateStackObject(Depth, Align(8), false)); 4223 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4224 4225 // The fixed integer arguments of a variadic function are stored to the 4226 // VarArgsFrameIndex on the stack so that they may be loaded by 4227 // dereferencing the result of va_next. 4228 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4229 // Get an existing live-in vreg, or add a new one. 4230 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4231 if (!VReg) 4232 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4233 4234 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4235 SDValue Store = 4236 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4237 MemOps.push_back(Store); 4238 // Increment the address by four for the next argument to store 4239 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4240 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4241 } 4242 4243 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4244 // is set. 4245 // The double arguments are stored to the VarArgsFrameIndex 4246 // on the stack. 4247 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4248 // Get an existing live-in vreg, or add a new one. 4249 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4250 if (!VReg) 4251 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4252 4253 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4254 SDValue Store = 4255 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4256 MemOps.push_back(Store); 4257 // Increment the address by eight for the next argument to store 4258 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4259 PtrVT); 4260 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4261 } 4262 } 4263 4264 if (!MemOps.empty()) 4265 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4266 4267 return Chain; 4268 } 4269 4270 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4271 // value to MVT::i64 and then truncate to the correct register size. 4272 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4273 EVT ObjectVT, SelectionDAG &DAG, 4274 SDValue ArgVal, 4275 const SDLoc &dl) const { 4276 if (Flags.isSExt()) 4277 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4278 DAG.getValueType(ObjectVT)); 4279 else if (Flags.isZExt()) 4280 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4281 DAG.getValueType(ObjectVT)); 4282 4283 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4284 } 4285 4286 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4287 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4288 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4289 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4290 // TODO: add description of PPC stack frame format, or at least some docs. 4291 // 4292 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4293 bool isLittleEndian = Subtarget.isLittleEndian(); 4294 MachineFunction &MF = DAG.getMachineFunction(); 4295 MachineFrameInfo &MFI = MF.getFrameInfo(); 4296 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4297 4298 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4299 "fastcc not supported on varargs functions"); 4300 4301 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4302 // Potential tail calls could cause overwriting of argument stack slots. 4303 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4304 (CallConv == CallingConv::Fast)); 4305 unsigned PtrByteSize = 8; 4306 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4307 4308 static const MCPhysReg GPR[] = { 4309 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4310 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4311 }; 4312 static const MCPhysReg VR[] = { 4313 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4314 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4315 }; 4316 4317 const unsigned Num_GPR_Regs = std::size(GPR); 4318 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4319 const unsigned Num_VR_Regs = std::size(VR); 4320 4321 // Do a first pass over the arguments to determine whether the ABI 4322 // guarantees that our caller has allocated the parameter save area 4323 // on its stack frame. In the ELFv1 ABI, this is always the case; 4324 // in the ELFv2 ABI, it is true if this is a vararg function or if 4325 // any parameter is located in a stack slot. 4326 4327 bool HasParameterArea = !isELFv2ABI || isVarArg; 4328 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4329 unsigned NumBytes = LinkageSize; 4330 unsigned AvailableFPRs = Num_FPR_Regs; 4331 unsigned AvailableVRs = Num_VR_Regs; 4332 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4333 if (Ins[i].Flags.isNest()) 4334 continue; 4335 4336 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4337 PtrByteSize, LinkageSize, ParamAreaSize, 4338 NumBytes, AvailableFPRs, AvailableVRs)) 4339 HasParameterArea = true; 4340 } 4341 4342 // Add DAG nodes to load the arguments or copy them out of registers. On 4343 // entry to a function on PPC, the arguments start after the linkage area, 4344 // although the first ones are often in registers. 4345 4346 unsigned ArgOffset = LinkageSize; 4347 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4348 SmallVector<SDValue, 8> MemOps; 4349 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4350 unsigned CurArgIdx = 0; 4351 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4352 SDValue ArgVal; 4353 bool needsLoad = false; 4354 EVT ObjectVT = Ins[ArgNo].VT; 4355 EVT OrigVT = Ins[ArgNo].ArgVT; 4356 unsigned ObjSize = ObjectVT.getStoreSize(); 4357 unsigned ArgSize = ObjSize; 4358 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4359 if (Ins[ArgNo].isOrigArg()) { 4360 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4361 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4362 } 4363 // We re-align the argument offset for each argument, except when using the 4364 // fast calling convention, when we need to make sure we do that only when 4365 // we'll actually use a stack slot. 4366 unsigned CurArgOffset; 4367 Align Alignment; 4368 auto ComputeArgOffset = [&]() { 4369 /* Respect alignment of argument on the stack. */ 4370 Alignment = 4371 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4372 ArgOffset = alignTo(ArgOffset, Alignment); 4373 CurArgOffset = ArgOffset; 4374 }; 4375 4376 if (CallConv != CallingConv::Fast) { 4377 ComputeArgOffset(); 4378 4379 /* Compute GPR index associated with argument offset. */ 4380 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4381 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4382 } 4383 4384 // FIXME the codegen can be much improved in some cases. 4385 // We do not have to keep everything in memory. 4386 if (Flags.isByVal()) { 4387 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4388 4389 if (CallConv == CallingConv::Fast) 4390 ComputeArgOffset(); 4391 4392 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4393 ObjSize = Flags.getByValSize(); 4394 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4395 // Empty aggregate parameters do not take up registers. Examples: 4396 // struct { } a; 4397 // union { } b; 4398 // int c[0]; 4399 // etc. However, we have to provide a place-holder in InVals, so 4400 // pretend we have an 8-byte item at the current address for that 4401 // purpose. 4402 if (!ObjSize) { 4403 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4404 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4405 InVals.push_back(FIN); 4406 continue; 4407 } 4408 4409 // Create a stack object covering all stack doublewords occupied 4410 // by the argument. If the argument is (fully or partially) on 4411 // the stack, or if the argument is fully in registers but the 4412 // caller has allocated the parameter save anyway, we can refer 4413 // directly to the caller's stack frame. Otherwise, create a 4414 // local copy in our own frame. 4415 int FI; 4416 if (HasParameterArea || 4417 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4418 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4419 else 4420 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4421 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4422 4423 // Handle aggregates smaller than 8 bytes. 4424 if (ObjSize < PtrByteSize) { 4425 // The value of the object is its address, which differs from the 4426 // address of the enclosing doubleword on big-endian systems. 4427 SDValue Arg = FIN; 4428 if (!isLittleEndian) { 4429 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4430 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4431 } 4432 InVals.push_back(Arg); 4433 4434 if (GPR_idx != Num_GPR_Regs) { 4435 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4436 FuncInfo->addLiveInAttr(VReg, Flags); 4437 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4438 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4439 SDValue Store = 4440 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4441 MachinePointerInfo(&*FuncArg), ObjType); 4442 MemOps.push_back(Store); 4443 } 4444 // Whether we copied from a register or not, advance the offset 4445 // into the parameter save area by a full doubleword. 4446 ArgOffset += PtrByteSize; 4447 continue; 4448 } 4449 4450 // The value of the object is its address, which is the address of 4451 // its first stack doubleword. 4452 InVals.push_back(FIN); 4453 4454 // Store whatever pieces of the object are in registers to memory. 4455 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4456 if (GPR_idx == Num_GPR_Regs) 4457 break; 4458 4459 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4460 FuncInfo->addLiveInAttr(VReg, Flags); 4461 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4462 SDValue Addr = FIN; 4463 if (j) { 4464 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4465 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4466 } 4467 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8; 4468 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits); 4469 SDValue Store = 4470 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr, 4471 MachinePointerInfo(&*FuncArg, j), ObjType); 4472 MemOps.push_back(Store); 4473 ++GPR_idx; 4474 } 4475 ArgOffset += ArgSize; 4476 continue; 4477 } 4478 4479 switch (ObjectVT.getSimpleVT().SimpleTy) { 4480 default: llvm_unreachable("Unhandled argument type!"); 4481 case MVT::i1: 4482 case MVT::i32: 4483 case MVT::i64: 4484 if (Flags.isNest()) { 4485 // The 'nest' parameter, if any, is passed in R11. 4486 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4487 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4488 4489 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4490 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4491 4492 break; 4493 } 4494 4495 // These can be scalar arguments or elements of an integer array type 4496 // passed directly. Clang may use those instead of "byval" aggregate 4497 // types to avoid forcing arguments to memory unnecessarily. 4498 if (GPR_idx != Num_GPR_Regs) { 4499 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4500 FuncInfo->addLiveInAttr(VReg, Flags); 4501 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4502 4503 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4504 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4505 // value to MVT::i64 and then truncate to the correct register size. 4506 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4507 } else { 4508 if (CallConv == CallingConv::Fast) 4509 ComputeArgOffset(); 4510 4511 needsLoad = true; 4512 ArgSize = PtrByteSize; 4513 } 4514 if (CallConv != CallingConv::Fast || needsLoad) 4515 ArgOffset += 8; 4516 break; 4517 4518 case MVT::f32: 4519 case MVT::f64: 4520 // These can be scalar arguments or elements of a float array type 4521 // passed directly. The latter are used to implement ELFv2 homogenous 4522 // float aggregates. 4523 if (FPR_idx != Num_FPR_Regs) { 4524 unsigned VReg; 4525 4526 if (ObjectVT == MVT::f32) 4527 VReg = MF.addLiveIn(FPR[FPR_idx], 4528 Subtarget.hasP8Vector() 4529 ? &PPC::VSSRCRegClass 4530 : &PPC::F4RCRegClass); 4531 else 4532 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4533 ? &PPC::VSFRCRegClass 4534 : &PPC::F8RCRegClass); 4535 4536 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4537 ++FPR_idx; 4538 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4539 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4540 // once we support fp <-> gpr moves. 4541 4542 // This can only ever happen in the presence of f32 array types, 4543 // since otherwise we never run out of FPRs before running out 4544 // of GPRs. 4545 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4546 FuncInfo->addLiveInAttr(VReg, Flags); 4547 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4548 4549 if (ObjectVT == MVT::f32) { 4550 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4551 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4552 DAG.getConstant(32, dl, MVT::i32)); 4553 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4554 } 4555 4556 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4557 } else { 4558 if (CallConv == CallingConv::Fast) 4559 ComputeArgOffset(); 4560 4561 needsLoad = true; 4562 } 4563 4564 // When passing an array of floats, the array occupies consecutive 4565 // space in the argument area; only round up to the next doubleword 4566 // at the end of the array. Otherwise, each float takes 8 bytes. 4567 if (CallConv != CallingConv::Fast || needsLoad) { 4568 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4569 ArgOffset += ArgSize; 4570 if (Flags.isInConsecutiveRegsLast()) 4571 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4572 } 4573 break; 4574 case MVT::v4f32: 4575 case MVT::v4i32: 4576 case MVT::v8i16: 4577 case MVT::v16i8: 4578 case MVT::v2f64: 4579 case MVT::v2i64: 4580 case MVT::v1i128: 4581 case MVT::f128: 4582 // These can be scalar arguments or elements of a vector array type 4583 // passed directly. The latter are used to implement ELFv2 homogenous 4584 // vector aggregates. 4585 if (VR_idx != Num_VR_Regs) { 4586 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4587 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4588 ++VR_idx; 4589 } else { 4590 if (CallConv == CallingConv::Fast) 4591 ComputeArgOffset(); 4592 needsLoad = true; 4593 } 4594 if (CallConv != CallingConv::Fast || needsLoad) 4595 ArgOffset += 16; 4596 break; 4597 } 4598 4599 // We need to load the argument to a virtual register if we determined 4600 // above that we ran out of physical registers of the appropriate type. 4601 if (needsLoad) { 4602 if (ObjSize < ArgSize && !isLittleEndian) 4603 CurArgOffset += ArgSize - ObjSize; 4604 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4605 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4606 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4607 } 4608 4609 InVals.push_back(ArgVal); 4610 } 4611 4612 // Area that is at least reserved in the caller of this function. 4613 unsigned MinReservedArea; 4614 if (HasParameterArea) 4615 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4616 else 4617 MinReservedArea = LinkageSize; 4618 4619 // Set the size that is at least reserved in caller of this function. Tail 4620 // call optimized functions' reserved stack space needs to be aligned so that 4621 // taking the difference between two stack areas will result in an aligned 4622 // stack. 4623 MinReservedArea = 4624 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4625 FuncInfo->setMinReservedArea(MinReservedArea); 4626 4627 // If the function takes variable number of arguments, make a frame index for 4628 // the start of the first vararg value... for expansion of llvm.va_start. 4629 // On ELFv2ABI spec, it writes: 4630 // C programs that are intended to be *portable* across different compilers 4631 // and architectures must use the header file <stdarg.h> to deal with variable 4632 // argument lists. 4633 if (isVarArg && MFI.hasVAStart()) { 4634 int Depth = ArgOffset; 4635 4636 FuncInfo->setVarArgsFrameIndex( 4637 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4638 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4639 4640 // If this function is vararg, store any remaining integer argument regs 4641 // to their spots on the stack so that they may be loaded by dereferencing 4642 // the result of va_next. 4643 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4644 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4645 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4646 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4647 SDValue Store = 4648 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4649 MemOps.push_back(Store); 4650 // Increment the address by four for the next argument to store 4651 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4652 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4653 } 4654 } 4655 4656 if (!MemOps.empty()) 4657 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4658 4659 return Chain; 4660 } 4661 4662 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4663 /// adjusted to accommodate the arguments for the tailcall. 4664 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4665 unsigned ParamSize) { 4666 4667 if (!isTailCall) return 0; 4668 4669 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4670 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4671 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4672 // Remember only if the new adjustment is bigger. 4673 if (SPDiff < FI->getTailCallSPDelta()) 4674 FI->setTailCallSPDelta(SPDiff); 4675 4676 return SPDiff; 4677 } 4678 4679 static bool isFunctionGlobalAddress(SDValue Callee); 4680 4681 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4682 const TargetMachine &TM) { 4683 // It does not make sense to call callsShareTOCBase() with a caller that 4684 // is PC Relative since PC Relative callers do not have a TOC. 4685 #ifndef NDEBUG 4686 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4687 assert(!STICaller->isUsingPCRelativeCalls() && 4688 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4689 #endif 4690 4691 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4692 // don't have enough information to determine if the caller and callee share 4693 // the same TOC base, so we have to pessimistically assume they don't for 4694 // correctness. 4695 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4696 if (!G) 4697 return false; 4698 4699 const GlobalValue *GV = G->getGlobal(); 4700 4701 // If the callee is preemptable, then the static linker will use a plt-stub 4702 // which saves the toc to the stack, and needs a nop after the call 4703 // instruction to convert to a toc-restore. 4704 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4705 return false; 4706 4707 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4708 // We may need a TOC restore in the situation where the caller requires a 4709 // valid TOC but the callee is PC Relative and does not. 4710 const Function *F = dyn_cast<Function>(GV); 4711 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4712 4713 // If we have an Alias we can try to get the function from there. 4714 if (Alias) { 4715 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4716 F = dyn_cast<Function>(GlobalObj); 4717 } 4718 4719 // If we still have no valid function pointer we do not have enough 4720 // information to determine if the callee uses PC Relative calls so we must 4721 // assume that it does. 4722 if (!F) 4723 return false; 4724 4725 // If the callee uses PC Relative we cannot guarantee that the callee won't 4726 // clobber the TOC of the caller and so we must assume that the two 4727 // functions do not share a TOC base. 4728 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4729 if (STICallee->isUsingPCRelativeCalls()) 4730 return false; 4731 4732 // If the GV is not a strong definition then we need to assume it can be 4733 // replaced by another function at link time. The function that replaces 4734 // it may not share the same TOC as the caller since the callee may be 4735 // replaced by a PC Relative version of the same function. 4736 if (!GV->isStrongDefinitionForLinker()) 4737 return false; 4738 4739 // The medium and large code models are expected to provide a sufficiently 4740 // large TOC to provide all data addressing needs of a module with a 4741 // single TOC. 4742 if (CodeModel::Medium == TM.getCodeModel() || 4743 CodeModel::Large == TM.getCodeModel()) 4744 return true; 4745 4746 // Any explicitly-specified sections and section prefixes must also match. 4747 // Also, if we're using -ffunction-sections, then each function is always in 4748 // a different section (the same is true for COMDAT functions). 4749 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4750 GV->getSection() != Caller->getSection()) 4751 return false; 4752 if (const auto *F = dyn_cast<Function>(GV)) { 4753 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4754 return false; 4755 } 4756 4757 return true; 4758 } 4759 4760 static bool 4761 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4762 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4763 assert(Subtarget.is64BitELFABI()); 4764 4765 const unsigned PtrByteSize = 8; 4766 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4767 4768 static const MCPhysReg GPR[] = { 4769 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4770 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4771 }; 4772 static const MCPhysReg VR[] = { 4773 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4774 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4775 }; 4776 4777 const unsigned NumGPRs = std::size(GPR); 4778 const unsigned NumFPRs = 13; 4779 const unsigned NumVRs = std::size(VR); 4780 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4781 4782 unsigned NumBytes = LinkageSize; 4783 unsigned AvailableFPRs = NumFPRs; 4784 unsigned AvailableVRs = NumVRs; 4785 4786 for (const ISD::OutputArg& Param : Outs) { 4787 if (Param.Flags.isNest()) continue; 4788 4789 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4790 LinkageSize, ParamAreaSize, NumBytes, 4791 AvailableFPRs, AvailableVRs)) 4792 return true; 4793 } 4794 return false; 4795 } 4796 4797 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4798 if (CB.arg_size() != CallerFn->arg_size()) 4799 return false; 4800 4801 auto CalleeArgIter = CB.arg_begin(); 4802 auto CalleeArgEnd = CB.arg_end(); 4803 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4804 4805 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4806 const Value* CalleeArg = *CalleeArgIter; 4807 const Value* CallerArg = &(*CallerArgIter); 4808 if (CalleeArg == CallerArg) 4809 continue; 4810 4811 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4812 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4813 // } 4814 // 1st argument of callee is undef and has the same type as caller. 4815 if (CalleeArg->getType() == CallerArg->getType() && 4816 isa<UndefValue>(CalleeArg)) 4817 continue; 4818 4819 return false; 4820 } 4821 4822 return true; 4823 } 4824 4825 // Returns true if TCO is possible between the callers and callees 4826 // calling conventions. 4827 static bool 4828 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4829 CallingConv::ID CalleeCC) { 4830 // Tail calls are possible with fastcc and ccc. 4831 auto isTailCallableCC = [] (CallingConv::ID CC){ 4832 return CC == CallingConv::C || CC == CallingConv::Fast; 4833 }; 4834 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4835 return false; 4836 4837 // We can safely tail call both fastcc and ccc callees from a c calling 4838 // convention caller. If the caller is fastcc, we may have less stack space 4839 // than a non-fastcc caller with the same signature so disable tail-calls in 4840 // that case. 4841 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4842 } 4843 4844 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4845 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4846 const SmallVectorImpl<ISD::OutputArg> &Outs, 4847 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4848 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4849 4850 if (DisableSCO && !TailCallOpt) return false; 4851 4852 // Variadic argument functions are not supported. 4853 if (isVarArg) return false; 4854 4855 auto &Caller = DAG.getMachineFunction().getFunction(); 4856 // Check that the calling conventions are compatible for tco. 4857 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4858 return false; 4859 4860 // Caller contains any byval parameter is not supported. 4861 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4862 return false; 4863 4864 // Callee contains any byval parameter is not supported, too. 4865 // Note: This is a quick work around, because in some cases, e.g. 4866 // caller's stack size > callee's stack size, we are still able to apply 4867 // sibling call optimization. For example, gcc is able to do SCO for caller1 4868 // in the following example, but not for caller2. 4869 // struct test { 4870 // long int a; 4871 // char ary[56]; 4872 // } gTest; 4873 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4874 // b->a = v.a; 4875 // return 0; 4876 // } 4877 // void caller1(struct test a, struct test c, struct test *b) { 4878 // callee(gTest, b); } 4879 // void caller2(struct test *b) { callee(gTest, b); } 4880 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4881 return false; 4882 4883 // If callee and caller use different calling conventions, we cannot pass 4884 // parameters on stack since offsets for the parameter area may be different. 4885 if (Caller.getCallingConv() != CalleeCC && 4886 needStackSlotPassParameters(Subtarget, Outs)) 4887 return false; 4888 4889 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4890 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4891 // callee potentially have different TOC bases then we cannot tail call since 4892 // we need to restore the TOC pointer after the call. 4893 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4894 // We cannot guarantee this for indirect calls or calls to external functions. 4895 // When PC-Relative addressing is used, the concept of the TOC is no longer 4896 // applicable so this check is not required. 4897 // Check first for indirect calls. 4898 if (!Subtarget.isUsingPCRelativeCalls() && 4899 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4900 return false; 4901 4902 // Check if we share the TOC base. 4903 if (!Subtarget.isUsingPCRelativeCalls() && 4904 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4905 return false; 4906 4907 // TCO allows altering callee ABI, so we don't have to check further. 4908 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4909 return true; 4910 4911 if (DisableSCO) return false; 4912 4913 // If callee use the same argument list that caller is using, then we can 4914 // apply SCO on this case. If it is not, then we need to check if callee needs 4915 // stack for passing arguments. 4916 // PC Relative tail calls may not have a CallBase. 4917 // If there is no CallBase we cannot verify if we have the same argument 4918 // list so assume that we don't have the same argument list. 4919 if (CB && !hasSameArgumentList(&Caller, *CB) && 4920 needStackSlotPassParameters(Subtarget, Outs)) 4921 return false; 4922 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4923 return false; 4924 4925 return true; 4926 } 4927 4928 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4929 /// for tail call optimization. Targets which want to do tail call 4930 /// optimization should implement this function. 4931 bool 4932 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4933 CallingConv::ID CalleeCC, 4934 bool isVarArg, 4935 const SmallVectorImpl<ISD::InputArg> &Ins, 4936 SelectionDAG& DAG) const { 4937 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4938 return false; 4939 4940 // Variable argument functions are not supported. 4941 if (isVarArg) 4942 return false; 4943 4944 MachineFunction &MF = DAG.getMachineFunction(); 4945 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4946 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4947 // Functions containing by val parameters are not supported. 4948 for (unsigned i = 0; i != Ins.size(); i++) { 4949 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4950 if (Flags.isByVal()) return false; 4951 } 4952 4953 // Non-PIC/GOT tail calls are supported. 4954 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4955 return true; 4956 4957 // At the moment we can only do local tail calls (in same module, hidden 4958 // or protected) if we are generating PIC. 4959 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4960 return G->getGlobal()->hasHiddenVisibility() 4961 || G->getGlobal()->hasProtectedVisibility(); 4962 } 4963 4964 return false; 4965 } 4966 4967 /// isCallCompatibleAddress - Return the immediate to use if the specified 4968 /// 32-bit value is representable in the immediate field of a BxA instruction. 4969 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4970 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4971 if (!C) return nullptr; 4972 4973 int Addr = C->getZExtValue(); 4974 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4975 SignExtend32<26>(Addr) != Addr) 4976 return nullptr; // Top 6 bits have to be sext of immediate. 4977 4978 return DAG 4979 .getConstant( 4980 (int)C->getZExtValue() >> 2, SDLoc(Op), 4981 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4982 .getNode(); 4983 } 4984 4985 namespace { 4986 4987 struct TailCallArgumentInfo { 4988 SDValue Arg; 4989 SDValue FrameIdxOp; 4990 int FrameIdx = 0; 4991 4992 TailCallArgumentInfo() = default; 4993 }; 4994 4995 } // end anonymous namespace 4996 4997 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4998 static void StoreTailCallArgumentsToStackSlot( 4999 SelectionDAG &DAG, SDValue Chain, 5000 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5001 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5002 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5003 SDValue Arg = TailCallArgs[i].Arg; 5004 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5005 int FI = TailCallArgs[i].FrameIdx; 5006 // Store relative to framepointer. 5007 MemOpChains.push_back(DAG.getStore( 5008 Chain, dl, Arg, FIN, 5009 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5010 } 5011 } 5012 5013 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5014 /// the appropriate stack slot for the tail call optimized function call. 5015 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5016 SDValue OldRetAddr, SDValue OldFP, 5017 int SPDiff, const SDLoc &dl) { 5018 if (SPDiff) { 5019 // Calculate the new stack slot for the return address. 5020 MachineFunction &MF = DAG.getMachineFunction(); 5021 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5022 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5023 bool isPPC64 = Subtarget.isPPC64(); 5024 int SlotSize = isPPC64 ? 8 : 4; 5025 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5026 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5027 NewRetAddrLoc, true); 5028 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5029 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5030 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5031 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5032 } 5033 return Chain; 5034 } 5035 5036 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5037 /// the position of the argument. 5038 static void 5039 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5040 SDValue Arg, int SPDiff, unsigned ArgOffset, 5041 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5042 int Offset = ArgOffset + SPDiff; 5043 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5044 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5045 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5046 SDValue FIN = DAG.getFrameIndex(FI, VT); 5047 TailCallArgumentInfo Info; 5048 Info.Arg = Arg; 5049 Info.FrameIdxOp = FIN; 5050 Info.FrameIdx = FI; 5051 TailCallArguments.push_back(Info); 5052 } 5053 5054 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5055 /// stack slot. Returns the chain as result and the loaded frame pointers in 5056 /// LROpOut/FPOpout. Used when tail calling. 5057 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5058 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5059 SDValue &FPOpOut, const SDLoc &dl) const { 5060 if (SPDiff) { 5061 // Load the LR and FP stack slot for later adjusting. 5062 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5063 LROpOut = getReturnAddrFrameIndex(DAG); 5064 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5065 Chain = SDValue(LROpOut.getNode(), 1); 5066 } 5067 return Chain; 5068 } 5069 5070 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5071 /// by "Src" to address "Dst" of size "Size". Alignment information is 5072 /// specified by the specific parameter attribute. The copy will be passed as 5073 /// a byval function parameter. 5074 /// Sometimes what we are copying is the end of a larger object, the part that 5075 /// does not fit in registers. 5076 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5077 SDValue Chain, ISD::ArgFlagsTy Flags, 5078 SelectionDAG &DAG, const SDLoc &dl) { 5079 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5080 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5081 Flags.getNonZeroByValAlign(), false, false, false, 5082 MachinePointerInfo(), MachinePointerInfo()); 5083 } 5084 5085 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5086 /// tail calls. 5087 static void LowerMemOpCallTo( 5088 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5089 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5090 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5091 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5092 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5093 if (!isTailCall) { 5094 if (isVector) { 5095 SDValue StackPtr; 5096 if (isPPC64) 5097 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5098 else 5099 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5100 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5101 DAG.getConstant(ArgOffset, dl, PtrVT)); 5102 } 5103 MemOpChains.push_back( 5104 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5105 // Calculate and remember argument location. 5106 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5107 TailCallArguments); 5108 } 5109 5110 static void 5111 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5112 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5113 SDValue FPOp, 5114 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5115 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5116 // might overwrite each other in case of tail call optimization. 5117 SmallVector<SDValue, 8> MemOpChains2; 5118 // Do not flag preceding copytoreg stuff together with the following stuff. 5119 InFlag = SDValue(); 5120 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5121 MemOpChains2, dl); 5122 if (!MemOpChains2.empty()) 5123 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5124 5125 // Store the return address to the appropriate stack slot. 5126 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5127 5128 // Emit callseq_end just before tailcall node. 5129 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InFlag, dl); 5130 InFlag = Chain.getValue(1); 5131 } 5132 5133 // Is this global address that of a function that can be called by name? (as 5134 // opposed to something that must hold a descriptor for an indirect call). 5135 static bool isFunctionGlobalAddress(SDValue Callee) { 5136 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5137 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5138 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5139 return false; 5140 5141 return G->getGlobal()->getValueType()->isFunctionTy(); 5142 } 5143 5144 return false; 5145 } 5146 5147 SDValue PPCTargetLowering::LowerCallResult( 5148 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5149 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5150 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5151 SmallVector<CCValAssign, 16> RVLocs; 5152 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5153 *DAG.getContext()); 5154 5155 CCRetInfo.AnalyzeCallResult( 5156 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5157 ? RetCC_PPC_Cold 5158 : RetCC_PPC); 5159 5160 // Copy all of the result registers out of their specified physreg. 5161 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5162 CCValAssign &VA = RVLocs[i]; 5163 assert(VA.isRegLoc() && "Can only return in registers!"); 5164 5165 SDValue Val; 5166 5167 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5168 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5169 InFlag); 5170 Chain = Lo.getValue(1); 5171 InFlag = Lo.getValue(2); 5172 VA = RVLocs[++i]; // skip ahead to next loc 5173 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5174 InFlag); 5175 Chain = Hi.getValue(1); 5176 InFlag = Hi.getValue(2); 5177 if (!Subtarget.isLittleEndian()) 5178 std::swap (Lo, Hi); 5179 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5180 } else { 5181 Val = DAG.getCopyFromReg(Chain, dl, 5182 VA.getLocReg(), VA.getLocVT(), InFlag); 5183 Chain = Val.getValue(1); 5184 InFlag = Val.getValue(2); 5185 } 5186 5187 switch (VA.getLocInfo()) { 5188 default: llvm_unreachable("Unknown loc info!"); 5189 case CCValAssign::Full: break; 5190 case CCValAssign::AExt: 5191 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5192 break; 5193 case CCValAssign::ZExt: 5194 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5195 DAG.getValueType(VA.getValVT())); 5196 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5197 break; 5198 case CCValAssign::SExt: 5199 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5200 DAG.getValueType(VA.getValVT())); 5201 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5202 break; 5203 } 5204 5205 InVals.push_back(Val); 5206 } 5207 5208 return Chain; 5209 } 5210 5211 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5212 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5213 // PatchPoint calls are not indirect. 5214 if (isPatchPoint) 5215 return false; 5216 5217 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5218 return false; 5219 5220 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5221 // becuase the immediate function pointer points to a descriptor instead of 5222 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5223 // pointer immediate points to the global entry point, while the BLA would 5224 // need to jump to the local entry point (see rL211174). 5225 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5226 isBLACompatibleAddress(Callee, DAG)) 5227 return false; 5228 5229 return true; 5230 } 5231 5232 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5233 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5234 return Subtarget.isAIXABI() || 5235 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5236 } 5237 5238 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5239 const Function &Caller, const SDValue &Callee, 5240 const PPCSubtarget &Subtarget, 5241 const TargetMachine &TM, 5242 bool IsStrictFPCall = false) { 5243 if (CFlags.IsTailCall) 5244 return PPCISD::TC_RETURN; 5245 5246 unsigned RetOpc = 0; 5247 // This is a call through a function pointer. 5248 if (CFlags.IsIndirect) { 5249 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5250 // indirect calls. The save of the caller's TOC pointer to the stack will be 5251 // inserted into the DAG as part of call lowering. The restore of the TOC 5252 // pointer is modeled by using a pseudo instruction for the call opcode that 5253 // represents the 2 instruction sequence of an indirect branch and link, 5254 // immediately followed by a load of the TOC pointer from the the stack save 5255 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5256 // as it is not saved or used. 5257 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5258 : PPCISD::BCTRL; 5259 } else if (Subtarget.isUsingPCRelativeCalls()) { 5260 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5261 RetOpc = PPCISD::CALL_NOTOC; 5262 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5263 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5264 // immediately following the call instruction if the caller and callee may 5265 // have different TOC bases. At link time if the linker determines the calls 5266 // may not share a TOC base, the call is redirected to a trampoline inserted 5267 // by the linker. The trampoline will (among other things) save the callers 5268 // TOC pointer at an ABI designated offset in the linkage area and the 5269 // linker will rewrite the nop to be a load of the TOC pointer from the 5270 // linkage area into gpr2. 5271 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5272 : PPCISD::CALL_NOP; 5273 else 5274 RetOpc = PPCISD::CALL; 5275 if (IsStrictFPCall) { 5276 switch (RetOpc) { 5277 default: 5278 llvm_unreachable("Unknown call opcode"); 5279 case PPCISD::BCTRL_LOAD_TOC: 5280 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5281 break; 5282 case PPCISD::BCTRL: 5283 RetOpc = PPCISD::BCTRL_RM; 5284 break; 5285 case PPCISD::CALL_NOTOC: 5286 RetOpc = PPCISD::CALL_NOTOC_RM; 5287 break; 5288 case PPCISD::CALL: 5289 RetOpc = PPCISD::CALL_RM; 5290 break; 5291 case PPCISD::CALL_NOP: 5292 RetOpc = PPCISD::CALL_NOP_RM; 5293 break; 5294 } 5295 } 5296 return RetOpc; 5297 } 5298 5299 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5300 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5301 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5302 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5303 return SDValue(Dest, 0); 5304 5305 // Returns true if the callee is local, and false otherwise. 5306 auto isLocalCallee = [&]() { 5307 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5308 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5309 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5310 5311 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5312 !isa_and_nonnull<GlobalIFunc>(GV); 5313 }; 5314 5315 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5316 // a static relocation model causes some versions of GNU LD (2.17.50, at 5317 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5318 // built with secure-PLT. 5319 bool UsePlt = 5320 Subtarget.is32BitELFABI() && !isLocalCallee() && 5321 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5322 5323 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5324 const TargetMachine &TM = Subtarget.getTargetMachine(); 5325 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5326 MCSymbolXCOFF *S = 5327 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5328 5329 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5330 return DAG.getMCSymbol(S, PtrVT); 5331 }; 5332 5333 if (isFunctionGlobalAddress(Callee)) { 5334 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5335 5336 if (Subtarget.isAIXABI()) { 5337 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5338 return getAIXFuncEntryPointSymbolSDNode(GV); 5339 } 5340 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5341 UsePlt ? PPCII::MO_PLT : 0); 5342 } 5343 5344 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5345 const char *SymName = S->getSymbol(); 5346 if (Subtarget.isAIXABI()) { 5347 // If there exists a user-declared function whose name is the same as the 5348 // ExternalSymbol's, then we pick up the user-declared version. 5349 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5350 if (const Function *F = 5351 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5352 return getAIXFuncEntryPointSymbolSDNode(F); 5353 5354 // On AIX, direct function calls reference the symbol for the function's 5355 // entry point, which is named by prepending a "." before the function's 5356 // C-linkage name. A Qualname is returned here because an external 5357 // function entry point is a csect with XTY_ER property. 5358 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5359 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5360 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5361 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5362 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5363 return Sec->getQualNameSymbol(); 5364 }; 5365 5366 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5367 } 5368 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5369 UsePlt ? PPCII::MO_PLT : 0); 5370 } 5371 5372 // No transformation needed. 5373 assert(Callee.getNode() && "What no callee?"); 5374 return Callee; 5375 } 5376 5377 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5378 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5379 "Expected a CALLSEQ_STARTSDNode."); 5380 5381 // The last operand is the chain, except when the node has glue. If the node 5382 // has glue, then the last operand is the glue, and the chain is the second 5383 // last operand. 5384 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5385 if (LastValue.getValueType() != MVT::Glue) 5386 return LastValue; 5387 5388 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5389 } 5390 5391 // Creates the node that moves a functions address into the count register 5392 // to prepare for an indirect call instruction. 5393 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5394 SDValue &Glue, SDValue &Chain, 5395 const SDLoc &dl) { 5396 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5397 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5398 Chain = DAG.getNode(PPCISD::MTCTR, dl, ArrayRef(ReturnTypes, 2), 5399 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5400 // The glue is the second value produced. 5401 Glue = Chain.getValue(1); 5402 } 5403 5404 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5405 SDValue &Glue, SDValue &Chain, 5406 SDValue CallSeqStart, 5407 const CallBase *CB, const SDLoc &dl, 5408 bool hasNest, 5409 const PPCSubtarget &Subtarget) { 5410 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5411 // entry point, but to the function descriptor (the function entry point 5412 // address is part of the function descriptor though). 5413 // The function descriptor is a three doubleword structure with the 5414 // following fields: function entry point, TOC base address and 5415 // environment pointer. 5416 // Thus for a call through a function pointer, the following actions need 5417 // to be performed: 5418 // 1. Save the TOC of the caller in the TOC save area of its stack 5419 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5420 // 2. Load the address of the function entry point from the function 5421 // descriptor. 5422 // 3. Load the TOC of the callee from the function descriptor into r2. 5423 // 4. Load the environment pointer from the function descriptor into 5424 // r11. 5425 // 5. Branch to the function entry point address. 5426 // 6. On return of the callee, the TOC of the caller needs to be 5427 // restored (this is done in FinishCall()). 5428 // 5429 // The loads are scheduled at the beginning of the call sequence, and the 5430 // register copies are flagged together to ensure that no other 5431 // operations can be scheduled in between. E.g. without flagging the 5432 // copies together, a TOC access in the caller could be scheduled between 5433 // the assignment of the callee TOC and the branch to the callee, which leads 5434 // to incorrect code. 5435 5436 // Start by loading the function address from the descriptor. 5437 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5438 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5439 ? (MachineMemOperand::MODereferenceable | 5440 MachineMemOperand::MOInvariant) 5441 : MachineMemOperand::MONone; 5442 5443 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5444 5445 // Registers used in building the DAG. 5446 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5447 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5448 5449 // Offsets of descriptor members. 5450 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5451 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5452 5453 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5454 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 5455 5456 // One load for the functions entry point address. 5457 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5458 Alignment, MMOFlags); 5459 5460 // One for loading the TOC anchor for the module that contains the called 5461 // function. 5462 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5463 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5464 SDValue TOCPtr = 5465 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5466 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5467 5468 // One for loading the environment pointer. 5469 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5470 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5471 SDValue LoadEnvPtr = 5472 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5473 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5474 5475 5476 // Then copy the newly loaded TOC anchor to the TOC pointer. 5477 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5478 Chain = TOCVal.getValue(0); 5479 Glue = TOCVal.getValue(1); 5480 5481 // If the function call has an explicit 'nest' parameter, it takes the 5482 // place of the environment pointer. 5483 assert((!hasNest || !Subtarget.isAIXABI()) && 5484 "Nest parameter is not supported on AIX."); 5485 if (!hasNest) { 5486 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5487 Chain = EnvVal.getValue(0); 5488 Glue = EnvVal.getValue(1); 5489 } 5490 5491 // The rest of the indirect call sequence is the same as the non-descriptor 5492 // DAG. 5493 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5494 } 5495 5496 static void 5497 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5498 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5499 SelectionDAG &DAG, 5500 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5501 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5502 const PPCSubtarget &Subtarget) { 5503 const bool IsPPC64 = Subtarget.isPPC64(); 5504 // MVT for a general purpose register. 5505 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5506 5507 // First operand is always the chain. 5508 Ops.push_back(Chain); 5509 5510 // If it's a direct call pass the callee as the second operand. 5511 if (!CFlags.IsIndirect) 5512 Ops.push_back(Callee); 5513 else { 5514 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5515 5516 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5517 // on the stack (this would have been done in `LowerCall_64SVR4` or 5518 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5519 // represents both the indirect branch and a load that restores the TOC 5520 // pointer from the linkage area. The operand for the TOC restore is an add 5521 // of the TOC save offset to the stack pointer. This must be the second 5522 // operand: after the chain input but before any other variadic arguments. 5523 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5524 // saved or used. 5525 if (isTOCSaveRestoreRequired(Subtarget)) { 5526 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5527 5528 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5529 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5530 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5531 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5532 Ops.push_back(AddTOC); 5533 } 5534 5535 // Add the register used for the environment pointer. 5536 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5537 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5538 RegVT)); 5539 5540 5541 // Add CTR register as callee so a bctr can be emitted later. 5542 if (CFlags.IsTailCall) 5543 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5544 } 5545 5546 // If this is a tail call add stack pointer delta. 5547 if (CFlags.IsTailCall) 5548 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5549 5550 // Add argument registers to the end of the list so that they are known live 5551 // into the call. 5552 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5553 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5554 RegsToPass[i].second.getValueType())); 5555 5556 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5557 // no way to mark dependencies as implicit here. 5558 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5559 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5560 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5561 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5562 5563 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5564 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5565 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5566 5567 // Add a register mask operand representing the call-preserved registers. 5568 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5569 const uint32_t *Mask = 5570 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5571 assert(Mask && "Missing call preserved mask for calling convention"); 5572 Ops.push_back(DAG.getRegisterMask(Mask)); 5573 5574 // If the glue is valid, it is the last operand. 5575 if (Glue.getNode()) 5576 Ops.push_back(Glue); 5577 } 5578 5579 SDValue PPCTargetLowering::FinishCall( 5580 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5581 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5582 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5583 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5584 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5585 5586 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5587 Subtarget.isAIXABI()) 5588 setUsesTOCBasePtr(DAG); 5589 5590 unsigned CallOpc = 5591 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5592 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5593 5594 if (!CFlags.IsIndirect) 5595 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5596 else if (Subtarget.usesFunctionDescriptors()) 5597 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5598 dl, CFlags.HasNest, Subtarget); 5599 else 5600 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5601 5602 // Build the operand list for the call instruction. 5603 SmallVector<SDValue, 8> Ops; 5604 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5605 SPDiff, Subtarget); 5606 5607 // Emit tail call. 5608 if (CFlags.IsTailCall) { 5609 // Indirect tail call when using PC Relative calls do not have the same 5610 // constraints. 5611 assert(((Callee.getOpcode() == ISD::Register && 5612 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5613 Callee.getOpcode() == ISD::TargetExternalSymbol || 5614 Callee.getOpcode() == ISD::TargetGlobalAddress || 5615 isa<ConstantSDNode>(Callee) || 5616 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5617 "Expecting a global address, external symbol, absolute value, " 5618 "register or an indirect tail call when PC Relative calls are " 5619 "used."); 5620 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5621 assert(CallOpc == PPCISD::TC_RETURN && 5622 "Unexpected call opcode for a tail call."); 5623 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5624 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5625 } 5626 5627 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5628 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5629 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5630 Glue = Chain.getValue(1); 5631 5632 // When performing tail call optimization the callee pops its arguments off 5633 // the stack. Account for this here so these bytes can be pushed back on in 5634 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5635 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5636 getTargetMachine().Options.GuaranteedTailCallOpt) 5637 ? NumBytes 5638 : 0; 5639 5640 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl); 5641 Glue = Chain.getValue(1); 5642 5643 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5644 DAG, InVals); 5645 } 5646 5647 SDValue 5648 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5649 SmallVectorImpl<SDValue> &InVals) const { 5650 SelectionDAG &DAG = CLI.DAG; 5651 SDLoc &dl = CLI.DL; 5652 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5653 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5654 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5655 SDValue Chain = CLI.Chain; 5656 SDValue Callee = CLI.Callee; 5657 bool &isTailCall = CLI.IsTailCall; 5658 CallingConv::ID CallConv = CLI.CallConv; 5659 bool isVarArg = CLI.IsVarArg; 5660 bool isPatchPoint = CLI.IsPatchPoint; 5661 const CallBase *CB = CLI.CB; 5662 5663 if (isTailCall) { 5664 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5665 isTailCall = false; 5666 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5667 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5668 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5669 else 5670 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5671 Ins, DAG); 5672 if (isTailCall) { 5673 ++NumTailCalls; 5674 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5675 ++NumSiblingCalls; 5676 5677 // PC Relative calls no longer guarantee that the callee is a Global 5678 // Address Node. The callee could be an indirect tail call in which 5679 // case the SDValue for the callee could be a load (to load the address 5680 // of a function pointer) or it may be a register copy (to move the 5681 // address of the callee from a function parameter into a virtual 5682 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5683 assert((Subtarget.isUsingPCRelativeCalls() || 5684 isa<GlobalAddressSDNode>(Callee)) && 5685 "Callee should be an llvm::Function object."); 5686 5687 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5688 << "\nTCO callee: "); 5689 LLVM_DEBUG(Callee.dump()); 5690 } 5691 } 5692 5693 if (!isTailCall && CB && CB->isMustTailCall()) 5694 report_fatal_error("failed to perform tail call elimination on a call " 5695 "site marked musttail"); 5696 5697 // When long calls (i.e. indirect calls) are always used, calls are always 5698 // made via function pointer. If we have a function name, first translate it 5699 // into a pointer. 5700 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5701 !isTailCall) 5702 Callee = LowerGlobalAddress(Callee, DAG); 5703 5704 CallFlags CFlags( 5705 CallConv, isTailCall, isVarArg, isPatchPoint, 5706 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5707 // hasNest 5708 Subtarget.is64BitELFABI() && 5709 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5710 CLI.NoMerge); 5711 5712 if (Subtarget.isAIXABI()) 5713 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5714 InVals, CB); 5715 5716 assert(Subtarget.isSVR4ABI()); 5717 if (Subtarget.isPPC64()) 5718 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5719 InVals, CB); 5720 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5721 InVals, CB); 5722 } 5723 5724 SDValue PPCTargetLowering::LowerCall_32SVR4( 5725 SDValue Chain, SDValue Callee, CallFlags CFlags, 5726 const SmallVectorImpl<ISD::OutputArg> &Outs, 5727 const SmallVectorImpl<SDValue> &OutVals, 5728 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5729 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5730 const CallBase *CB) const { 5731 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5732 // of the 32-bit SVR4 ABI stack frame layout. 5733 5734 const CallingConv::ID CallConv = CFlags.CallConv; 5735 const bool IsVarArg = CFlags.IsVarArg; 5736 const bool IsTailCall = CFlags.IsTailCall; 5737 5738 assert((CallConv == CallingConv::C || 5739 CallConv == CallingConv::Cold || 5740 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5741 5742 const Align PtrAlign(4); 5743 5744 MachineFunction &MF = DAG.getMachineFunction(); 5745 5746 // Mark this function as potentially containing a function that contains a 5747 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5748 // and restoring the callers stack pointer in this functions epilog. This is 5749 // done because by tail calling the called function might overwrite the value 5750 // in this function's (MF) stack pointer stack slot 0(SP). 5751 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5752 CallConv == CallingConv::Fast) 5753 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5754 5755 // Count how many bytes are to be pushed on the stack, including the linkage 5756 // area, parameter list area and the part of the local variable space which 5757 // contains copies of aggregates which are passed by value. 5758 5759 // Assign locations to all of the outgoing arguments. 5760 SmallVector<CCValAssign, 16> ArgLocs; 5761 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5762 5763 // Reserve space for the linkage area on the stack. 5764 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5765 PtrAlign); 5766 if (useSoftFloat()) 5767 CCInfo.PreAnalyzeCallOperands(Outs); 5768 5769 if (IsVarArg) { 5770 // Handle fixed and variable vector arguments differently. 5771 // Fixed vector arguments go into registers as long as registers are 5772 // available. Variable vector arguments always go into memory. 5773 unsigned NumArgs = Outs.size(); 5774 5775 for (unsigned i = 0; i != NumArgs; ++i) { 5776 MVT ArgVT = Outs[i].VT; 5777 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5778 bool Result; 5779 5780 if (Outs[i].IsFixed) { 5781 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5782 CCInfo); 5783 } else { 5784 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5785 ArgFlags, CCInfo); 5786 } 5787 5788 if (Result) { 5789 #ifndef NDEBUG 5790 errs() << "Call operand #" << i << " has unhandled type " 5791 << EVT(ArgVT).getEVTString() << "\n"; 5792 #endif 5793 llvm_unreachable(nullptr); 5794 } 5795 } 5796 } else { 5797 // All arguments are treated the same. 5798 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5799 } 5800 CCInfo.clearWasPPCF128(); 5801 5802 // Assign locations to all of the outgoing aggregate by value arguments. 5803 SmallVector<CCValAssign, 16> ByValArgLocs; 5804 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5805 5806 // Reserve stack space for the allocations in CCInfo. 5807 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5808 5809 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5810 5811 // Size of the linkage area, parameter list area and the part of the local 5812 // space variable where copies of aggregates which are passed by value are 5813 // stored. 5814 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5815 5816 // Calculate by how many bytes the stack has to be adjusted in case of tail 5817 // call optimization. 5818 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5819 5820 // Adjust the stack pointer for the new arguments... 5821 // These operations are automatically eliminated by the prolog/epilog pass 5822 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5823 SDValue CallSeqStart = Chain; 5824 5825 // Load the return address and frame pointer so it can be moved somewhere else 5826 // later. 5827 SDValue LROp, FPOp; 5828 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5829 5830 // Set up a copy of the stack pointer for use loading and storing any 5831 // arguments that may not fit in the registers available for argument 5832 // passing. 5833 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5834 5835 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5836 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5837 SmallVector<SDValue, 8> MemOpChains; 5838 5839 bool seenFloatArg = false; 5840 // Walk the register/memloc assignments, inserting copies/loads. 5841 // i - Tracks the index into the list of registers allocated for the call 5842 // RealArgIdx - Tracks the index into the list of actual function arguments 5843 // j - Tracks the index into the list of byval arguments 5844 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5845 i != e; 5846 ++i, ++RealArgIdx) { 5847 CCValAssign &VA = ArgLocs[i]; 5848 SDValue Arg = OutVals[RealArgIdx]; 5849 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5850 5851 if (Flags.isByVal()) { 5852 // Argument is an aggregate which is passed by value, thus we need to 5853 // create a copy of it in the local variable space of the current stack 5854 // frame (which is the stack frame of the caller) and pass the address of 5855 // this copy to the callee. 5856 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5857 CCValAssign &ByValVA = ByValArgLocs[j++]; 5858 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5859 5860 // Memory reserved in the local variable space of the callers stack frame. 5861 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5862 5863 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5864 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5865 StackPtr, PtrOff); 5866 5867 // Create a copy of the argument in the local area of the current 5868 // stack frame. 5869 SDValue MemcpyCall = 5870 CreateCopyOfByValArgument(Arg, PtrOff, 5871 CallSeqStart.getNode()->getOperand(0), 5872 Flags, DAG, dl); 5873 5874 // This must go outside the CALLSEQ_START..END. 5875 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5876 SDLoc(MemcpyCall)); 5877 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5878 NewCallSeqStart.getNode()); 5879 Chain = CallSeqStart = NewCallSeqStart; 5880 5881 // Pass the address of the aggregate copy on the stack either in a 5882 // physical register or in the parameter list area of the current stack 5883 // frame to the callee. 5884 Arg = PtrOff; 5885 } 5886 5887 // When useCRBits() is true, there can be i1 arguments. 5888 // It is because getRegisterType(MVT::i1) => MVT::i1, 5889 // and for other integer types getRegisterType() => MVT::i32. 5890 // Extend i1 and ensure callee will get i32. 5891 if (Arg.getValueType() == MVT::i1) 5892 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5893 dl, MVT::i32, Arg); 5894 5895 if (VA.isRegLoc()) { 5896 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5897 // Put argument in a physical register. 5898 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5899 bool IsLE = Subtarget.isLittleEndian(); 5900 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5901 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5902 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5903 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5904 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5905 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5906 SVal.getValue(0))); 5907 } else 5908 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5909 } else { 5910 // Put argument in the parameter list area of the current stack frame. 5911 assert(VA.isMemLoc()); 5912 unsigned LocMemOffset = VA.getLocMemOffset(); 5913 5914 if (!IsTailCall) { 5915 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5916 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5917 StackPtr, PtrOff); 5918 5919 MemOpChains.push_back( 5920 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5921 } else { 5922 // Calculate and remember argument location. 5923 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5924 TailCallArguments); 5925 } 5926 } 5927 } 5928 5929 if (!MemOpChains.empty()) 5930 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5931 5932 // Build a sequence of copy-to-reg nodes chained together with token chain 5933 // and flag operands which copy the outgoing args into the appropriate regs. 5934 SDValue InFlag; 5935 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5936 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5937 RegsToPass[i].second, InFlag); 5938 InFlag = Chain.getValue(1); 5939 } 5940 5941 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5942 // registers. 5943 if (IsVarArg) { 5944 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5945 SDValue Ops[] = { Chain, InFlag }; 5946 5947 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl, 5948 VTs, ArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5949 5950 InFlag = Chain.getValue(1); 5951 } 5952 5953 if (IsTailCall) 5954 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5955 TailCallArguments); 5956 5957 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5958 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5959 } 5960 5961 // Copy an argument into memory, being careful to do this outside the 5962 // call sequence for the call to which the argument belongs. 5963 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5964 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5965 SelectionDAG &DAG, const SDLoc &dl) const { 5966 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5967 CallSeqStart.getNode()->getOperand(0), 5968 Flags, DAG, dl); 5969 // The MEMCPY must go outside the CALLSEQ_START..END. 5970 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5971 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5972 SDLoc(MemcpyCall)); 5973 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5974 NewCallSeqStart.getNode()); 5975 return NewCallSeqStart; 5976 } 5977 5978 SDValue PPCTargetLowering::LowerCall_64SVR4( 5979 SDValue Chain, SDValue Callee, CallFlags CFlags, 5980 const SmallVectorImpl<ISD::OutputArg> &Outs, 5981 const SmallVectorImpl<SDValue> &OutVals, 5982 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5983 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5984 const CallBase *CB) const { 5985 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5986 bool isLittleEndian = Subtarget.isLittleEndian(); 5987 unsigned NumOps = Outs.size(); 5988 bool IsSibCall = false; 5989 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5990 5991 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5992 unsigned PtrByteSize = 8; 5993 5994 MachineFunction &MF = DAG.getMachineFunction(); 5995 5996 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5997 IsSibCall = true; 5998 5999 // Mark this function as potentially containing a function that contains a 6000 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6001 // and restoring the callers stack pointer in this functions epilog. This is 6002 // done because by tail calling the called function might overwrite the value 6003 // in this function's (MF) stack pointer stack slot 0(SP). 6004 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6005 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6006 6007 assert(!(IsFastCall && CFlags.IsVarArg) && 6008 "fastcc not supported on varargs functions"); 6009 6010 // Count how many bytes are to be pushed on the stack, including the linkage 6011 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6012 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6013 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6014 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6015 unsigned NumBytes = LinkageSize; 6016 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6017 6018 static const MCPhysReg GPR[] = { 6019 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6020 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6021 }; 6022 static const MCPhysReg VR[] = { 6023 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6024 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6025 }; 6026 6027 const unsigned NumGPRs = std::size(GPR); 6028 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6029 const unsigned NumVRs = std::size(VR); 6030 6031 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6032 // can be passed to the callee in registers. 6033 // For the fast calling convention, there is another check below. 6034 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6035 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6036 if (!HasParameterArea) { 6037 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6038 unsigned AvailableFPRs = NumFPRs; 6039 unsigned AvailableVRs = NumVRs; 6040 unsigned NumBytesTmp = NumBytes; 6041 for (unsigned i = 0; i != NumOps; ++i) { 6042 if (Outs[i].Flags.isNest()) continue; 6043 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6044 PtrByteSize, LinkageSize, ParamAreaSize, 6045 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6046 HasParameterArea = true; 6047 } 6048 } 6049 6050 // When using the fast calling convention, we don't provide backing for 6051 // arguments that will be in registers. 6052 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6053 6054 // Avoid allocating parameter area for fastcc functions if all the arguments 6055 // can be passed in the registers. 6056 if (IsFastCall) 6057 HasParameterArea = false; 6058 6059 // Add up all the space actually used. 6060 for (unsigned i = 0; i != NumOps; ++i) { 6061 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6062 EVT ArgVT = Outs[i].VT; 6063 EVT OrigVT = Outs[i].ArgVT; 6064 6065 if (Flags.isNest()) 6066 continue; 6067 6068 if (IsFastCall) { 6069 if (Flags.isByVal()) { 6070 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6071 if (NumGPRsUsed > NumGPRs) 6072 HasParameterArea = true; 6073 } else { 6074 switch (ArgVT.getSimpleVT().SimpleTy) { 6075 default: llvm_unreachable("Unexpected ValueType for argument!"); 6076 case MVT::i1: 6077 case MVT::i32: 6078 case MVT::i64: 6079 if (++NumGPRsUsed <= NumGPRs) 6080 continue; 6081 break; 6082 case MVT::v4i32: 6083 case MVT::v8i16: 6084 case MVT::v16i8: 6085 case MVT::v2f64: 6086 case MVT::v2i64: 6087 case MVT::v1i128: 6088 case MVT::f128: 6089 if (++NumVRsUsed <= NumVRs) 6090 continue; 6091 break; 6092 case MVT::v4f32: 6093 if (++NumVRsUsed <= NumVRs) 6094 continue; 6095 break; 6096 case MVT::f32: 6097 case MVT::f64: 6098 if (++NumFPRsUsed <= NumFPRs) 6099 continue; 6100 break; 6101 } 6102 HasParameterArea = true; 6103 } 6104 } 6105 6106 /* Respect alignment of argument on the stack. */ 6107 auto Alignement = 6108 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6109 NumBytes = alignTo(NumBytes, Alignement); 6110 6111 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6112 if (Flags.isInConsecutiveRegsLast()) 6113 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6114 } 6115 6116 unsigned NumBytesActuallyUsed = NumBytes; 6117 6118 // In the old ELFv1 ABI, 6119 // the prolog code of the callee may store up to 8 GPR argument registers to 6120 // the stack, allowing va_start to index over them in memory if its varargs. 6121 // Because we cannot tell if this is needed on the caller side, we have to 6122 // conservatively assume that it is needed. As such, make sure we have at 6123 // least enough stack space for the caller to store the 8 GPRs. 6124 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6125 // really requires memory operands, e.g. a vararg function. 6126 if (HasParameterArea) 6127 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6128 else 6129 NumBytes = LinkageSize; 6130 6131 // Tail call needs the stack to be aligned. 6132 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6133 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6134 6135 int SPDiff = 0; 6136 6137 // Calculate by how many bytes the stack has to be adjusted in case of tail 6138 // call optimization. 6139 if (!IsSibCall) 6140 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6141 6142 // To protect arguments on the stack from being clobbered in a tail call, 6143 // force all the loads to happen before doing any other lowering. 6144 if (CFlags.IsTailCall) 6145 Chain = DAG.getStackArgumentTokenFactor(Chain); 6146 6147 // Adjust the stack pointer for the new arguments... 6148 // These operations are automatically eliminated by the prolog/epilog pass 6149 if (!IsSibCall) 6150 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6151 SDValue CallSeqStart = Chain; 6152 6153 // Load the return address and frame pointer so it can be move somewhere else 6154 // later. 6155 SDValue LROp, FPOp; 6156 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6157 6158 // Set up a copy of the stack pointer for use loading and storing any 6159 // arguments that may not fit in the registers available for argument 6160 // passing. 6161 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6162 6163 // Figure out which arguments are going to go in registers, and which in 6164 // memory. Also, if this is a vararg function, floating point operations 6165 // must be stored to our stack, and loaded into integer regs as well, if 6166 // any integer regs are available for argument passing. 6167 unsigned ArgOffset = LinkageSize; 6168 6169 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6170 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6171 6172 SmallVector<SDValue, 8> MemOpChains; 6173 for (unsigned i = 0; i != NumOps; ++i) { 6174 SDValue Arg = OutVals[i]; 6175 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6176 EVT ArgVT = Outs[i].VT; 6177 EVT OrigVT = Outs[i].ArgVT; 6178 6179 // PtrOff will be used to store the current argument to the stack if a 6180 // register cannot be found for it. 6181 SDValue PtrOff; 6182 6183 // We re-align the argument offset for each argument, except when using the 6184 // fast calling convention, when we need to make sure we do that only when 6185 // we'll actually use a stack slot. 6186 auto ComputePtrOff = [&]() { 6187 /* Respect alignment of argument on the stack. */ 6188 auto Alignment = 6189 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6190 ArgOffset = alignTo(ArgOffset, Alignment); 6191 6192 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6193 6194 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6195 }; 6196 6197 if (!IsFastCall) { 6198 ComputePtrOff(); 6199 6200 /* Compute GPR index associated with argument offset. */ 6201 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6202 GPR_idx = std::min(GPR_idx, NumGPRs); 6203 } 6204 6205 // Promote integers to 64-bit values. 6206 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6207 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6208 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6209 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6210 } 6211 6212 // FIXME memcpy is used way more than necessary. Correctness first. 6213 // Note: "by value" is code for passing a structure by value, not 6214 // basic types. 6215 if (Flags.isByVal()) { 6216 // Note: Size includes alignment padding, so 6217 // struct x { short a; char b; } 6218 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6219 // These are the proper values we need for right-justifying the 6220 // aggregate in a parameter register. 6221 unsigned Size = Flags.getByValSize(); 6222 6223 // An empty aggregate parameter takes up no storage and no 6224 // registers. 6225 if (Size == 0) 6226 continue; 6227 6228 if (IsFastCall) 6229 ComputePtrOff(); 6230 6231 // All aggregates smaller than 8 bytes must be passed right-justified. 6232 if (Size==1 || Size==2 || Size==4) { 6233 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6234 if (GPR_idx != NumGPRs) { 6235 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6236 MachinePointerInfo(), VT); 6237 MemOpChains.push_back(Load.getValue(1)); 6238 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6239 6240 ArgOffset += PtrByteSize; 6241 continue; 6242 } 6243 } 6244 6245 if (GPR_idx == NumGPRs && Size < 8) { 6246 SDValue AddPtr = PtrOff; 6247 if (!isLittleEndian) { 6248 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6249 PtrOff.getValueType()); 6250 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6251 } 6252 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6253 CallSeqStart, 6254 Flags, DAG, dl); 6255 ArgOffset += PtrByteSize; 6256 continue; 6257 } 6258 // Copy the object to parameter save area if it can not be entirely passed 6259 // by registers. 6260 // FIXME: we only need to copy the parts which need to be passed in 6261 // parameter save area. For the parts passed by registers, we don't need 6262 // to copy them to the stack although we need to allocate space for them 6263 // in parameter save area. 6264 if ((NumGPRs - GPR_idx) * PtrByteSize < Size) 6265 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6266 CallSeqStart, 6267 Flags, DAG, dl); 6268 6269 // When a register is available, pass a small aggregate right-justified. 6270 if (Size < 8 && GPR_idx != NumGPRs) { 6271 // The easiest way to get this right-justified in a register 6272 // is to copy the structure into the rightmost portion of a 6273 // local variable slot, then load the whole slot into the 6274 // register. 6275 // FIXME: The memcpy seems to produce pretty awful code for 6276 // small aggregates, particularly for packed ones. 6277 // FIXME: It would be preferable to use the slot in the 6278 // parameter save area instead of a new local variable. 6279 SDValue AddPtr = PtrOff; 6280 if (!isLittleEndian) { 6281 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6282 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6283 } 6284 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6285 CallSeqStart, 6286 Flags, DAG, dl); 6287 6288 // Load the slot into the register. 6289 SDValue Load = 6290 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6291 MemOpChains.push_back(Load.getValue(1)); 6292 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6293 6294 // Done with this argument. 6295 ArgOffset += PtrByteSize; 6296 continue; 6297 } 6298 6299 // For aggregates larger than PtrByteSize, copy the pieces of the 6300 // object that fit into registers from the parameter save area. 6301 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6302 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6303 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6304 if (GPR_idx != NumGPRs) { 6305 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8; 6306 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits); 6307 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg, 6308 MachinePointerInfo(), ObjType); 6309 6310 MemOpChains.push_back(Load.getValue(1)); 6311 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6312 ArgOffset += PtrByteSize; 6313 } else { 6314 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6315 break; 6316 } 6317 } 6318 continue; 6319 } 6320 6321 switch (Arg.getSimpleValueType().SimpleTy) { 6322 default: llvm_unreachable("Unexpected ValueType for argument!"); 6323 case MVT::i1: 6324 case MVT::i32: 6325 case MVT::i64: 6326 if (Flags.isNest()) { 6327 // The 'nest' parameter, if any, is passed in R11. 6328 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6329 break; 6330 } 6331 6332 // These can be scalar arguments or elements of an integer array type 6333 // passed directly. Clang may use those instead of "byval" aggregate 6334 // types to avoid forcing arguments to memory unnecessarily. 6335 if (GPR_idx != NumGPRs) { 6336 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6337 } else { 6338 if (IsFastCall) 6339 ComputePtrOff(); 6340 6341 assert(HasParameterArea && 6342 "Parameter area must exist to pass an argument in memory."); 6343 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6344 true, CFlags.IsTailCall, false, MemOpChains, 6345 TailCallArguments, dl); 6346 if (IsFastCall) 6347 ArgOffset += PtrByteSize; 6348 } 6349 if (!IsFastCall) 6350 ArgOffset += PtrByteSize; 6351 break; 6352 case MVT::f32: 6353 case MVT::f64: { 6354 // These can be scalar arguments or elements of a float array type 6355 // passed directly. The latter are used to implement ELFv2 homogenous 6356 // float aggregates. 6357 6358 // Named arguments go into FPRs first, and once they overflow, the 6359 // remaining arguments go into GPRs and then the parameter save area. 6360 // Unnamed arguments for vararg functions always go to GPRs and 6361 // then the parameter save area. For now, put all arguments to vararg 6362 // routines always in both locations (FPR *and* GPR or stack slot). 6363 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6364 bool NeededLoad = false; 6365 6366 // First load the argument into the next available FPR. 6367 if (FPR_idx != NumFPRs) 6368 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6369 6370 // Next, load the argument into GPR or stack slot if needed. 6371 if (!NeedGPROrStack) 6372 ; 6373 else if (GPR_idx != NumGPRs && !IsFastCall) { 6374 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6375 // once we support fp <-> gpr moves. 6376 6377 // In the non-vararg case, this can only ever happen in the 6378 // presence of f32 array types, since otherwise we never run 6379 // out of FPRs before running out of GPRs. 6380 SDValue ArgVal; 6381 6382 // Double values are always passed in a single GPR. 6383 if (Arg.getValueType() != MVT::f32) { 6384 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6385 6386 // Non-array float values are extended and passed in a GPR. 6387 } else if (!Flags.isInConsecutiveRegs()) { 6388 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6389 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6390 6391 // If we have an array of floats, we collect every odd element 6392 // together with its predecessor into one GPR. 6393 } else if (ArgOffset % PtrByteSize != 0) { 6394 SDValue Lo, Hi; 6395 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6396 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6397 if (!isLittleEndian) 6398 std::swap(Lo, Hi); 6399 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6400 6401 // The final element, if even, goes into the first half of a GPR. 6402 } else if (Flags.isInConsecutiveRegsLast()) { 6403 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6404 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6405 if (!isLittleEndian) 6406 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6407 DAG.getConstant(32, dl, MVT::i32)); 6408 6409 // Non-final even elements are skipped; they will be handled 6410 // together the with subsequent argument on the next go-around. 6411 } else 6412 ArgVal = SDValue(); 6413 6414 if (ArgVal.getNode()) 6415 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6416 } else { 6417 if (IsFastCall) 6418 ComputePtrOff(); 6419 6420 // Single-precision floating-point values are mapped to the 6421 // second (rightmost) word of the stack doubleword. 6422 if (Arg.getValueType() == MVT::f32 && 6423 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6424 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6425 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6426 } 6427 6428 assert(HasParameterArea && 6429 "Parameter area must exist to pass an argument in memory."); 6430 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6431 true, CFlags.IsTailCall, false, MemOpChains, 6432 TailCallArguments, dl); 6433 6434 NeededLoad = true; 6435 } 6436 // When passing an array of floats, the array occupies consecutive 6437 // space in the argument area; only round up to the next doubleword 6438 // at the end of the array. Otherwise, each float takes 8 bytes. 6439 if (!IsFastCall || NeededLoad) { 6440 ArgOffset += (Arg.getValueType() == MVT::f32 && 6441 Flags.isInConsecutiveRegs()) ? 4 : 8; 6442 if (Flags.isInConsecutiveRegsLast()) 6443 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6444 } 6445 break; 6446 } 6447 case MVT::v4f32: 6448 case MVT::v4i32: 6449 case MVT::v8i16: 6450 case MVT::v16i8: 6451 case MVT::v2f64: 6452 case MVT::v2i64: 6453 case MVT::v1i128: 6454 case MVT::f128: 6455 // These can be scalar arguments or elements of a vector array type 6456 // passed directly. The latter are used to implement ELFv2 homogenous 6457 // vector aggregates. 6458 6459 // For a varargs call, named arguments go into VRs or on the stack as 6460 // usual; unnamed arguments always go to the stack or the corresponding 6461 // GPRs when within range. For now, we always put the value in both 6462 // locations (or even all three). 6463 if (CFlags.IsVarArg) { 6464 assert(HasParameterArea && 6465 "Parameter area must exist if we have a varargs call."); 6466 // We could elide this store in the case where the object fits 6467 // entirely in R registers. Maybe later. 6468 SDValue Store = 6469 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6470 MemOpChains.push_back(Store); 6471 if (VR_idx != NumVRs) { 6472 SDValue Load = 6473 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6474 MemOpChains.push_back(Load.getValue(1)); 6475 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6476 } 6477 ArgOffset += 16; 6478 for (unsigned i=0; i<16; i+=PtrByteSize) { 6479 if (GPR_idx == NumGPRs) 6480 break; 6481 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6482 DAG.getConstant(i, dl, PtrVT)); 6483 SDValue Load = 6484 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6485 MemOpChains.push_back(Load.getValue(1)); 6486 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6487 } 6488 break; 6489 } 6490 6491 // Non-varargs Altivec params go into VRs or on the stack. 6492 if (VR_idx != NumVRs) { 6493 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6494 } else { 6495 if (IsFastCall) 6496 ComputePtrOff(); 6497 6498 assert(HasParameterArea && 6499 "Parameter area must exist to pass an argument in memory."); 6500 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6501 true, CFlags.IsTailCall, true, MemOpChains, 6502 TailCallArguments, dl); 6503 if (IsFastCall) 6504 ArgOffset += 16; 6505 } 6506 6507 if (!IsFastCall) 6508 ArgOffset += 16; 6509 break; 6510 } 6511 } 6512 6513 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6514 "mismatch in size of parameter area"); 6515 (void)NumBytesActuallyUsed; 6516 6517 if (!MemOpChains.empty()) 6518 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6519 6520 // Check if this is an indirect call (MTCTR/BCTRL). 6521 // See prepareDescriptorIndirectCall and buildCallOperands for more 6522 // information about calls through function pointers in the 64-bit SVR4 ABI. 6523 if (CFlags.IsIndirect) { 6524 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6525 // caller in the TOC save area. 6526 if (isTOCSaveRestoreRequired(Subtarget)) { 6527 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6528 // Load r2 into a virtual register and store it to the TOC save area. 6529 setUsesTOCBasePtr(DAG); 6530 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6531 // TOC save area offset. 6532 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6533 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6534 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6535 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6536 MachinePointerInfo::getStack( 6537 DAG.getMachineFunction(), TOCSaveOffset)); 6538 } 6539 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6540 // This does not mean the MTCTR instruction must use R12; it's easier 6541 // to model this as an extra parameter, so do that. 6542 if (isELFv2ABI && !CFlags.IsPatchPoint) 6543 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6544 } 6545 6546 // Build a sequence of copy-to-reg nodes chained together with token chain 6547 // and flag operands which copy the outgoing args into the appropriate regs. 6548 SDValue InFlag; 6549 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6550 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6551 RegsToPass[i].second, InFlag); 6552 InFlag = Chain.getValue(1); 6553 } 6554 6555 if (CFlags.IsTailCall && !IsSibCall) 6556 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6557 TailCallArguments); 6558 6559 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6560 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6561 } 6562 6563 // Returns true when the shadow of a general purpose argument register 6564 // in the parameter save area is aligned to at least 'RequiredAlign'. 6565 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6566 assert(RequiredAlign.value() <= 16 && 6567 "Required alignment greater than stack alignment."); 6568 switch (Reg) { 6569 default: 6570 report_fatal_error("called on invalid register."); 6571 case PPC::R5: 6572 case PPC::R9: 6573 case PPC::X3: 6574 case PPC::X5: 6575 case PPC::X7: 6576 case PPC::X9: 6577 // These registers are 16 byte aligned which is the most strict aligment 6578 // we can support. 6579 return true; 6580 case PPC::R3: 6581 case PPC::R7: 6582 case PPC::X4: 6583 case PPC::X6: 6584 case PPC::X8: 6585 case PPC::X10: 6586 // The shadow of these registers in the PSA is 8 byte aligned. 6587 return RequiredAlign <= 8; 6588 case PPC::R4: 6589 case PPC::R6: 6590 case PPC::R8: 6591 case PPC::R10: 6592 return RequiredAlign <= 4; 6593 } 6594 } 6595 6596 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6597 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6598 CCState &S) { 6599 AIXCCState &State = static_cast<AIXCCState &>(S); 6600 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6601 State.getMachineFunction().getSubtarget()); 6602 const bool IsPPC64 = Subtarget.isPPC64(); 6603 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6604 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6605 6606 if (ValVT == MVT::f128) 6607 report_fatal_error("f128 is unimplemented on AIX."); 6608 6609 if (ArgFlags.isNest()) 6610 report_fatal_error("Nest arguments are unimplemented."); 6611 6612 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6613 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6614 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6615 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6616 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6617 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6618 6619 static const MCPhysReg VR[] = {// Vector registers. 6620 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6621 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6622 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6623 6624 if (ArgFlags.isByVal()) { 6625 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6626 report_fatal_error("Pass-by-value arguments with alignment greater than " 6627 "register width are not supported."); 6628 6629 const unsigned ByValSize = ArgFlags.getByValSize(); 6630 6631 // An empty aggregate parameter takes up no storage and no registers, 6632 // but needs a MemLoc for a stack slot for the formal arguments side. 6633 if (ByValSize == 0) { 6634 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6635 State.getNextStackOffset(), RegVT, 6636 LocInfo)); 6637 return false; 6638 } 6639 6640 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6641 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6642 for (const unsigned E = Offset + StackSize; Offset < E; 6643 Offset += PtrAlign.value()) { 6644 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6645 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6646 else { 6647 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6648 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6649 LocInfo)); 6650 break; 6651 } 6652 } 6653 return false; 6654 } 6655 6656 // Arguments always reserve parameter save area. 6657 switch (ValVT.SimpleTy) { 6658 default: 6659 report_fatal_error("Unhandled value type for argument."); 6660 case MVT::i64: 6661 // i64 arguments should have been split to i32 for PPC32. 6662 assert(IsPPC64 && "PPC32 should have split i64 values."); 6663 [[fallthrough]]; 6664 case MVT::i1: 6665 case MVT::i32: { 6666 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6667 // AIX integer arguments are always passed in register width. 6668 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6669 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6670 : CCValAssign::LocInfo::ZExt; 6671 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6672 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6673 else 6674 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6675 6676 return false; 6677 } 6678 case MVT::f32: 6679 case MVT::f64: { 6680 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6681 const unsigned StoreSize = LocVT.getStoreSize(); 6682 // Floats are always 4-byte aligned in the PSA on AIX. 6683 // This includes f64 in 64-bit mode for ABI compatibility. 6684 const unsigned Offset = 6685 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6686 unsigned FReg = State.AllocateReg(FPR); 6687 if (FReg) 6688 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6689 6690 // Reserve and initialize GPRs or initialize the PSA as required. 6691 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6692 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6693 assert(FReg && "An FPR should be available when a GPR is reserved."); 6694 if (State.isVarArg()) { 6695 // Successfully reserved GPRs are only initialized for vararg calls. 6696 // Custom handling is required for: 6697 // f64 in PPC32 needs to be split into 2 GPRs. 6698 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6699 State.addLoc( 6700 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6701 } 6702 } else { 6703 // If there are insufficient GPRs, the PSA needs to be initialized. 6704 // Initialization occurs even if an FPR was initialized for 6705 // compatibility with the AIX XL compiler. The full memory for the 6706 // argument will be initialized even if a prior word is saved in GPR. 6707 // A custom memLoc is used when the argument also passes in FPR so 6708 // that the callee handling can skip over it easily. 6709 State.addLoc( 6710 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6711 LocInfo) 6712 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6713 break; 6714 } 6715 } 6716 6717 return false; 6718 } 6719 case MVT::v4f32: 6720 case MVT::v4i32: 6721 case MVT::v8i16: 6722 case MVT::v16i8: 6723 case MVT::v2i64: 6724 case MVT::v2f64: 6725 case MVT::v1i128: { 6726 const unsigned VecSize = 16; 6727 const Align VecAlign(VecSize); 6728 6729 if (!State.isVarArg()) { 6730 // If there are vector registers remaining we don't consume any stack 6731 // space. 6732 if (unsigned VReg = State.AllocateReg(VR)) { 6733 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6734 return false; 6735 } 6736 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6737 // might be allocated in the portion of the PSA that is shadowed by the 6738 // GPRs. 6739 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6740 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6741 return false; 6742 } 6743 6744 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6745 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6746 6747 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6748 // Burn any underaligned registers and their shadowed stack space until 6749 // we reach the required alignment. 6750 while (NextRegIndex != GPRs.size() && 6751 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6752 // Shadow allocate register and its stack shadow. 6753 unsigned Reg = State.AllocateReg(GPRs); 6754 State.AllocateStack(PtrSize, PtrAlign); 6755 assert(Reg && "Allocating register unexpectedly failed."); 6756 (void)Reg; 6757 NextRegIndex = State.getFirstUnallocated(GPRs); 6758 } 6759 6760 // Vectors that are passed as fixed arguments are handled differently. 6761 // They are passed in VRs if any are available (unlike arguments passed 6762 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6763 // functions) 6764 if (State.isFixed(ValNo)) { 6765 if (unsigned VReg = State.AllocateReg(VR)) { 6766 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6767 // Shadow allocate GPRs and stack space even though we pass in a VR. 6768 for (unsigned I = 0; I != VecSize; I += PtrSize) 6769 State.AllocateReg(GPRs); 6770 State.AllocateStack(VecSize, VecAlign); 6771 return false; 6772 } 6773 // No vector registers remain so pass on the stack. 6774 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6775 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6776 return false; 6777 } 6778 6779 // If all GPRS are consumed then we pass the argument fully on the stack. 6780 if (NextRegIndex == GPRs.size()) { 6781 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6782 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6783 return false; 6784 } 6785 6786 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6787 // half of the argument, and then need to pass the remaining half on the 6788 // stack. 6789 if (GPRs[NextRegIndex] == PPC::R9) { 6790 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6791 State.addLoc( 6792 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6793 6794 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6795 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6796 assert(FirstReg && SecondReg && 6797 "Allocating R9 or R10 unexpectedly failed."); 6798 State.addLoc( 6799 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6800 State.addLoc( 6801 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6802 return false; 6803 } 6804 6805 // We have enough GPRs to fully pass the vector argument, and we have 6806 // already consumed any underaligned registers. Start with the custom 6807 // MemLoc and then the custom RegLocs. 6808 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6809 State.addLoc( 6810 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6811 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6812 const unsigned Reg = State.AllocateReg(GPRs); 6813 assert(Reg && "Failed to allocated register for vararg vector argument"); 6814 State.addLoc( 6815 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6816 } 6817 return false; 6818 } 6819 } 6820 return true; 6821 } 6822 6823 // So far, this function is only used by LowerFormalArguments_AIX() 6824 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6825 bool IsPPC64, 6826 bool HasP8Vector, 6827 bool HasVSX) { 6828 assert((IsPPC64 || SVT != MVT::i64) && 6829 "i64 should have been split for 32-bit codegen."); 6830 6831 switch (SVT) { 6832 default: 6833 report_fatal_error("Unexpected value type for formal argument"); 6834 case MVT::i1: 6835 case MVT::i32: 6836 case MVT::i64: 6837 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6838 case MVT::f32: 6839 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6840 case MVT::f64: 6841 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6842 case MVT::v4f32: 6843 case MVT::v4i32: 6844 case MVT::v8i16: 6845 case MVT::v16i8: 6846 case MVT::v2i64: 6847 case MVT::v2f64: 6848 case MVT::v1i128: 6849 return &PPC::VRRCRegClass; 6850 } 6851 } 6852 6853 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6854 SelectionDAG &DAG, SDValue ArgValue, 6855 MVT LocVT, const SDLoc &dl) { 6856 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6857 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6858 6859 if (Flags.isSExt()) 6860 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6861 DAG.getValueType(ValVT)); 6862 else if (Flags.isZExt()) 6863 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6864 DAG.getValueType(ValVT)); 6865 6866 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6867 } 6868 6869 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6870 const unsigned LASize = FL->getLinkageSize(); 6871 6872 if (PPC::GPRCRegClass.contains(Reg)) { 6873 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6874 "Reg must be a valid argument register!"); 6875 return LASize + 4 * (Reg - PPC::R3); 6876 } 6877 6878 if (PPC::G8RCRegClass.contains(Reg)) { 6879 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6880 "Reg must be a valid argument register!"); 6881 return LASize + 8 * (Reg - PPC::X3); 6882 } 6883 6884 llvm_unreachable("Only general purpose registers expected."); 6885 } 6886 6887 // AIX ABI Stack Frame Layout: 6888 // 6889 // Low Memory +--------------------------------------------+ 6890 // SP +---> | Back chain | ---+ 6891 // | +--------------------------------------------+ | 6892 // | | Saved Condition Register | | 6893 // | +--------------------------------------------+ | 6894 // | | Saved Linkage Register | | 6895 // | +--------------------------------------------+ | Linkage Area 6896 // | | Reserved for compilers | | 6897 // | +--------------------------------------------+ | 6898 // | | Reserved for binders | | 6899 // | +--------------------------------------------+ | 6900 // | | Saved TOC pointer | ---+ 6901 // | +--------------------------------------------+ 6902 // | | Parameter save area | 6903 // | +--------------------------------------------+ 6904 // | | Alloca space | 6905 // | +--------------------------------------------+ 6906 // | | Local variable space | 6907 // | +--------------------------------------------+ 6908 // | | Float/int conversion temporary | 6909 // | +--------------------------------------------+ 6910 // | | Save area for AltiVec registers | 6911 // | +--------------------------------------------+ 6912 // | | AltiVec alignment padding | 6913 // | +--------------------------------------------+ 6914 // | | Save area for VRSAVE register | 6915 // | +--------------------------------------------+ 6916 // | | Save area for General Purpose registers | 6917 // | +--------------------------------------------+ 6918 // | | Save area for Floating Point registers | 6919 // | +--------------------------------------------+ 6920 // +---- | Back chain | 6921 // High Memory +--------------------------------------------+ 6922 // 6923 // Specifications: 6924 // AIX 7.2 Assembler Language Reference 6925 // Subroutine linkage convention 6926 6927 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6928 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6929 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6930 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6931 6932 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6933 CallConv == CallingConv::Fast) && 6934 "Unexpected calling convention!"); 6935 6936 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6937 report_fatal_error("Tail call support is unimplemented on AIX."); 6938 6939 if (useSoftFloat()) 6940 report_fatal_error("Soft float support is unimplemented on AIX."); 6941 6942 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 6943 6944 const bool IsPPC64 = Subtarget.isPPC64(); 6945 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6946 6947 // Assign locations to all of the incoming arguments. 6948 SmallVector<CCValAssign, 16> ArgLocs; 6949 MachineFunction &MF = DAG.getMachineFunction(); 6950 MachineFrameInfo &MFI = MF.getFrameInfo(); 6951 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6952 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6953 6954 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6955 // Reserve space for the linkage area on the stack. 6956 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6957 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6958 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6959 6960 SmallVector<SDValue, 8> MemOps; 6961 6962 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6963 CCValAssign &VA = ArgLocs[I++]; 6964 MVT LocVT = VA.getLocVT(); 6965 MVT ValVT = VA.getValVT(); 6966 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6967 // For compatibility with the AIX XL compiler, the float args in the 6968 // parameter save area are initialized even if the argument is available 6969 // in register. The caller is required to initialize both the register 6970 // and memory, however, the callee can choose to expect it in either. 6971 // The memloc is dismissed here because the argument is retrieved from 6972 // the register. 6973 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6974 continue; 6975 6976 auto HandleMemLoc = [&]() { 6977 const unsigned LocSize = LocVT.getStoreSize(); 6978 const unsigned ValSize = ValVT.getStoreSize(); 6979 assert((ValSize <= LocSize) && 6980 "Object size is larger than size of MemLoc"); 6981 int CurArgOffset = VA.getLocMemOffset(); 6982 // Objects are right-justified because AIX is big-endian. 6983 if (LocSize > ValSize) 6984 CurArgOffset += LocSize - ValSize; 6985 // Potential tail calls could cause overwriting of argument stack slots. 6986 const bool IsImmutable = 6987 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6988 (CallConv == CallingConv::Fast)); 6989 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6990 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6991 SDValue ArgValue = 6992 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6993 InVals.push_back(ArgValue); 6994 }; 6995 6996 // Vector arguments to VaArg functions are passed both on the stack, and 6997 // in any available GPRs. Load the value from the stack and add the GPRs 6998 // as live ins. 6999 if (VA.isMemLoc() && VA.needsCustom()) { 7000 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 7001 assert(isVarArg && "Only use custom memloc for vararg."); 7002 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 7003 // matching custom RegLocs. 7004 const unsigned OriginalValNo = VA.getValNo(); 7005 (void)OriginalValNo; 7006 7007 auto HandleCustomVecRegLoc = [&]() { 7008 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7009 "Missing custom RegLoc."); 7010 VA = ArgLocs[I++]; 7011 assert(VA.getValVT().isVector() && 7012 "Unexpected Val type for custom RegLoc."); 7013 assert(VA.getValNo() == OriginalValNo && 7014 "ValNo mismatch between custom MemLoc and RegLoc."); 7015 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 7016 MF.addLiveIn(VA.getLocReg(), 7017 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7018 Subtarget.hasVSX())); 7019 }; 7020 7021 HandleMemLoc(); 7022 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7023 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7024 // R10. 7025 HandleCustomVecRegLoc(); 7026 HandleCustomVecRegLoc(); 7027 7028 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 7029 // we passed the vector in R5, R6, R7 and R8. 7030 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 7031 assert(!IsPPC64 && 7032 "Only 2 custom RegLocs expected for 64-bit codegen."); 7033 HandleCustomVecRegLoc(); 7034 HandleCustomVecRegLoc(); 7035 } 7036 7037 continue; 7038 } 7039 7040 if (VA.isRegLoc()) { 7041 if (VA.getValVT().isScalarInteger()) 7042 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7043 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7044 switch (VA.getValVT().SimpleTy) { 7045 default: 7046 report_fatal_error("Unhandled value type for argument."); 7047 case MVT::f32: 7048 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7049 break; 7050 case MVT::f64: 7051 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7052 break; 7053 } 7054 } else if (VA.getValVT().isVector()) { 7055 switch (VA.getValVT().SimpleTy) { 7056 default: 7057 report_fatal_error("Unhandled value type for argument."); 7058 case MVT::v16i8: 7059 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7060 break; 7061 case MVT::v8i16: 7062 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7063 break; 7064 case MVT::v4i32: 7065 case MVT::v2i64: 7066 case MVT::v1i128: 7067 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7068 break; 7069 case MVT::v4f32: 7070 case MVT::v2f64: 7071 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7072 break; 7073 } 7074 } 7075 } 7076 7077 if (Flags.isByVal() && VA.isMemLoc()) { 7078 const unsigned Size = 7079 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7080 PtrByteSize); 7081 const int FI = MF.getFrameInfo().CreateFixedObject( 7082 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7083 /* IsAliased */ true); 7084 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7085 InVals.push_back(FIN); 7086 7087 continue; 7088 } 7089 7090 if (Flags.isByVal()) { 7091 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7092 7093 const MCPhysReg ArgReg = VA.getLocReg(); 7094 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7095 7096 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7097 report_fatal_error("Over aligned byvals not supported yet."); 7098 7099 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7100 const int FI = MF.getFrameInfo().CreateFixedObject( 7101 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7102 /* IsAliased */ true); 7103 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7104 InVals.push_back(FIN); 7105 7106 // Add live ins for all the RegLocs for the same ByVal. 7107 const TargetRegisterClass *RegClass = 7108 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7109 7110 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7111 unsigned Offset) { 7112 const Register VReg = MF.addLiveIn(PhysReg, RegClass); 7113 // Since the callers side has left justified the aggregate in the 7114 // register, we can simply store the entire register into the stack 7115 // slot. 7116 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7117 // The store to the fixedstack object is needed becuase accessing a 7118 // field of the ByVal will use a gep and load. Ideally we will optimize 7119 // to extracting the value from the register directly, and elide the 7120 // stores when the arguments address is not taken, but that will need to 7121 // be future work. 7122 SDValue Store = DAG.getStore( 7123 CopyFrom.getValue(1), dl, CopyFrom, 7124 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7125 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7126 7127 MemOps.push_back(Store); 7128 }; 7129 7130 unsigned Offset = 0; 7131 HandleRegLoc(VA.getLocReg(), Offset); 7132 Offset += PtrByteSize; 7133 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7134 Offset += PtrByteSize) { 7135 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7136 "RegLocs should be for ByVal argument."); 7137 7138 const CCValAssign RL = ArgLocs[I++]; 7139 HandleRegLoc(RL.getLocReg(), Offset); 7140 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7141 } 7142 7143 if (Offset != StackSize) { 7144 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7145 "Expected MemLoc for remaining bytes."); 7146 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7147 // Consume the MemLoc.The InVal has already been emitted, so nothing 7148 // more needs to be done. 7149 ++I; 7150 } 7151 7152 continue; 7153 } 7154 7155 if (VA.isRegLoc() && !VA.needsCustom()) { 7156 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7157 Register VReg = 7158 MF.addLiveIn(VA.getLocReg(), 7159 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7160 Subtarget.hasVSX())); 7161 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7162 if (ValVT.isScalarInteger() && 7163 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7164 ArgValue = 7165 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7166 } 7167 InVals.push_back(ArgValue); 7168 continue; 7169 } 7170 if (VA.isMemLoc()) { 7171 HandleMemLoc(); 7172 continue; 7173 } 7174 } 7175 7176 // On AIX a minimum of 8 words is saved to the parameter save area. 7177 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7178 // Area that is at least reserved in the caller of this function. 7179 unsigned CallerReservedArea = 7180 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7181 7182 // Set the size that is at least reserved in caller of this function. Tail 7183 // call optimized function's reserved stack space needs to be aligned so 7184 // that taking the difference between two stack areas will result in an 7185 // aligned stack. 7186 CallerReservedArea = 7187 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7188 FuncInfo->setMinReservedArea(CallerReservedArea); 7189 7190 if (isVarArg) { 7191 FuncInfo->setVarArgsFrameIndex( 7192 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7193 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7194 7195 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7196 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7197 7198 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7199 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7200 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32); 7201 7202 // The fixed integer arguments of a variadic function are stored to the 7203 // VarArgsFrameIndex on the stack so that they may be loaded by 7204 // dereferencing the result of va_next. 7205 for (unsigned GPRIndex = 7206 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7207 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7208 7209 const Register VReg = 7210 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7211 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7212 7213 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7214 SDValue Store = 7215 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7216 MemOps.push_back(Store); 7217 // Increment the address for the next argument to store. 7218 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7219 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7220 } 7221 } 7222 7223 if (!MemOps.empty()) 7224 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7225 7226 return Chain; 7227 } 7228 7229 SDValue PPCTargetLowering::LowerCall_AIX( 7230 SDValue Chain, SDValue Callee, CallFlags CFlags, 7231 const SmallVectorImpl<ISD::OutputArg> &Outs, 7232 const SmallVectorImpl<SDValue> &OutVals, 7233 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7234 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7235 const CallBase *CB) const { 7236 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7237 // AIX ABI stack frame layout. 7238 7239 assert((CFlags.CallConv == CallingConv::C || 7240 CFlags.CallConv == CallingConv::Cold || 7241 CFlags.CallConv == CallingConv::Fast) && 7242 "Unexpected calling convention!"); 7243 7244 if (CFlags.IsPatchPoint) 7245 report_fatal_error("This call type is unimplemented on AIX."); 7246 7247 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 7248 7249 MachineFunction &MF = DAG.getMachineFunction(); 7250 SmallVector<CCValAssign, 16> ArgLocs; 7251 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7252 *DAG.getContext()); 7253 7254 // Reserve space for the linkage save area (LSA) on the stack. 7255 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7256 // [SP][CR][LR][2 x reserved][TOC]. 7257 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7258 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7259 const bool IsPPC64 = Subtarget.isPPC64(); 7260 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7261 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7262 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7263 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7264 7265 // The prolog code of the callee may store up to 8 GPR argument registers to 7266 // the stack, allowing va_start to index over them in memory if the callee 7267 // is variadic. 7268 // Because we cannot tell if this is needed on the caller side, we have to 7269 // conservatively assume that it is needed. As such, make sure we have at 7270 // least enough stack space for the caller to store the 8 GPRs. 7271 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7272 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7273 CCInfo.getNextStackOffset()); 7274 7275 // Adjust the stack pointer for the new arguments... 7276 // These operations are automatically eliminated by the prolog/epilog pass. 7277 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7278 SDValue CallSeqStart = Chain; 7279 7280 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7281 SmallVector<SDValue, 8> MemOpChains; 7282 7283 // Set up a copy of the stack pointer for loading and storing any 7284 // arguments that may not fit in the registers available for argument 7285 // passing. 7286 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7287 : DAG.getRegister(PPC::R1, MVT::i32); 7288 7289 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7290 const unsigned ValNo = ArgLocs[I].getValNo(); 7291 SDValue Arg = OutVals[ValNo]; 7292 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7293 7294 if (Flags.isByVal()) { 7295 const unsigned ByValSize = Flags.getByValSize(); 7296 7297 // Nothing to do for zero-sized ByVals on the caller side. 7298 if (!ByValSize) { 7299 ++I; 7300 continue; 7301 } 7302 7303 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7304 return DAG.getExtLoad( 7305 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7306 (LoadOffset != 0) 7307 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7308 : Arg, 7309 MachinePointerInfo(), VT); 7310 }; 7311 7312 unsigned LoadOffset = 0; 7313 7314 // Initialize registers, which are fully occupied by the by-val argument. 7315 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7316 SDValue Load = GetLoad(PtrVT, LoadOffset); 7317 MemOpChains.push_back(Load.getValue(1)); 7318 LoadOffset += PtrByteSize; 7319 const CCValAssign &ByValVA = ArgLocs[I++]; 7320 assert(ByValVA.getValNo() == ValNo && 7321 "Unexpected location for pass-by-value argument."); 7322 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7323 } 7324 7325 if (LoadOffset == ByValSize) 7326 continue; 7327 7328 // There must be one more loc to handle the remainder. 7329 assert(ArgLocs[I].getValNo() == ValNo && 7330 "Expected additional location for by-value argument."); 7331 7332 if (ArgLocs[I].isMemLoc()) { 7333 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7334 const CCValAssign &ByValVA = ArgLocs[I++]; 7335 ISD::ArgFlagsTy MemcpyFlags = Flags; 7336 // Only memcpy the bytes that don't pass in register. 7337 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7338 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7339 (LoadOffset != 0) 7340 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7341 : Arg, 7342 DAG.getObjectPtrOffset(dl, StackPtr, 7343 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7344 CallSeqStart, MemcpyFlags, DAG, dl); 7345 continue; 7346 } 7347 7348 // Initialize the final register residue. 7349 // Any residue that occupies the final by-val arg register must be 7350 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7351 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7352 // 2 and 1 byte loads. 7353 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7354 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7355 "Unexpected register residue for by-value argument."); 7356 SDValue ResidueVal; 7357 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7358 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7359 const MVT VT = 7360 N == 1 ? MVT::i8 7361 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7362 SDValue Load = GetLoad(VT, LoadOffset); 7363 MemOpChains.push_back(Load.getValue(1)); 7364 LoadOffset += N; 7365 Bytes += N; 7366 7367 // By-val arguments are passed left-justfied in register. 7368 // Every load here needs to be shifted, otherwise a full register load 7369 // should have been used. 7370 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7371 "Unexpected load emitted during handling of pass-by-value " 7372 "argument."); 7373 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7374 EVT ShiftAmountTy = 7375 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7376 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7377 SDValue ShiftedLoad = 7378 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7379 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7380 ShiftedLoad) 7381 : ShiftedLoad; 7382 } 7383 7384 const CCValAssign &ByValVA = ArgLocs[I++]; 7385 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7386 continue; 7387 } 7388 7389 CCValAssign &VA = ArgLocs[I++]; 7390 const MVT LocVT = VA.getLocVT(); 7391 const MVT ValVT = VA.getValVT(); 7392 7393 switch (VA.getLocInfo()) { 7394 default: 7395 report_fatal_error("Unexpected argument extension type."); 7396 case CCValAssign::Full: 7397 break; 7398 case CCValAssign::ZExt: 7399 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7400 break; 7401 case CCValAssign::SExt: 7402 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7403 break; 7404 } 7405 7406 if (VA.isRegLoc() && !VA.needsCustom()) { 7407 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7408 continue; 7409 } 7410 7411 // Vector arguments passed to VarArg functions need custom handling when 7412 // they are passed (at least partially) in GPRs. 7413 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7414 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7415 // Store value to its stack slot. 7416 SDValue PtrOff = 7417 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7418 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7419 SDValue Store = 7420 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7421 MemOpChains.push_back(Store); 7422 const unsigned OriginalValNo = VA.getValNo(); 7423 // Then load the GPRs from the stack 7424 unsigned LoadOffset = 0; 7425 auto HandleCustomVecRegLoc = [&]() { 7426 assert(I != E && "Unexpected end of CCvalAssigns."); 7427 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7428 "Expected custom RegLoc."); 7429 CCValAssign RegVA = ArgLocs[I++]; 7430 assert(RegVA.getValNo() == OriginalValNo && 7431 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7432 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7433 DAG.getConstant(LoadOffset, dl, PtrVT)); 7434 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7435 MemOpChains.push_back(Load.getValue(1)); 7436 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7437 LoadOffset += PtrByteSize; 7438 }; 7439 7440 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7441 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7442 // R10. 7443 HandleCustomVecRegLoc(); 7444 HandleCustomVecRegLoc(); 7445 7446 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7447 ArgLocs[I].getValNo() == OriginalValNo) { 7448 assert(!IsPPC64 && 7449 "Only 2 custom RegLocs expected for 64-bit codegen."); 7450 HandleCustomVecRegLoc(); 7451 HandleCustomVecRegLoc(); 7452 } 7453 7454 continue; 7455 } 7456 7457 if (VA.isMemLoc()) { 7458 SDValue PtrOff = 7459 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7460 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7461 MemOpChains.push_back( 7462 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7463 7464 continue; 7465 } 7466 7467 if (!ValVT.isFloatingPoint()) 7468 report_fatal_error( 7469 "Unexpected register handling for calling convention."); 7470 7471 // Custom handling is used for GPR initializations for vararg float 7472 // arguments. 7473 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7474 LocVT.isInteger() && 7475 "Custom register handling only expected for VarArg."); 7476 7477 SDValue ArgAsInt = 7478 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7479 7480 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7481 // f32 in 32-bit GPR 7482 // f64 in 64-bit GPR 7483 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7484 else if (Arg.getValueType().getFixedSizeInBits() < 7485 LocVT.getFixedSizeInBits()) 7486 // f32 in 64-bit GPR. 7487 RegsToPass.push_back(std::make_pair( 7488 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7489 else { 7490 // f64 in two 32-bit GPRs 7491 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7492 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7493 "Unexpected custom register for argument!"); 7494 CCValAssign &GPR1 = VA; 7495 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7496 DAG.getConstant(32, dl, MVT::i8)); 7497 RegsToPass.push_back(std::make_pair( 7498 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7499 7500 if (I != E) { 7501 // If only 1 GPR was available, there will only be one custom GPR and 7502 // the argument will also pass in memory. 7503 CCValAssign &PeekArg = ArgLocs[I]; 7504 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7505 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7506 CCValAssign &GPR2 = ArgLocs[I++]; 7507 RegsToPass.push_back(std::make_pair( 7508 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7509 } 7510 } 7511 } 7512 } 7513 7514 if (!MemOpChains.empty()) 7515 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7516 7517 // For indirect calls, we need to save the TOC base to the stack for 7518 // restoration after the call. 7519 if (CFlags.IsIndirect) { 7520 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7521 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7522 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7523 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7524 const unsigned TOCSaveOffset = 7525 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7526 7527 setUsesTOCBasePtr(DAG); 7528 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7529 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7530 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7531 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7532 Chain = DAG.getStore( 7533 Val.getValue(1), dl, Val, AddPtr, 7534 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7535 } 7536 7537 // Build a sequence of copy-to-reg nodes chained together with token chain 7538 // and flag operands which copy the outgoing args into the appropriate regs. 7539 SDValue InFlag; 7540 for (auto Reg : RegsToPass) { 7541 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7542 InFlag = Chain.getValue(1); 7543 } 7544 7545 const int SPDiff = 0; 7546 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7547 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7548 } 7549 7550 bool 7551 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7552 MachineFunction &MF, bool isVarArg, 7553 const SmallVectorImpl<ISD::OutputArg> &Outs, 7554 LLVMContext &Context) const { 7555 SmallVector<CCValAssign, 16> RVLocs; 7556 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7557 return CCInfo.CheckReturn( 7558 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7559 ? RetCC_PPC_Cold 7560 : RetCC_PPC); 7561 } 7562 7563 SDValue 7564 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7565 bool isVarArg, 7566 const SmallVectorImpl<ISD::OutputArg> &Outs, 7567 const SmallVectorImpl<SDValue> &OutVals, 7568 const SDLoc &dl, SelectionDAG &DAG) const { 7569 SmallVector<CCValAssign, 16> RVLocs; 7570 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7571 *DAG.getContext()); 7572 CCInfo.AnalyzeReturn(Outs, 7573 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7574 ? RetCC_PPC_Cold 7575 : RetCC_PPC); 7576 7577 SDValue Flag; 7578 SmallVector<SDValue, 4> RetOps(1, Chain); 7579 7580 // Copy the result values into the output registers. 7581 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7582 CCValAssign &VA = RVLocs[i]; 7583 assert(VA.isRegLoc() && "Can only return in registers!"); 7584 7585 SDValue Arg = OutVals[RealResIdx]; 7586 7587 switch (VA.getLocInfo()) { 7588 default: llvm_unreachable("Unknown loc info!"); 7589 case CCValAssign::Full: break; 7590 case CCValAssign::AExt: 7591 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7592 break; 7593 case CCValAssign::ZExt: 7594 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7595 break; 7596 case CCValAssign::SExt: 7597 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7598 break; 7599 } 7600 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7601 bool isLittleEndian = Subtarget.isLittleEndian(); 7602 // Legalize ret f64 -> ret 2 x i32. 7603 SDValue SVal = 7604 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7605 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7606 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7607 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7608 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7609 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7610 Flag = Chain.getValue(1); 7611 VA = RVLocs[++i]; // skip ahead to next loc 7612 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7613 } else 7614 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7615 Flag = Chain.getValue(1); 7616 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7617 } 7618 7619 RetOps[0] = Chain; // Update chain. 7620 7621 // Add the flag if we have it. 7622 if (Flag.getNode()) 7623 RetOps.push_back(Flag); 7624 7625 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7626 } 7627 7628 SDValue 7629 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7630 SelectionDAG &DAG) const { 7631 SDLoc dl(Op); 7632 7633 // Get the correct type for integers. 7634 EVT IntVT = Op.getValueType(); 7635 7636 // Get the inputs. 7637 SDValue Chain = Op.getOperand(0); 7638 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7639 // Build a DYNAREAOFFSET node. 7640 SDValue Ops[2] = {Chain, FPSIdx}; 7641 SDVTList VTs = DAG.getVTList(IntVT); 7642 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7643 } 7644 7645 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7646 SelectionDAG &DAG) const { 7647 // When we pop the dynamic allocation we need to restore the SP link. 7648 SDLoc dl(Op); 7649 7650 // Get the correct type for pointers. 7651 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7652 7653 // Construct the stack pointer operand. 7654 bool isPPC64 = Subtarget.isPPC64(); 7655 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7656 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7657 7658 // Get the operands for the STACKRESTORE. 7659 SDValue Chain = Op.getOperand(0); 7660 SDValue SaveSP = Op.getOperand(1); 7661 7662 // Load the old link SP. 7663 SDValue LoadLinkSP = 7664 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7665 7666 // Restore the stack pointer. 7667 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7668 7669 // Store the old link SP. 7670 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7671 } 7672 7673 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7674 MachineFunction &MF = DAG.getMachineFunction(); 7675 bool isPPC64 = Subtarget.isPPC64(); 7676 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7677 7678 // Get current frame pointer save index. The users of this index will be 7679 // primarily DYNALLOC instructions. 7680 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7681 int RASI = FI->getReturnAddrSaveIndex(); 7682 7683 // If the frame pointer save index hasn't been defined yet. 7684 if (!RASI) { 7685 // Find out what the fix offset of the frame pointer save area. 7686 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7687 // Allocate the frame index for frame pointer save area. 7688 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7689 // Save the result. 7690 FI->setReturnAddrSaveIndex(RASI); 7691 } 7692 return DAG.getFrameIndex(RASI, PtrVT); 7693 } 7694 7695 SDValue 7696 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7697 MachineFunction &MF = DAG.getMachineFunction(); 7698 bool isPPC64 = Subtarget.isPPC64(); 7699 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7700 7701 // Get current frame pointer save index. The users of this index will be 7702 // primarily DYNALLOC instructions. 7703 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7704 int FPSI = FI->getFramePointerSaveIndex(); 7705 7706 // If the frame pointer save index hasn't been defined yet. 7707 if (!FPSI) { 7708 // Find out what the fix offset of the frame pointer save area. 7709 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7710 // Allocate the frame index for frame pointer save area. 7711 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7712 // Save the result. 7713 FI->setFramePointerSaveIndex(FPSI); 7714 } 7715 return DAG.getFrameIndex(FPSI, PtrVT); 7716 } 7717 7718 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7719 SelectionDAG &DAG) const { 7720 MachineFunction &MF = DAG.getMachineFunction(); 7721 // Get the inputs. 7722 SDValue Chain = Op.getOperand(0); 7723 SDValue Size = Op.getOperand(1); 7724 SDLoc dl(Op); 7725 7726 // Get the correct type for pointers. 7727 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7728 // Negate the size. 7729 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7730 DAG.getConstant(0, dl, PtrVT), Size); 7731 // Construct a node for the frame pointer save index. 7732 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7733 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7734 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7735 if (hasInlineStackProbe(MF)) 7736 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7737 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7738 } 7739 7740 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7741 SelectionDAG &DAG) const { 7742 MachineFunction &MF = DAG.getMachineFunction(); 7743 7744 bool isPPC64 = Subtarget.isPPC64(); 7745 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7746 7747 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7748 return DAG.getFrameIndex(FI, PtrVT); 7749 } 7750 7751 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7752 SelectionDAG &DAG) const { 7753 SDLoc DL(Op); 7754 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7755 DAG.getVTList(MVT::i32, MVT::Other), 7756 Op.getOperand(0), Op.getOperand(1)); 7757 } 7758 7759 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7760 SelectionDAG &DAG) const { 7761 SDLoc DL(Op); 7762 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7763 Op.getOperand(0), Op.getOperand(1)); 7764 } 7765 7766 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7767 if (Op.getValueType().isVector()) 7768 return LowerVectorLoad(Op, DAG); 7769 7770 assert(Op.getValueType() == MVT::i1 && 7771 "Custom lowering only for i1 loads"); 7772 7773 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7774 7775 SDLoc dl(Op); 7776 LoadSDNode *LD = cast<LoadSDNode>(Op); 7777 7778 SDValue Chain = LD->getChain(); 7779 SDValue BasePtr = LD->getBasePtr(); 7780 MachineMemOperand *MMO = LD->getMemOperand(); 7781 7782 SDValue NewLD = 7783 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7784 BasePtr, MVT::i8, MMO); 7785 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7786 7787 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7788 return DAG.getMergeValues(Ops, dl); 7789 } 7790 7791 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7792 if (Op.getOperand(1).getValueType().isVector()) 7793 return LowerVectorStore(Op, DAG); 7794 7795 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7796 "Custom lowering only for i1 stores"); 7797 7798 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7799 7800 SDLoc dl(Op); 7801 StoreSDNode *ST = cast<StoreSDNode>(Op); 7802 7803 SDValue Chain = ST->getChain(); 7804 SDValue BasePtr = ST->getBasePtr(); 7805 SDValue Value = ST->getValue(); 7806 MachineMemOperand *MMO = ST->getMemOperand(); 7807 7808 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7809 Value); 7810 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7811 } 7812 7813 // FIXME: Remove this once the ANDI glue bug is fixed: 7814 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7815 assert(Op.getValueType() == MVT::i1 && 7816 "Custom lowering only for i1 results"); 7817 7818 SDLoc DL(Op); 7819 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7820 } 7821 7822 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7823 SelectionDAG &DAG) const { 7824 7825 // Implements a vector truncate that fits in a vector register as a shuffle. 7826 // We want to legalize vector truncates down to where the source fits in 7827 // a vector register (and target is therefore smaller than vector register 7828 // size). At that point legalization will try to custom lower the sub-legal 7829 // result and get here - where we can contain the truncate as a single target 7830 // operation. 7831 7832 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7833 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7834 // 7835 // We will implement it for big-endian ordering as this (where x denotes 7836 // undefined): 7837 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7838 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7839 // 7840 // The same operation in little-endian ordering will be: 7841 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7842 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7843 7844 EVT TrgVT = Op.getValueType(); 7845 assert(TrgVT.isVector() && "Vector type expected."); 7846 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7847 EVT EltVT = TrgVT.getVectorElementType(); 7848 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7849 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7850 !isPowerOf2_32(EltVT.getSizeInBits())) 7851 return SDValue(); 7852 7853 SDValue N1 = Op.getOperand(0); 7854 EVT SrcVT = N1.getValueType(); 7855 unsigned SrcSize = SrcVT.getSizeInBits(); 7856 if (SrcSize > 256 || 7857 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7858 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7859 return SDValue(); 7860 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7861 return SDValue(); 7862 7863 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7864 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7865 7866 SDLoc DL(Op); 7867 SDValue Op1, Op2; 7868 if (SrcSize == 256) { 7869 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7870 EVT SplitVT = 7871 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7872 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7873 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7874 DAG.getConstant(0, DL, VecIdxTy)); 7875 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7876 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7877 } 7878 else { 7879 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7880 Op2 = DAG.getUNDEF(WideVT); 7881 } 7882 7883 // First list the elements we want to keep. 7884 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7885 SmallVector<int, 16> ShuffV; 7886 if (Subtarget.isLittleEndian()) 7887 for (unsigned i = 0; i < TrgNumElts; ++i) 7888 ShuffV.push_back(i * SizeMult); 7889 else 7890 for (unsigned i = 1; i <= TrgNumElts; ++i) 7891 ShuffV.push_back(i * SizeMult - 1); 7892 7893 // Populate the remaining elements with undefs. 7894 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7895 // ShuffV.push_back(i + WideNumElts); 7896 ShuffV.push_back(WideNumElts + 1); 7897 7898 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7899 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7900 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7901 } 7902 7903 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7904 /// possible. 7905 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7906 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7907 EVT ResVT = Op.getValueType(); 7908 EVT CmpVT = Op.getOperand(0).getValueType(); 7909 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7910 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7911 SDLoc dl(Op); 7912 7913 // Without power9-vector, we don't have native instruction for f128 comparison. 7914 // Following transformation to libcall is needed for setcc: 7915 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7916 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7917 SDValue Z = DAG.getSetCC( 7918 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7919 LHS, RHS, CC); 7920 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7921 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7922 } 7923 7924 // Not FP, or using SPE? Not a fsel. 7925 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7926 Subtarget.hasSPE()) 7927 return Op; 7928 7929 SDNodeFlags Flags = Op.getNode()->getFlags(); 7930 7931 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the 7932 // presence of infinities. 7933 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7934 switch (CC) { 7935 default: 7936 break; 7937 case ISD::SETOGT: 7938 case ISD::SETGT: 7939 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS); 7940 case ISD::SETOLT: 7941 case ISD::SETLT: 7942 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS); 7943 } 7944 } 7945 7946 // We might be able to do better than this under some circumstances, but in 7947 // general, fsel-based lowering of select is a finite-math-only optimization. 7948 // For more information, see section F.3 of the 2.06 ISA specification. 7949 // With ISA 3.0 7950 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7951 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7952 return Op; 7953 7954 // If the RHS of the comparison is a 0.0, we don't need to do the 7955 // subtraction at all. 7956 SDValue Sel1; 7957 if (isFloatingPointZero(RHS)) 7958 switch (CC) { 7959 default: break; // SETUO etc aren't handled by fsel. 7960 case ISD::SETNE: 7961 std::swap(TV, FV); 7962 [[fallthrough]]; 7963 case ISD::SETEQ: 7964 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7965 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7966 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7967 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7968 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7969 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7970 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7971 case ISD::SETULT: 7972 case ISD::SETLT: 7973 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7974 [[fallthrough]]; 7975 case ISD::SETOGE: 7976 case ISD::SETGE: 7977 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7978 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7979 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7980 case ISD::SETUGT: 7981 case ISD::SETGT: 7982 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7983 [[fallthrough]]; 7984 case ISD::SETOLE: 7985 case ISD::SETLE: 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, 7989 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7990 } 7991 7992 SDValue Cmp; 7993 switch (CC) { 7994 default: break; // SETUO etc aren't handled by fsel. 7995 case ISD::SETNE: 7996 std::swap(TV, FV); 7997 [[fallthrough]]; 7998 case ISD::SETEQ: 7999 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8000 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8001 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8002 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8003 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8004 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8005 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8006 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8007 case ISD::SETULT: 8008 case ISD::SETLT: 8009 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8010 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8011 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8012 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8013 case ISD::SETOGE: 8014 case ISD::SETGE: 8015 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8016 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8017 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8018 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8019 case ISD::SETUGT: 8020 case ISD::SETGT: 8021 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8022 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8023 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8024 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8025 case ISD::SETOLE: 8026 case ISD::SETLE: 8027 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8028 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8029 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8030 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8031 } 8032 return Op; 8033 } 8034 8035 static unsigned getPPCStrictOpcode(unsigned Opc) { 8036 switch (Opc) { 8037 default: 8038 llvm_unreachable("No strict version of this opcode!"); 8039 case PPCISD::FCTIDZ: 8040 return PPCISD::STRICT_FCTIDZ; 8041 case PPCISD::FCTIWZ: 8042 return PPCISD::STRICT_FCTIWZ; 8043 case PPCISD::FCTIDUZ: 8044 return PPCISD::STRICT_FCTIDUZ; 8045 case PPCISD::FCTIWUZ: 8046 return PPCISD::STRICT_FCTIWUZ; 8047 case PPCISD::FCFID: 8048 return PPCISD::STRICT_FCFID; 8049 case PPCISD::FCFIDU: 8050 return PPCISD::STRICT_FCFIDU; 8051 case PPCISD::FCFIDS: 8052 return PPCISD::STRICT_FCFIDS; 8053 case PPCISD::FCFIDUS: 8054 return PPCISD::STRICT_FCFIDUS; 8055 } 8056 } 8057 8058 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8059 const PPCSubtarget &Subtarget) { 8060 SDLoc dl(Op); 8061 bool IsStrict = Op->isStrictFPOpcode(); 8062 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8063 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8064 8065 // TODO: Any other flags to propagate? 8066 SDNodeFlags Flags; 8067 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8068 8069 // For strict nodes, source is the second operand. 8070 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8071 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8072 assert(Src.getValueType().isFloatingPoint()); 8073 if (Src.getValueType() == MVT::f32) { 8074 if (IsStrict) { 8075 Src = 8076 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8077 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8078 Chain = Src.getValue(1); 8079 } else 8080 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8081 } 8082 SDValue Conv; 8083 unsigned Opc = ISD::DELETED_NODE; 8084 switch (Op.getSimpleValueType().SimpleTy) { 8085 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8086 case MVT::i32: 8087 Opc = IsSigned ? PPCISD::FCTIWZ 8088 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8089 break; 8090 case MVT::i64: 8091 assert((IsSigned || Subtarget.hasFPCVT()) && 8092 "i64 FP_TO_UINT is supported only with FPCVT"); 8093 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8094 } 8095 if (IsStrict) { 8096 Opc = getPPCStrictOpcode(Opc); 8097 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8098 {Chain, Src}, Flags); 8099 } else { 8100 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8101 } 8102 return Conv; 8103 } 8104 8105 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8106 SelectionDAG &DAG, 8107 const SDLoc &dl) const { 8108 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8109 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8110 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8111 bool IsStrict = Op->isStrictFPOpcode(); 8112 8113 // Convert the FP value to an int value through memory. 8114 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8115 (IsSigned || Subtarget.hasFPCVT()); 8116 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8117 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8118 MachinePointerInfo MPI = 8119 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8120 8121 // Emit a store to the stack slot. 8122 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8123 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8124 if (i32Stack) { 8125 MachineFunction &MF = DAG.getMachineFunction(); 8126 Alignment = Align(4); 8127 MachineMemOperand *MMO = 8128 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8129 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8130 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8131 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8132 } else 8133 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8134 8135 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8136 // add in a bias on big endian. 8137 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8138 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8139 DAG.getConstant(4, dl, FIPtr.getValueType())); 8140 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8141 } 8142 8143 RLI.Chain = Chain; 8144 RLI.Ptr = FIPtr; 8145 RLI.MPI = MPI; 8146 RLI.Alignment = Alignment; 8147 } 8148 8149 /// Custom lowers floating point to integer conversions to use 8150 /// the direct move instructions available in ISA 2.07 to avoid the 8151 /// need for load/store combinations. 8152 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8153 SelectionDAG &DAG, 8154 const SDLoc &dl) const { 8155 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8156 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8157 if (Op->isStrictFPOpcode()) 8158 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8159 else 8160 return Mov; 8161 } 8162 8163 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8164 const SDLoc &dl) const { 8165 bool IsStrict = Op->isStrictFPOpcode(); 8166 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8167 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8168 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8169 EVT SrcVT = Src.getValueType(); 8170 EVT DstVT = Op.getValueType(); 8171 8172 // FP to INT conversions are legal for f128. 8173 if (SrcVT == MVT::f128) 8174 return Subtarget.hasP9Vector() ? Op : SDValue(); 8175 8176 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8177 // PPC (the libcall is not available). 8178 if (SrcVT == MVT::ppcf128) { 8179 if (DstVT == MVT::i32) { 8180 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8181 // set other fast-math flags to FP operations in both strict and 8182 // non-strict cases. (FP_TO_SINT, FSUB) 8183 SDNodeFlags Flags; 8184 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8185 8186 if (IsSigned) { 8187 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8188 DAG.getIntPtrConstant(0, dl)); 8189 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8190 DAG.getIntPtrConstant(1, dl)); 8191 8192 // Add the two halves of the long double in round-to-zero mode, and use 8193 // a smaller FP_TO_SINT. 8194 if (IsStrict) { 8195 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8196 DAG.getVTList(MVT::f64, MVT::Other), 8197 {Op.getOperand(0), Lo, Hi}, Flags); 8198 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8199 DAG.getVTList(MVT::i32, MVT::Other), 8200 {Res.getValue(1), Res}, Flags); 8201 } else { 8202 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8203 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8204 } 8205 } else { 8206 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8207 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8208 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8209 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8210 if (IsStrict) { 8211 // Sel = Src < 0x80000000 8212 // FltOfs = select Sel, 0.0, 0x80000000 8213 // IntOfs = select Sel, 0, 0x80000000 8214 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8215 SDValue Chain = Op.getOperand(0); 8216 EVT SetCCVT = 8217 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8218 EVT DstSetCCVT = 8219 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8220 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8221 Chain, true); 8222 Chain = Sel.getValue(1); 8223 8224 SDValue FltOfs = DAG.getSelect( 8225 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8226 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8227 8228 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8229 DAG.getVTList(SrcVT, MVT::Other), 8230 {Chain, Src, FltOfs}, Flags); 8231 Chain = Val.getValue(1); 8232 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8233 DAG.getVTList(DstVT, MVT::Other), 8234 {Chain, Val}, Flags); 8235 Chain = SInt.getValue(1); 8236 SDValue IntOfs = DAG.getSelect( 8237 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8238 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8239 return DAG.getMergeValues({Result, Chain}, dl); 8240 } else { 8241 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8242 // FIXME: generated code sucks. 8243 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8244 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8245 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8246 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8247 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8248 } 8249 } 8250 } 8251 8252 return SDValue(); 8253 } 8254 8255 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8256 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8257 8258 ReuseLoadInfo RLI; 8259 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8260 8261 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8262 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8263 } 8264 8265 // We're trying to insert a regular store, S, and then a load, L. If the 8266 // incoming value, O, is a load, we might just be able to have our load use the 8267 // address used by O. However, we don't know if anything else will store to 8268 // that address before we can load from it. To prevent this situation, we need 8269 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8270 // the same chain operand as O, we create a token factor from the chain results 8271 // of O and L, and we replace all uses of O's chain result with that token 8272 // factor (see spliceIntoChain below for this last part). 8273 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8274 ReuseLoadInfo &RLI, 8275 SelectionDAG &DAG, 8276 ISD::LoadExtType ET) const { 8277 // Conservatively skip reusing for constrained FP nodes. 8278 if (Op->isStrictFPOpcode()) 8279 return false; 8280 8281 SDLoc dl(Op); 8282 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8283 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8284 if (ET == ISD::NON_EXTLOAD && 8285 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8286 isOperationLegalOrCustom(Op.getOpcode(), 8287 Op.getOperand(0).getValueType())) { 8288 8289 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8290 return true; 8291 } 8292 8293 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8294 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8295 LD->isNonTemporal()) 8296 return false; 8297 if (LD->getMemoryVT() != MemVT) 8298 return false; 8299 8300 // If the result of the load is an illegal type, then we can't build a 8301 // valid chain for reuse since the legalised loads and token factor node that 8302 // ties the legalised loads together uses a different output chain then the 8303 // illegal load. 8304 if (!isTypeLegal(LD->getValueType(0))) 8305 return false; 8306 8307 RLI.Ptr = LD->getBasePtr(); 8308 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8309 assert(LD->getAddressingMode() == ISD::PRE_INC && 8310 "Non-pre-inc AM on PPC?"); 8311 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8312 LD->getOffset()); 8313 } 8314 8315 RLI.Chain = LD->getChain(); 8316 RLI.MPI = LD->getPointerInfo(); 8317 RLI.IsDereferenceable = LD->isDereferenceable(); 8318 RLI.IsInvariant = LD->isInvariant(); 8319 RLI.Alignment = LD->getAlign(); 8320 RLI.AAInfo = LD->getAAInfo(); 8321 RLI.Ranges = LD->getRanges(); 8322 8323 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8324 return true; 8325 } 8326 8327 // Given the head of the old chain, ResChain, insert a token factor containing 8328 // it and NewResChain, and make users of ResChain now be users of that token 8329 // factor. 8330 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8331 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8332 SDValue NewResChain, 8333 SelectionDAG &DAG) const { 8334 if (!ResChain) 8335 return; 8336 8337 SDLoc dl(NewResChain); 8338 8339 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8340 NewResChain, DAG.getUNDEF(MVT::Other)); 8341 assert(TF.getNode() != NewResChain.getNode() && 8342 "A new TF really is required here"); 8343 8344 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8345 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8346 } 8347 8348 /// Analyze profitability of direct move 8349 /// prefer float load to int load plus direct move 8350 /// when there is no integer use of int load 8351 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8352 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode(); 8353 if (Origin->getOpcode() != ISD::LOAD) 8354 return true; 8355 8356 // If there is no LXSIBZX/LXSIHZX, like Power8, 8357 // prefer direct move if the memory size is 1 or 2 bytes. 8358 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8359 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8360 return true; 8361 8362 for (SDNode::use_iterator UI = Origin->use_begin(), 8363 UE = Origin->use_end(); 8364 UI != UE; ++UI) { 8365 8366 // Only look at the users of the loaded value. 8367 if (UI.getUse().get().getResNo() != 0) 8368 continue; 8369 8370 if (UI->getOpcode() != ISD::SINT_TO_FP && 8371 UI->getOpcode() != ISD::UINT_TO_FP && 8372 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8373 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8374 return true; 8375 } 8376 8377 return false; 8378 } 8379 8380 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8381 const PPCSubtarget &Subtarget, 8382 SDValue Chain = SDValue()) { 8383 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8384 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8385 SDLoc dl(Op); 8386 8387 // TODO: Any other flags to propagate? 8388 SDNodeFlags Flags; 8389 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8390 8391 // If we have FCFIDS, then use it when converting to single-precision. 8392 // Otherwise, convert to double-precision and then round. 8393 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8394 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8395 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8396 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8397 if (Op->isStrictFPOpcode()) { 8398 if (!Chain) 8399 Chain = Op.getOperand(0); 8400 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8401 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8402 } else 8403 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8404 } 8405 8406 /// Custom lowers integer to floating point conversions to use 8407 /// the direct move instructions available in ISA 2.07 to avoid the 8408 /// need for load/store combinations. 8409 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8410 SelectionDAG &DAG, 8411 const SDLoc &dl) const { 8412 assert((Op.getValueType() == MVT::f32 || 8413 Op.getValueType() == MVT::f64) && 8414 "Invalid floating point type as target of conversion"); 8415 assert(Subtarget.hasFPCVT() && 8416 "Int to FP conversions with direct moves require FPCVT"); 8417 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8418 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8419 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8420 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8421 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8422 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8423 return convertIntToFP(Op, Mov, DAG, Subtarget); 8424 } 8425 8426 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8427 8428 EVT VecVT = Vec.getValueType(); 8429 assert(VecVT.isVector() && "Expected a vector type."); 8430 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8431 8432 EVT EltVT = VecVT.getVectorElementType(); 8433 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8434 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8435 8436 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8437 SmallVector<SDValue, 16> Ops(NumConcat); 8438 Ops[0] = Vec; 8439 SDValue UndefVec = DAG.getUNDEF(VecVT); 8440 for (unsigned i = 1; i < NumConcat; ++i) 8441 Ops[i] = UndefVec; 8442 8443 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8444 } 8445 8446 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8447 const SDLoc &dl) const { 8448 bool IsStrict = Op->isStrictFPOpcode(); 8449 unsigned Opc = Op.getOpcode(); 8450 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8451 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8452 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8453 "Unexpected conversion type"); 8454 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8455 "Supports conversions to v2f64/v4f32 only."); 8456 8457 // TODO: Any other flags to propagate? 8458 SDNodeFlags Flags; 8459 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8460 8461 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8462 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8463 8464 SDValue Wide = widenVec(DAG, Src, dl); 8465 EVT WideVT = Wide.getValueType(); 8466 unsigned WideNumElts = WideVT.getVectorNumElements(); 8467 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8468 8469 SmallVector<int, 16> ShuffV; 8470 for (unsigned i = 0; i < WideNumElts; ++i) 8471 ShuffV.push_back(i + WideNumElts); 8472 8473 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8474 int SaveElts = FourEltRes ? 4 : 2; 8475 if (Subtarget.isLittleEndian()) 8476 for (int i = 0; i < SaveElts; i++) 8477 ShuffV[i * Stride] = i; 8478 else 8479 for (int i = 1; i <= SaveElts; i++) 8480 ShuffV[i * Stride - 1] = i - 1; 8481 8482 SDValue ShuffleSrc2 = 8483 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8484 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8485 8486 SDValue Extend; 8487 if (SignedConv) { 8488 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8489 EVT ExtVT = Src.getValueType(); 8490 if (Subtarget.hasP9Altivec()) 8491 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8492 IntermediateVT.getVectorNumElements()); 8493 8494 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8495 DAG.getValueType(ExtVT)); 8496 } else 8497 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8498 8499 if (IsStrict) 8500 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8501 {Op.getOperand(0), Extend}, Flags); 8502 8503 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8504 } 8505 8506 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8507 SelectionDAG &DAG) const { 8508 SDLoc dl(Op); 8509 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8510 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8511 bool IsStrict = Op->isStrictFPOpcode(); 8512 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8513 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8514 8515 // TODO: Any other flags to propagate? 8516 SDNodeFlags Flags; 8517 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8518 8519 EVT InVT = Src.getValueType(); 8520 EVT OutVT = Op.getValueType(); 8521 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8522 isOperationCustom(Op.getOpcode(), InVT)) 8523 return LowerINT_TO_FPVector(Op, DAG, dl); 8524 8525 // Conversions to f128 are legal. 8526 if (Op.getValueType() == MVT::f128) 8527 return Subtarget.hasP9Vector() ? Op : SDValue(); 8528 8529 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8530 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8531 return SDValue(); 8532 8533 if (Src.getValueType() == MVT::i1) { 8534 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8535 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8536 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8537 if (IsStrict) 8538 return DAG.getMergeValues({Sel, Chain}, dl); 8539 else 8540 return Sel; 8541 } 8542 8543 // If we have direct moves, we can do all the conversion, skip the store/load 8544 // however, without FPCVT we can't do most conversions. 8545 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8546 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8547 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8548 8549 assert((IsSigned || Subtarget.hasFPCVT()) && 8550 "UINT_TO_FP is supported only with FPCVT"); 8551 8552 if (Src.getValueType() == MVT::i64) { 8553 SDValue SINT = Src; 8554 // When converting to single-precision, we actually need to convert 8555 // to double-precision first and then round to single-precision. 8556 // To avoid double-rounding effects during that operation, we have 8557 // to prepare the input operand. Bits that might be truncated when 8558 // converting to double-precision are replaced by a bit that won't 8559 // be lost at this stage, but is below the single-precision rounding 8560 // position. 8561 // 8562 // However, if -enable-unsafe-fp-math is in effect, accept double 8563 // rounding to avoid the extra overhead. 8564 if (Op.getValueType() == MVT::f32 && 8565 !Subtarget.hasFPCVT() && 8566 !DAG.getTarget().Options.UnsafeFPMath) { 8567 8568 // Twiddle input to make sure the low 11 bits are zero. (If this 8569 // is the case, we are guaranteed the value will fit into the 53 bit 8570 // mantissa of an IEEE double-precision value without rounding.) 8571 // If any of those low 11 bits were not zero originally, make sure 8572 // bit 12 (value 2048) is set instead, so that the final rounding 8573 // to single-precision gets the correct result. 8574 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8575 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8576 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8577 Round, DAG.getConstant(2047, dl, MVT::i64)); 8578 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8579 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8580 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8581 8582 // However, we cannot use that value unconditionally: if the magnitude 8583 // of the input value is small, the bit-twiddling we did above might 8584 // end up visibly changing the output. Fortunately, in that case, we 8585 // don't need to twiddle bits since the original input will convert 8586 // exactly to double-precision floating-point already. Therefore, 8587 // construct a conditional to use the original value if the top 11 8588 // bits are all sign-bit copies, and use the rounded value computed 8589 // above otherwise. 8590 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8591 SINT, DAG.getConstant(53, dl, MVT::i32)); 8592 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8593 Cond, DAG.getConstant(1, dl, MVT::i64)); 8594 Cond = DAG.getSetCC( 8595 dl, 8596 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8597 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8598 8599 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8600 } 8601 8602 ReuseLoadInfo RLI; 8603 SDValue Bits; 8604 8605 MachineFunction &MF = DAG.getMachineFunction(); 8606 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8607 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8608 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8609 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8610 } else if (Subtarget.hasLFIWAX() && 8611 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8612 MachineMemOperand *MMO = 8613 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8614 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8615 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8616 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8617 DAG.getVTList(MVT::f64, MVT::Other), 8618 Ops, MVT::i32, MMO); 8619 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8620 } else if (Subtarget.hasFPCVT() && 8621 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8622 MachineMemOperand *MMO = 8623 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8624 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8625 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8626 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8627 DAG.getVTList(MVT::f64, MVT::Other), 8628 Ops, MVT::i32, MMO); 8629 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8630 } else if (((Subtarget.hasLFIWAX() && 8631 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8632 (Subtarget.hasFPCVT() && 8633 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8634 SINT.getOperand(0).getValueType() == MVT::i32) { 8635 MachineFrameInfo &MFI = MF.getFrameInfo(); 8636 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8637 8638 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8639 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8640 8641 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8642 MachinePointerInfo::getFixedStack( 8643 DAG.getMachineFunction(), FrameIdx)); 8644 Chain = Store; 8645 8646 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8647 "Expected an i32 store"); 8648 8649 RLI.Ptr = FIdx; 8650 RLI.Chain = Chain; 8651 RLI.MPI = 8652 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8653 RLI.Alignment = Align(4); 8654 8655 MachineMemOperand *MMO = 8656 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8657 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8658 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8659 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8660 PPCISD::LFIWZX : PPCISD::LFIWAX, 8661 dl, DAG.getVTList(MVT::f64, MVT::Other), 8662 Ops, MVT::i32, MMO); 8663 Chain = Bits.getValue(1); 8664 } else 8665 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8666 8667 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8668 if (IsStrict) 8669 Chain = FP.getValue(1); 8670 8671 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8672 if (IsStrict) 8673 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8674 DAG.getVTList(MVT::f32, MVT::Other), 8675 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8676 else 8677 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8678 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 8679 } 8680 return FP; 8681 } 8682 8683 assert(Src.getValueType() == MVT::i32 && 8684 "Unhandled INT_TO_FP type in custom expander!"); 8685 // Since we only generate this in 64-bit mode, we can take advantage of 8686 // 64-bit registers. In particular, sign extend the input value into the 8687 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8688 // then lfd it and fcfid it. 8689 MachineFunction &MF = DAG.getMachineFunction(); 8690 MachineFrameInfo &MFI = MF.getFrameInfo(); 8691 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8692 8693 SDValue Ld; 8694 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8695 ReuseLoadInfo RLI; 8696 bool ReusingLoad; 8697 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8698 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8699 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8700 8701 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8702 MachinePointerInfo::getFixedStack( 8703 DAG.getMachineFunction(), FrameIdx)); 8704 Chain = Store; 8705 8706 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8707 "Expected an i32 store"); 8708 8709 RLI.Ptr = FIdx; 8710 RLI.Chain = Chain; 8711 RLI.MPI = 8712 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8713 RLI.Alignment = Align(4); 8714 } 8715 8716 MachineMemOperand *MMO = 8717 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8718 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8719 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8720 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8721 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8722 MVT::i32, MMO); 8723 Chain = Ld.getValue(1); 8724 if (ReusingLoad) 8725 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8726 } else { 8727 assert(Subtarget.isPPC64() && 8728 "i32->FP without LFIWAX supported only on PPC64"); 8729 8730 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8731 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8732 8733 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8734 8735 // STD the extended value into the stack slot. 8736 SDValue Store = DAG.getStore( 8737 Chain, dl, Ext64, FIdx, 8738 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8739 Chain = Store; 8740 8741 // Load the value as a double. 8742 Ld = DAG.getLoad( 8743 MVT::f64, dl, Chain, FIdx, 8744 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8745 Chain = Ld.getValue(1); 8746 } 8747 8748 // FCFID it and return it. 8749 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8750 if (IsStrict) 8751 Chain = FP.getValue(1); 8752 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8753 if (IsStrict) 8754 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8755 DAG.getVTList(MVT::f32, MVT::Other), 8756 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8757 else 8758 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8759 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 8760 } 8761 return FP; 8762 } 8763 8764 SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op, 8765 SelectionDAG &DAG) const { 8766 SDLoc dl(Op); 8767 /* 8768 The rounding mode is in bits 30:31 of FPSR, and has the following 8769 settings: 8770 00 Round to nearest 8771 01 Round to 0 8772 10 Round to +inf 8773 11 Round to -inf 8774 8775 GET_ROUNDING, on the other hand, expects the following: 8776 -1 Undefined 8777 0 Round to 0 8778 1 Round to nearest 8779 2 Round to +inf 8780 3 Round to -inf 8781 8782 To perform the conversion, we do: 8783 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8784 */ 8785 8786 MachineFunction &MF = DAG.getMachineFunction(); 8787 EVT VT = Op.getValueType(); 8788 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8789 8790 // Save FP Control Word to register 8791 SDValue Chain = Op.getOperand(0); 8792 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8793 Chain = MFFS.getValue(1); 8794 8795 SDValue CWD; 8796 if (isTypeLegal(MVT::i64)) { 8797 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8798 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8799 } else { 8800 // Save FP register to stack slot 8801 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8802 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8803 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8804 8805 // Load FP Control Word from low 32 bits of stack slot. 8806 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8807 "Stack slot adjustment is valid only on big endian subtargets!"); 8808 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8809 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8810 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8811 Chain = CWD.getValue(1); 8812 } 8813 8814 // Transform as necessary 8815 SDValue CWD1 = 8816 DAG.getNode(ISD::AND, dl, MVT::i32, 8817 CWD, DAG.getConstant(3, dl, MVT::i32)); 8818 SDValue CWD2 = 8819 DAG.getNode(ISD::SRL, dl, MVT::i32, 8820 DAG.getNode(ISD::AND, dl, MVT::i32, 8821 DAG.getNode(ISD::XOR, dl, MVT::i32, 8822 CWD, DAG.getConstant(3, dl, MVT::i32)), 8823 DAG.getConstant(3, dl, MVT::i32)), 8824 DAG.getConstant(1, dl, MVT::i32)); 8825 8826 SDValue RetVal = 8827 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8828 8829 RetVal = 8830 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8831 dl, VT, RetVal); 8832 8833 return DAG.getMergeValues({RetVal, Chain}, dl); 8834 } 8835 8836 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8837 EVT VT = Op.getValueType(); 8838 unsigned BitWidth = VT.getSizeInBits(); 8839 SDLoc dl(Op); 8840 assert(Op.getNumOperands() == 3 && 8841 VT == Op.getOperand(1).getValueType() && 8842 "Unexpected SHL!"); 8843 8844 // Expand into a bunch of logical ops. Note that these ops 8845 // depend on the PPC behavior for oversized shift amounts. 8846 SDValue Lo = Op.getOperand(0); 8847 SDValue Hi = Op.getOperand(1); 8848 SDValue Amt = Op.getOperand(2); 8849 EVT AmtVT = Amt.getValueType(); 8850 8851 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8852 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8853 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8854 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8855 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8856 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8857 DAG.getConstant(-BitWidth, dl, AmtVT)); 8858 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8859 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8860 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8861 SDValue OutOps[] = { OutLo, OutHi }; 8862 return DAG.getMergeValues(OutOps, dl); 8863 } 8864 8865 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8866 EVT VT = Op.getValueType(); 8867 SDLoc dl(Op); 8868 unsigned BitWidth = VT.getSizeInBits(); 8869 assert(Op.getNumOperands() == 3 && 8870 VT == Op.getOperand(1).getValueType() && 8871 "Unexpected SRL!"); 8872 8873 // Expand into a bunch of logical ops. Note that these ops 8874 // depend on the PPC behavior for oversized shift amounts. 8875 SDValue Lo = Op.getOperand(0); 8876 SDValue Hi = Op.getOperand(1); 8877 SDValue Amt = Op.getOperand(2); 8878 EVT AmtVT = Amt.getValueType(); 8879 8880 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8881 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8882 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8883 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8884 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8885 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8886 DAG.getConstant(-BitWidth, dl, AmtVT)); 8887 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8888 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8889 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8890 SDValue OutOps[] = { OutLo, OutHi }; 8891 return DAG.getMergeValues(OutOps, dl); 8892 } 8893 8894 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8895 SDLoc dl(Op); 8896 EVT VT = Op.getValueType(); 8897 unsigned BitWidth = VT.getSizeInBits(); 8898 assert(Op.getNumOperands() == 3 && 8899 VT == Op.getOperand(1).getValueType() && 8900 "Unexpected SRA!"); 8901 8902 // Expand into a bunch of logical ops, followed by a select_cc. 8903 SDValue Lo = Op.getOperand(0); 8904 SDValue Hi = Op.getOperand(1); 8905 SDValue Amt = Op.getOperand(2); 8906 EVT AmtVT = Amt.getValueType(); 8907 8908 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8909 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8910 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8911 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8912 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8913 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8914 DAG.getConstant(-BitWidth, dl, AmtVT)); 8915 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8916 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8917 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8918 Tmp4, Tmp6, ISD::SETLE); 8919 SDValue OutOps[] = { OutLo, OutHi }; 8920 return DAG.getMergeValues(OutOps, dl); 8921 } 8922 8923 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8924 SelectionDAG &DAG) const { 8925 SDLoc dl(Op); 8926 EVT VT = Op.getValueType(); 8927 unsigned BitWidth = VT.getSizeInBits(); 8928 8929 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8930 SDValue X = Op.getOperand(0); 8931 SDValue Y = Op.getOperand(1); 8932 SDValue Z = Op.getOperand(2); 8933 EVT AmtVT = Z.getValueType(); 8934 8935 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8936 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8937 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8938 // on PowerPC shift by BW being well defined. 8939 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8940 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8941 SDValue SubZ = 8942 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8943 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8944 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8945 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8946 } 8947 8948 //===----------------------------------------------------------------------===// 8949 // Vector related lowering. 8950 // 8951 8952 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8953 /// element size of SplatSize. Cast the result to VT. 8954 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8955 SelectionDAG &DAG, const SDLoc &dl) { 8956 static const MVT VTys[] = { // canonical VT to use for each size. 8957 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8958 }; 8959 8960 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8961 8962 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8963 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8964 SplatSize = 1; 8965 Val = 0xFF; 8966 } 8967 8968 EVT CanonicalVT = VTys[SplatSize-1]; 8969 8970 // Build a canonical splat for this value. 8971 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8972 } 8973 8974 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8975 /// specified intrinsic ID. 8976 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8977 const SDLoc &dl, EVT DestVT = MVT::Other) { 8978 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8979 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8980 DAG.getConstant(IID, dl, MVT::i32), Op); 8981 } 8982 8983 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8984 /// specified intrinsic ID. 8985 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8986 SelectionDAG &DAG, const SDLoc &dl, 8987 EVT DestVT = MVT::Other) { 8988 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8989 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8990 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8991 } 8992 8993 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8994 /// specified intrinsic ID. 8995 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8996 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8997 EVT DestVT = MVT::Other) { 8998 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8999 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9000 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9001 } 9002 9003 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9004 /// amount. The result has the specified value type. 9005 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9006 SelectionDAG &DAG, const SDLoc &dl) { 9007 // Force LHS/RHS to be the right type. 9008 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9009 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9010 9011 int Ops[16]; 9012 for (unsigned i = 0; i != 16; ++i) 9013 Ops[i] = i + Amt; 9014 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9015 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9016 } 9017 9018 /// Do we have an efficient pattern in a .td file for this node? 9019 /// 9020 /// \param V - pointer to the BuildVectorSDNode being matched 9021 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9022 /// 9023 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9024 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9025 /// the opposite is true (expansion is beneficial) are: 9026 /// - The node builds a vector out of integers that are not 32 or 64-bits 9027 /// - The node builds a vector out of constants 9028 /// - The node is a "load-and-splat" 9029 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9030 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9031 bool HasDirectMove, 9032 bool HasP8Vector) { 9033 EVT VecVT = V->getValueType(0); 9034 bool RightType = VecVT == MVT::v2f64 || 9035 (HasP8Vector && VecVT == MVT::v4f32) || 9036 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9037 if (!RightType) 9038 return false; 9039 9040 bool IsSplat = true; 9041 bool IsLoad = false; 9042 SDValue Op0 = V->getOperand(0); 9043 9044 // This function is called in a block that confirms the node is not a constant 9045 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9046 // different constants. 9047 if (V->isConstant()) 9048 return false; 9049 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9050 if (V->getOperand(i).isUndef()) 9051 return false; 9052 // We want to expand nodes that represent load-and-splat even if the 9053 // loaded value is a floating point truncation or conversion to int. 9054 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9055 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9056 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9057 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9058 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9059 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9060 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9061 IsLoad = true; 9062 // If the operands are different or the input is not a load and has more 9063 // uses than just this BV node, then it isn't a splat. 9064 if (V->getOperand(i) != Op0 || 9065 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9066 IsSplat = false; 9067 } 9068 return !(IsSplat && IsLoad); 9069 } 9070 9071 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9072 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9073 9074 SDLoc dl(Op); 9075 SDValue Op0 = Op->getOperand(0); 9076 9077 if ((Op.getValueType() != MVT::f128) || 9078 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9079 (Op0.getOperand(0).getValueType() != MVT::i64) || 9080 (Op0.getOperand(1).getValueType() != MVT::i64)) 9081 return SDValue(); 9082 9083 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9084 Op0.getOperand(1)); 9085 } 9086 9087 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9088 const SDValue *InputLoad = &Op; 9089 while (InputLoad->getOpcode() == ISD::BITCAST) 9090 InputLoad = &InputLoad->getOperand(0); 9091 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9092 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9093 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9094 InputLoad = &InputLoad->getOperand(0); 9095 } 9096 if (InputLoad->getOpcode() != ISD::LOAD) 9097 return nullptr; 9098 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9099 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9100 } 9101 9102 // Convert the argument APFloat to a single precision APFloat if there is no 9103 // loss in information during the conversion to single precision APFloat and the 9104 // resulting number is not a denormal number. Return true if successful. 9105 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9106 APFloat APFloatToConvert = ArgAPFloat; 9107 bool LosesInfo = true; 9108 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9109 &LosesInfo); 9110 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9111 if (Success) 9112 ArgAPFloat = APFloatToConvert; 9113 return Success; 9114 } 9115 9116 // Bitcast the argument APInt to a double and convert it to a single precision 9117 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9118 // argument if there is no loss in information during the conversion from 9119 // double to single precision APFloat and the resulting number is not a denormal 9120 // number. Return true if successful. 9121 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9122 double DpValue = ArgAPInt.bitsToDouble(); 9123 APFloat APFloatDp(DpValue); 9124 bool Success = convertToNonDenormSingle(APFloatDp); 9125 if (Success) 9126 ArgAPInt = APFloatDp.bitcastToAPInt(); 9127 return Success; 9128 } 9129 9130 // Nondestructive check for convertTonNonDenormSingle. 9131 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9132 // Only convert if it loses info, since XXSPLTIDP should 9133 // handle the other case. 9134 APFloat APFloatToConvert = ArgAPFloat; 9135 bool LosesInfo = true; 9136 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9137 &LosesInfo); 9138 9139 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9140 } 9141 9142 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9143 unsigned &Opcode) { 9144 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0)); 9145 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode)) 9146 return false; 9147 9148 EVT Ty = Op->getValueType(0); 9149 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending 9150 // as we cannot handle extending loads for these types. 9151 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) && 9152 ISD::isNON_EXTLoad(InputNode)) 9153 return true; 9154 9155 EVT MemVT = InputNode->getMemoryVT(); 9156 // For v8i16 and v16i8 types, extending loads can be handled as long as the 9157 // memory VT is the same vector element VT type. 9158 // The loads feeding into the v8i16 and v16i8 types will be extending because 9159 // scalar i8/i16 are not legal types. 9160 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) && 9161 (MemVT == Ty.getVectorElementType())) 9162 return true; 9163 9164 if (Ty == MVT::v2i64) { 9165 // Check the extend type, when the input type is i32, and the output vector 9166 // type is v2i64. 9167 if (MemVT == MVT::i32) { 9168 if (ISD::isZEXTLoad(InputNode)) 9169 Opcode = PPCISD::ZEXT_LD_SPLAT; 9170 if (ISD::isSEXTLoad(InputNode)) 9171 Opcode = PPCISD::SEXT_LD_SPLAT; 9172 } 9173 return true; 9174 } 9175 return false; 9176 } 9177 9178 // If this is a case we can't handle, return null and let the default 9179 // expansion code take care of it. If we CAN select this case, and if it 9180 // selects to a single instruction, return Op. Otherwise, if we can codegen 9181 // this case more efficiently than a constant pool load, lower it to the 9182 // sequence of ops that should be used. 9183 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9184 SelectionDAG &DAG) const { 9185 SDLoc dl(Op); 9186 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9187 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9188 9189 // Check if this is a splat of a constant value. 9190 APInt APSplatBits, APSplatUndef; 9191 unsigned SplatBitSize; 9192 bool HasAnyUndefs; 9193 bool BVNIsConstantSplat = 9194 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9195 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9196 9197 // If it is a splat of a double, check if we can shrink it to a 32 bit 9198 // non-denormal float which when converted back to double gives us the same 9199 // double. This is to exploit the XXSPLTIDP instruction. 9200 // If we lose precision, we use XXSPLTI32DX. 9201 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9202 Subtarget.hasPrefixInstrs()) { 9203 // Check the type first to short-circuit so we don't modify APSplatBits if 9204 // this block isn't executed. 9205 if ((Op->getValueType(0) == MVT::v2f64) && 9206 convertToNonDenormSingle(APSplatBits)) { 9207 SDValue SplatNode = DAG.getNode( 9208 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9209 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9210 return DAG.getBitcast(Op.getValueType(), SplatNode); 9211 } else { 9212 // We may lose precision, so we have to use XXSPLTI32DX. 9213 9214 uint32_t Hi = 9215 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9216 uint32_t Lo = 9217 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9218 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9219 9220 if (!Hi || !Lo) 9221 // If either load is 0, then we should generate XXLXOR to set to 0. 9222 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9223 9224 if (Hi) 9225 SplatNode = DAG.getNode( 9226 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9227 DAG.getTargetConstant(0, dl, MVT::i32), 9228 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9229 9230 if (Lo) 9231 SplatNode = 9232 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9233 DAG.getTargetConstant(1, dl, MVT::i32), 9234 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9235 9236 return DAG.getBitcast(Op.getValueType(), SplatNode); 9237 } 9238 } 9239 9240 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9241 unsigned NewOpcode = PPCISD::LD_SPLAT; 9242 9243 // Handle load-and-splat patterns as we have instructions that will do this 9244 // in one go. 9245 if (DAG.isSplatValue(Op, true) && 9246 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9247 const SDValue *InputLoad = &Op.getOperand(0); 9248 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9249 9250 // If the input load is an extending load, it will be an i32 -> i64 9251 // extending load and isValidSplatLoad() will update NewOpcode. 9252 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9253 unsigned ElementSize = 9254 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9255 9256 assert(((ElementSize == 2 * MemorySize) 9257 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9258 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9259 : (NewOpcode == PPCISD::LD_SPLAT)) && 9260 "Unmatched element size and opcode!\n"); 9261 9262 // Checking for a single use of this load, we have to check for vector 9263 // width (128 bits) / ElementSize uses (since each operand of the 9264 // BUILD_VECTOR is a separate use of the value. 9265 unsigned NumUsesOfInputLD = 128 / ElementSize; 9266 for (SDValue BVInOp : Op->ops()) 9267 if (BVInOp.isUndef()) 9268 NumUsesOfInputLD--; 9269 9270 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9271 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9272 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9273 // 15", but funciton IsValidSplatLoad() now will only return true when 9274 // the data at index 0 is not nullptr. So we will not get into trouble for 9275 // these cases. 9276 // 9277 // case 1 - lfiwzx/lfiwax 9278 // 1.1: load result is i32 and is sign/zero extend to i64; 9279 // 1.2: build a v2i64 vector type with above loaded value; 9280 // 1.3: the vector has only one value at index 0, others are all undef; 9281 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9282 if (NumUsesOfInputLD == 1 && 9283 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9284 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9285 Subtarget.hasLFIWAX())) 9286 return SDValue(); 9287 9288 // case 2 - lxvr[hb]x 9289 // 2.1: load result is at most i16; 9290 // 2.2: build a vector with above loaded value; 9291 // 2.3: the vector has only one value at index 0, others are all undef; 9292 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9293 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9294 Subtarget.isISA3_1() && ElementSize <= 16) 9295 return SDValue(); 9296 9297 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9298 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9299 Subtarget.hasVSX()) { 9300 SDValue Ops[] = { 9301 LD->getChain(), // Chain 9302 LD->getBasePtr(), // Ptr 9303 DAG.getValueType(Op.getValueType()) // VT 9304 }; 9305 SDValue LdSplt = DAG.getMemIntrinsicNode( 9306 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9307 LD->getMemoryVT(), LD->getMemOperand()); 9308 // Replace all uses of the output chain of the original load with the 9309 // output chain of the new load. 9310 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9311 LdSplt.getValue(1)); 9312 return LdSplt; 9313 } 9314 } 9315 9316 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9317 // 32-bits can be lowered to VSX instructions under certain conditions. 9318 // Without VSX, there is no pattern more efficient than expanding the node. 9319 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9320 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9321 Subtarget.hasP8Vector())) 9322 return Op; 9323 return SDValue(); 9324 } 9325 9326 uint64_t SplatBits = APSplatBits.getZExtValue(); 9327 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9328 unsigned SplatSize = SplatBitSize / 8; 9329 9330 // First, handle single instruction cases. 9331 9332 // All zeros? 9333 if (SplatBits == 0) { 9334 // Canonicalize all zero vectors to be v4i32. 9335 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9336 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9337 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9338 } 9339 return Op; 9340 } 9341 9342 // We have XXSPLTIW for constant splats four bytes wide. 9343 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9344 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9345 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9346 // turned into a 4-byte splat of 0xABABABAB. 9347 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9348 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9349 Op.getValueType(), DAG, dl); 9350 9351 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9352 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9353 dl); 9354 9355 // We have XXSPLTIB for constant splats one byte wide. 9356 if (Subtarget.hasP9Vector() && SplatSize == 1) 9357 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9358 dl); 9359 9360 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9361 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9362 (32-SplatBitSize)); 9363 if (SextVal >= -16 && SextVal <= 15) 9364 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9365 dl); 9366 9367 // Two instruction sequences. 9368 9369 // If this value is in the range [-32,30] and is even, use: 9370 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9371 // If this value is in the range [17,31] and is odd, use: 9372 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9373 // If this value is in the range [-31,-17] and is odd, use: 9374 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9375 // Note the last two are three-instruction sequences. 9376 if (SextVal >= -32 && SextVal <= 31) { 9377 // To avoid having these optimizations undone by constant folding, 9378 // we convert to a pseudo that will be expanded later into one of 9379 // the above forms. 9380 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9381 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9382 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9383 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9384 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9385 if (VT == Op.getValueType()) 9386 return RetVal; 9387 else 9388 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9389 } 9390 9391 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9392 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9393 // for fneg/fabs. 9394 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9395 // Make -1 and vspltisw -1: 9396 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9397 9398 // Make the VSLW intrinsic, computing 0x8000_0000. 9399 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9400 OnesV, DAG, dl); 9401 9402 // xor by OnesV to invert it. 9403 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9404 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9405 } 9406 9407 // Check to see if this is a wide variety of vsplti*, binop self cases. 9408 static const signed char SplatCsts[] = { 9409 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9410 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9411 }; 9412 9413 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) { 9414 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9415 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9416 int i = SplatCsts[idx]; 9417 9418 // Figure out what shift amount will be used by altivec if shifted by i in 9419 // this splat size. 9420 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9421 9422 // vsplti + shl self. 9423 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9424 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9425 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9426 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9427 Intrinsic::ppc_altivec_vslw 9428 }; 9429 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9430 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9431 } 9432 9433 // vsplti + srl self. 9434 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9435 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9436 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9437 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9438 Intrinsic::ppc_altivec_vsrw 9439 }; 9440 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9441 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9442 } 9443 9444 // vsplti + rol self. 9445 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9446 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9447 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9448 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9449 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9450 Intrinsic::ppc_altivec_vrlw 9451 }; 9452 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9453 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9454 } 9455 9456 // t = vsplti c, result = vsldoi t, t, 1 9457 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9458 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9459 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9460 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9461 } 9462 // t = vsplti c, result = vsldoi t, t, 2 9463 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9464 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9465 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9466 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9467 } 9468 // t = vsplti c, result = vsldoi t, t, 3 9469 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9470 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9471 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9472 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9473 } 9474 } 9475 9476 return SDValue(); 9477 } 9478 9479 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9480 /// the specified operations to build the shuffle. 9481 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9482 SDValue RHS, SelectionDAG &DAG, 9483 const SDLoc &dl) { 9484 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9485 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9486 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9487 9488 enum { 9489 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9490 OP_VMRGHW, 9491 OP_VMRGLW, 9492 OP_VSPLTISW0, 9493 OP_VSPLTISW1, 9494 OP_VSPLTISW2, 9495 OP_VSPLTISW3, 9496 OP_VSLDOI4, 9497 OP_VSLDOI8, 9498 OP_VSLDOI12 9499 }; 9500 9501 if (OpNum == OP_COPY) { 9502 if (LHSID == (1*9+2)*9+3) return LHS; 9503 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9504 return RHS; 9505 } 9506 9507 SDValue OpLHS, OpRHS; 9508 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9509 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9510 9511 int ShufIdxs[16]; 9512 switch (OpNum) { 9513 default: llvm_unreachable("Unknown i32 permute!"); 9514 case OP_VMRGHW: 9515 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9516 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9517 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9518 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9519 break; 9520 case OP_VMRGLW: 9521 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9522 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9523 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9524 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9525 break; 9526 case OP_VSPLTISW0: 9527 for (unsigned i = 0; i != 16; ++i) 9528 ShufIdxs[i] = (i&3)+0; 9529 break; 9530 case OP_VSPLTISW1: 9531 for (unsigned i = 0; i != 16; ++i) 9532 ShufIdxs[i] = (i&3)+4; 9533 break; 9534 case OP_VSPLTISW2: 9535 for (unsigned i = 0; i != 16; ++i) 9536 ShufIdxs[i] = (i&3)+8; 9537 break; 9538 case OP_VSPLTISW3: 9539 for (unsigned i = 0; i != 16; ++i) 9540 ShufIdxs[i] = (i&3)+12; 9541 break; 9542 case OP_VSLDOI4: 9543 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9544 case OP_VSLDOI8: 9545 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9546 case OP_VSLDOI12: 9547 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9548 } 9549 EVT VT = OpLHS.getValueType(); 9550 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9551 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9552 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9553 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9554 } 9555 9556 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9557 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9558 /// SDValue. 9559 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9560 SelectionDAG &DAG) const { 9561 const unsigned BytesInVector = 16; 9562 bool IsLE = Subtarget.isLittleEndian(); 9563 SDLoc dl(N); 9564 SDValue V1 = N->getOperand(0); 9565 SDValue V2 = N->getOperand(1); 9566 unsigned ShiftElts = 0, InsertAtByte = 0; 9567 bool Swap = false; 9568 9569 // Shifts required to get the byte we want at element 7. 9570 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9571 0, 15, 14, 13, 12, 11, 10, 9}; 9572 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9573 1, 2, 3, 4, 5, 6, 7, 8}; 9574 9575 ArrayRef<int> Mask = N->getMask(); 9576 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9577 9578 // For each mask element, find out if we're just inserting something 9579 // from V2 into V1 or vice versa. 9580 // Possible permutations inserting an element from V2 into V1: 9581 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9582 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9583 // ... 9584 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9585 // Inserting from V1 into V2 will be similar, except mask range will be 9586 // [16,31]. 9587 9588 bool FoundCandidate = false; 9589 // If both vector operands for the shuffle are the same vector, the mask 9590 // will contain only elements from the first one and the second one will be 9591 // undef. 9592 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9593 // Go through the mask of half-words to find an element that's being moved 9594 // from one vector to the other. 9595 for (unsigned i = 0; i < BytesInVector; ++i) { 9596 unsigned CurrentElement = Mask[i]; 9597 // If 2nd operand is undefined, we should only look for element 7 in the 9598 // Mask. 9599 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9600 continue; 9601 9602 bool OtherElementsInOrder = true; 9603 // Examine the other elements in the Mask to see if they're in original 9604 // order. 9605 for (unsigned j = 0; j < BytesInVector; ++j) { 9606 if (j == i) 9607 continue; 9608 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9609 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9610 // in which we always assume we're always picking from the 1st operand. 9611 int MaskOffset = 9612 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9613 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9614 OtherElementsInOrder = false; 9615 break; 9616 } 9617 } 9618 // If other elements are in original order, we record the number of shifts 9619 // we need to get the element we want into element 7. Also record which byte 9620 // in the vector we should insert into. 9621 if (OtherElementsInOrder) { 9622 // If 2nd operand is undefined, we assume no shifts and no swapping. 9623 if (V2.isUndef()) { 9624 ShiftElts = 0; 9625 Swap = false; 9626 } else { 9627 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9628 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9629 : BigEndianShifts[CurrentElement & 0xF]; 9630 Swap = CurrentElement < BytesInVector; 9631 } 9632 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9633 FoundCandidate = true; 9634 break; 9635 } 9636 } 9637 9638 if (!FoundCandidate) 9639 return SDValue(); 9640 9641 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9642 // optionally with VECSHL if shift is required. 9643 if (Swap) 9644 std::swap(V1, V2); 9645 if (V2.isUndef()) 9646 V2 = V1; 9647 if (ShiftElts) { 9648 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9649 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9650 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9651 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9652 } 9653 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9654 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9655 } 9656 9657 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9658 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9659 /// SDValue. 9660 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9661 SelectionDAG &DAG) const { 9662 const unsigned NumHalfWords = 8; 9663 const unsigned BytesInVector = NumHalfWords * 2; 9664 // Check that the shuffle is on half-words. 9665 if (!isNByteElemShuffleMask(N, 2, 1)) 9666 return SDValue(); 9667 9668 bool IsLE = Subtarget.isLittleEndian(); 9669 SDLoc dl(N); 9670 SDValue V1 = N->getOperand(0); 9671 SDValue V2 = N->getOperand(1); 9672 unsigned ShiftElts = 0, InsertAtByte = 0; 9673 bool Swap = false; 9674 9675 // Shifts required to get the half-word we want at element 3. 9676 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9677 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9678 9679 uint32_t Mask = 0; 9680 uint32_t OriginalOrderLow = 0x1234567; 9681 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9682 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9683 // 32-bit space, only need 4-bit nibbles per element. 9684 for (unsigned i = 0; i < NumHalfWords; ++i) { 9685 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9686 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9687 } 9688 9689 // For each mask element, find out if we're just inserting something 9690 // from V2 into V1 or vice versa. Possible permutations inserting an element 9691 // from V2 into V1: 9692 // X, 1, 2, 3, 4, 5, 6, 7 9693 // 0, X, 2, 3, 4, 5, 6, 7 9694 // 0, 1, X, 3, 4, 5, 6, 7 9695 // 0, 1, 2, X, 4, 5, 6, 7 9696 // 0, 1, 2, 3, X, 5, 6, 7 9697 // 0, 1, 2, 3, 4, X, 6, 7 9698 // 0, 1, 2, 3, 4, 5, X, 7 9699 // 0, 1, 2, 3, 4, 5, 6, X 9700 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9701 9702 bool FoundCandidate = false; 9703 // Go through the mask of half-words to find an element that's being moved 9704 // from one vector to the other. 9705 for (unsigned i = 0; i < NumHalfWords; ++i) { 9706 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9707 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9708 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9709 uint32_t TargetOrder = 0x0; 9710 9711 // If both vector operands for the shuffle are the same vector, the mask 9712 // will contain only elements from the first one and the second one will be 9713 // undef. 9714 if (V2.isUndef()) { 9715 ShiftElts = 0; 9716 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9717 TargetOrder = OriginalOrderLow; 9718 Swap = false; 9719 // Skip if not the correct element or mask of other elements don't equal 9720 // to our expected order. 9721 if (MaskOneElt == VINSERTHSrcElem && 9722 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9723 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9724 FoundCandidate = true; 9725 break; 9726 } 9727 } else { // If both operands are defined. 9728 // Target order is [8,15] if the current mask is between [0,7]. 9729 TargetOrder = 9730 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9731 // Skip if mask of other elements don't equal our expected order. 9732 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9733 // We only need the last 3 bits for the number of shifts. 9734 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9735 : BigEndianShifts[MaskOneElt & 0x7]; 9736 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9737 Swap = MaskOneElt < NumHalfWords; 9738 FoundCandidate = true; 9739 break; 9740 } 9741 } 9742 } 9743 9744 if (!FoundCandidate) 9745 return SDValue(); 9746 9747 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9748 // optionally with VECSHL if shift is required. 9749 if (Swap) 9750 std::swap(V1, V2); 9751 if (V2.isUndef()) 9752 V2 = V1; 9753 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9754 if (ShiftElts) { 9755 // Double ShiftElts because we're left shifting on v16i8 type. 9756 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9757 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9758 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9759 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9760 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9761 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9762 } 9763 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9764 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9765 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9766 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9767 } 9768 9769 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9770 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9771 /// return the default SDValue. 9772 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9773 SelectionDAG &DAG) const { 9774 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9775 // to v16i8. Peek through the bitcasts to get the actual operands. 9776 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9777 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9778 9779 auto ShuffleMask = SVN->getMask(); 9780 SDValue VecShuffle(SVN, 0); 9781 SDLoc DL(SVN); 9782 9783 // Check that we have a four byte shuffle. 9784 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9785 return SDValue(); 9786 9787 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9788 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9789 std::swap(LHS, RHS); 9790 VecShuffle = peekThroughBitcasts(DAG.getCommutedVectorShuffle(*SVN)); 9791 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle); 9792 if (!CommutedSV) 9793 return SDValue(); 9794 ShuffleMask = CommutedSV->getMask(); 9795 } 9796 9797 // Ensure that the RHS is a vector of constants. 9798 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9799 if (!BVN) 9800 return SDValue(); 9801 9802 // Check if RHS is a splat of 4-bytes (or smaller). 9803 APInt APSplatValue, APSplatUndef; 9804 unsigned SplatBitSize; 9805 bool HasAnyUndefs; 9806 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9807 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9808 SplatBitSize > 32) 9809 return SDValue(); 9810 9811 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9812 // The instruction splats a constant C into two words of the source vector 9813 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9814 // Thus we check that the shuffle mask is the equivalent of 9815 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9816 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9817 // within each word are consecutive, so we only need to check the first byte. 9818 SDValue Index; 9819 bool IsLE = Subtarget.isLittleEndian(); 9820 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9821 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9822 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9823 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9824 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9825 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9826 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9827 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9828 else 9829 return SDValue(); 9830 9831 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9832 // for XXSPLTI32DX. 9833 unsigned SplatVal = APSplatValue.getZExtValue(); 9834 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9835 SplatVal |= (SplatVal << SplatBitSize); 9836 9837 SDValue SplatNode = DAG.getNode( 9838 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9839 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9840 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9841 } 9842 9843 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9844 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9845 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9846 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9847 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9848 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9849 assert(Op.getValueType() == MVT::v1i128 && 9850 "Only set v1i128 as custom, other type shouldn't reach here!"); 9851 SDLoc dl(Op); 9852 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9853 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9854 unsigned SHLAmt = N1.getConstantOperandVal(0); 9855 if (SHLAmt % 8 == 0) { 9856 std::array<int, 16> Mask; 9857 std::iota(Mask.begin(), Mask.end(), 0); 9858 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9859 if (SDValue Shuffle = 9860 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9861 DAG.getUNDEF(MVT::v16i8), Mask)) 9862 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9863 } 9864 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9865 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9866 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9867 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9868 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9869 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9870 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9871 } 9872 9873 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9874 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9875 /// return the code it can be lowered into. Worst case, it can always be 9876 /// lowered into a vperm. 9877 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9878 SelectionDAG &DAG) const { 9879 SDLoc dl(Op); 9880 SDValue V1 = Op.getOperand(0); 9881 SDValue V2 = Op.getOperand(1); 9882 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9883 9884 // Any nodes that were combined in the target-independent combiner prior 9885 // to vector legalization will not be sent to the target combine. Try to 9886 // combine it here. 9887 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9888 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9889 return NewShuffle; 9890 Op = NewShuffle; 9891 SVOp = cast<ShuffleVectorSDNode>(Op); 9892 V1 = Op.getOperand(0); 9893 V2 = Op.getOperand(1); 9894 } 9895 EVT VT = Op.getValueType(); 9896 bool isLittleEndian = Subtarget.isLittleEndian(); 9897 9898 unsigned ShiftElts, InsertAtByte; 9899 bool Swap = false; 9900 9901 // If this is a load-and-splat, we can do that with a single instruction 9902 // in some cases. However if the load has multiple uses, we don't want to 9903 // combine it because that will just produce multiple loads. 9904 bool IsPermutedLoad = false; 9905 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9906 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9907 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9908 InputLoad->hasOneUse()) { 9909 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9910 int SplatIdx = 9911 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9912 9913 // The splat index for permuted loads will be in the left half of the vector 9914 // which is strictly wider than the loaded value by 8 bytes. So we need to 9915 // adjust the splat index to point to the correct address in memory. 9916 if (IsPermutedLoad) { 9917 assert((isLittleEndian || IsFourByte) && 9918 "Unexpected size for permuted load on big endian target"); 9919 SplatIdx += IsFourByte ? 2 : 1; 9920 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9921 "Splat of a value outside of the loaded memory"); 9922 } 9923 9924 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9925 // For 4-byte load-and-splat, we need Power9. 9926 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9927 uint64_t Offset = 0; 9928 if (IsFourByte) 9929 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9930 else 9931 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9932 9933 // If the width of the load is the same as the width of the splat, 9934 // loading with an offset would load the wrong memory. 9935 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9936 Offset = 0; 9937 9938 SDValue BasePtr = LD->getBasePtr(); 9939 if (Offset != 0) 9940 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9941 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9942 SDValue Ops[] = { 9943 LD->getChain(), // Chain 9944 BasePtr, // BasePtr 9945 DAG.getValueType(Op.getValueType()) // VT 9946 }; 9947 SDVTList VTL = 9948 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9949 SDValue LdSplt = 9950 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9951 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9952 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9953 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9954 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9955 return LdSplt; 9956 } 9957 } 9958 9959 // All v2i64 and v2f64 shuffles are legal 9960 if (VT == MVT::v2i64 || VT == MVT::v2f64) 9961 return Op; 9962 9963 if (Subtarget.hasP9Vector() && 9964 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9965 isLittleEndian)) { 9966 if (Swap) 9967 std::swap(V1, V2); 9968 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9969 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9970 if (ShiftElts) { 9971 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9972 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9973 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9974 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9975 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9976 } 9977 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9978 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9979 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9980 } 9981 9982 if (Subtarget.hasPrefixInstrs()) { 9983 SDValue SplatInsertNode; 9984 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9985 return SplatInsertNode; 9986 } 9987 9988 if (Subtarget.hasP9Altivec()) { 9989 SDValue NewISDNode; 9990 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9991 return NewISDNode; 9992 9993 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9994 return NewISDNode; 9995 } 9996 9997 if (Subtarget.hasVSX() && 9998 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9999 if (Swap) 10000 std::swap(V1, V2); 10001 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10002 SDValue Conv2 = 10003 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 10004 10005 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 10006 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10007 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 10008 } 10009 10010 if (Subtarget.hasVSX() && 10011 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 10012 if (Swap) 10013 std::swap(V1, V2); 10014 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10015 SDValue Conv2 = 10016 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 10017 10018 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 10019 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10020 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 10021 } 10022 10023 if (Subtarget.hasP9Vector()) { 10024 if (PPC::isXXBRHShuffleMask(SVOp)) { 10025 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 10026 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 10027 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 10028 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 10029 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10030 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 10031 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 10032 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 10033 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10034 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 10035 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 10036 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 10037 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 10038 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10039 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10040 } 10041 } 10042 10043 if (Subtarget.hasVSX()) { 10044 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10045 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10046 10047 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10048 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10049 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10050 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10051 } 10052 10053 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10054 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10055 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10056 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10057 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10058 } 10059 } 10060 10061 // Cases that are handled by instructions that take permute immediates 10062 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10063 // selected by the instruction selector. 10064 if (V2.isUndef()) { 10065 if (PPC::isSplatShuffleMask(SVOp, 1) || 10066 PPC::isSplatShuffleMask(SVOp, 2) || 10067 PPC::isSplatShuffleMask(SVOp, 4) || 10068 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10069 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10070 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10071 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10072 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10073 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10074 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10075 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10076 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10077 (Subtarget.hasP8Altivec() && ( 10078 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10079 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10080 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10081 return Op; 10082 } 10083 } 10084 10085 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10086 // and produce a fixed permutation. If any of these match, do not lower to 10087 // VPERM. 10088 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10089 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10090 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10091 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10092 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10093 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10094 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10095 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10096 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10097 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10098 (Subtarget.hasP8Altivec() && ( 10099 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10100 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10101 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10102 return Op; 10103 10104 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10105 // perfect shuffle table to emit an optimal matching sequence. 10106 ArrayRef<int> PermMask = SVOp->getMask(); 10107 10108 if (!DisablePerfectShuffle && !isLittleEndian) { 10109 unsigned PFIndexes[4]; 10110 bool isFourElementShuffle = true; 10111 for (unsigned i = 0; i != 4 && isFourElementShuffle; 10112 ++i) { // Element number 10113 unsigned EltNo = 8; // Start out undef. 10114 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10115 if (PermMask[i * 4 + j] < 0) 10116 continue; // Undef, ignore it. 10117 10118 unsigned ByteSource = PermMask[i * 4 + j]; 10119 if ((ByteSource & 3) != j) { 10120 isFourElementShuffle = false; 10121 break; 10122 } 10123 10124 if (EltNo == 8) { 10125 EltNo = ByteSource / 4; 10126 } else if (EltNo != ByteSource / 4) { 10127 isFourElementShuffle = false; 10128 break; 10129 } 10130 } 10131 PFIndexes[i] = EltNo; 10132 } 10133 10134 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10135 // perfect shuffle vector to determine if it is cost effective to do this as 10136 // discrete instructions, or whether we should use a vperm. 10137 // For now, we skip this for little endian until such time as we have a 10138 // little-endian perfect shuffle table. 10139 if (isFourElementShuffle) { 10140 // Compute the index in the perfect shuffle table. 10141 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10142 PFIndexes[2] * 9 + PFIndexes[3]; 10143 10144 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10145 unsigned Cost = (PFEntry >> 30); 10146 10147 // Determining when to avoid vperm is tricky. Many things affect the cost 10148 // of vperm, particularly how many times the perm mask needs to be 10149 // computed. For example, if the perm mask can be hoisted out of a loop or 10150 // is already used (perhaps because there are multiple permutes with the 10151 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the 10152 // permute mask out of the loop requires an extra register. 10153 // 10154 // As a compromise, we only emit discrete instructions if the shuffle can 10155 // be generated in 3 or fewer operations. When we have loop information 10156 // available, if this block is within a loop, we should avoid using vperm 10157 // for 3-operation perms and use a constant pool load instead. 10158 if (Cost < 3) 10159 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10160 } 10161 } 10162 10163 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10164 // vector that will get spilled to the constant pool. 10165 if (V2.isUndef()) V2 = V1; 10166 10167 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2); 10168 } 10169 10170 SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG, 10171 ArrayRef<int> PermMask, EVT VT, 10172 SDValue V1, SDValue V2) const { 10173 unsigned Opcode = PPCISD::VPERM; 10174 EVT ValType = V1.getValueType(); 10175 SDLoc dl(Op); 10176 bool NeedSwap = false; 10177 bool isLittleEndian = Subtarget.isLittleEndian(); 10178 bool isPPC64 = Subtarget.isPPC64(); 10179 10180 // Only need to place items backwards in LE, 10181 // the mask will be properly calculated. 10182 if (isLittleEndian) 10183 std::swap(V1, V2); 10184 10185 if (Subtarget.isISA3_0() && (V1->hasOneUse() || V2->hasOneUse())) { 10186 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using " 10187 "XXPERM instead\n"); 10188 Opcode = PPCISD::XXPERM; 10189 10190 // if V2 is dead, then we swap V1 and V2 so we can 10191 // use V2 as the destination instead. 10192 if (!V1->hasOneUse() && V2->hasOneUse()) { 10193 std::swap(V1, V2); 10194 NeedSwap = !NeedSwap; 10195 } 10196 } 10197 10198 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10199 // that it is in input element units, not in bytes. Convert now. 10200 10201 // For little endian, the order of the input vectors is reversed, and 10202 // the permutation mask is complemented with respect to 31. This is 10203 // necessary to produce proper semantics with the big-endian-based vperm 10204 // instruction. 10205 EVT EltVT = V1.getValueType().getVectorElementType(); 10206 unsigned BytesPerElement = EltVT.getSizeInBits() / 8; 10207 10208 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD; 10209 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD; 10210 10211 /* 10212 Vectors will be appended like so: [ V1 | v2 ] 10213 XXSWAPD on V1: 10214 [ A | B | C | D ] -> [ C | D | A | B ] 10215 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15 10216 i.e. index of A, B += 8, and index of C, D -= 8. 10217 XXSWAPD on V2: 10218 [ E | F | G | H ] -> [ G | H | E | F ] 10219 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31 10220 i.e. index of E, F += 8, index of G, H -= 8 10221 Swap V1 and V2: 10222 [ V1 | V2 ] -> [ V2 | V1 ] 10223 0-15 16-31 0-15 16-31 10224 i.e. index of V1 += 16, index of V2 -= 16 10225 */ 10226 10227 SmallVector<SDValue, 16> ResultMask; 10228 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10229 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10230 10231 if (Opcode == PPCISD::XXPERM) { 10232 if (V1HasXXSWAPD) { 10233 if (SrcElt < 8) 10234 SrcElt += 8; 10235 else if (SrcElt < 16) 10236 SrcElt -= 8; 10237 } 10238 if (V2HasXXSWAPD) { 10239 if (SrcElt > 23) 10240 SrcElt -= 8; 10241 else if (SrcElt > 15) 10242 SrcElt += 8; 10243 } 10244 if (NeedSwap) { 10245 if (SrcElt < 16) 10246 SrcElt += 16; 10247 else 10248 SrcElt -= 16; 10249 } 10250 } 10251 10252 for (unsigned j = 0; j != BytesPerElement; ++j) 10253 if (isLittleEndian) 10254 ResultMask.push_back( 10255 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32)); 10256 else 10257 ResultMask.push_back( 10258 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32)); 10259 } 10260 10261 if (Opcode == PPCISD::XXPERM && (V1HasXXSWAPD || V2HasXXSWAPD)) { 10262 if (V1HasXXSWAPD) { 10263 dl = SDLoc(V1->getOperand(0)); 10264 V1 = V1->getOperand(0)->getOperand(1); 10265 } 10266 if (V2HasXXSWAPD) { 10267 dl = SDLoc(V2->getOperand(0)); 10268 V2 = V2->getOperand(0)->getOperand(1); 10269 } 10270 if (isPPC64 && ValType != MVT::v2f64) 10271 V1 = DAG.getBitcast(MVT::v2f64, V1); 10272 if (isPPC64 && V2.getValueType() != MVT::v2f64) 10273 V2 = DAG.getBitcast(MVT::v2f64, V2); 10274 } 10275 10276 ShufflesHandledWithVPERM++; 10277 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10278 LLVM_DEBUG({ 10279 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 10280 if (Opcode == PPCISD::XXPERM) { 10281 dbgs() << "Emitting a XXPERM for the following shuffle:\n"; 10282 } else { 10283 dbgs() << "Emitting a VPERM for the following shuffle:\n"; 10284 } 10285 SVOp->dump(); 10286 dbgs() << "With the following permute control vector:\n"; 10287 VPermMask.dump(); 10288 }); 10289 10290 if (Opcode == PPCISD::XXPERM) 10291 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask); 10292 10293 SDValue VPERMNode = 10294 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask); 10295 10296 VPERMNode = DAG.getBitcast(ValType, VPERMNode); 10297 return VPERMNode; 10298 } 10299 10300 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10301 /// vector comparison. If it is, return true and fill in Opc/isDot with 10302 /// information about the intrinsic. 10303 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10304 bool &isDot, const PPCSubtarget &Subtarget) { 10305 unsigned IntrinsicID = 10306 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10307 CompareOpc = -1; 10308 isDot = false; 10309 switch (IntrinsicID) { 10310 default: 10311 return false; 10312 // Comparison predicates. 10313 case Intrinsic::ppc_altivec_vcmpbfp_p: 10314 CompareOpc = 966; 10315 isDot = true; 10316 break; 10317 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10318 CompareOpc = 198; 10319 isDot = true; 10320 break; 10321 case Intrinsic::ppc_altivec_vcmpequb_p: 10322 CompareOpc = 6; 10323 isDot = true; 10324 break; 10325 case Intrinsic::ppc_altivec_vcmpequh_p: 10326 CompareOpc = 70; 10327 isDot = true; 10328 break; 10329 case Intrinsic::ppc_altivec_vcmpequw_p: 10330 CompareOpc = 134; 10331 isDot = true; 10332 break; 10333 case Intrinsic::ppc_altivec_vcmpequd_p: 10334 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10335 CompareOpc = 199; 10336 isDot = true; 10337 } else 10338 return false; 10339 break; 10340 case Intrinsic::ppc_altivec_vcmpneb_p: 10341 case Intrinsic::ppc_altivec_vcmpneh_p: 10342 case Intrinsic::ppc_altivec_vcmpnew_p: 10343 case Intrinsic::ppc_altivec_vcmpnezb_p: 10344 case Intrinsic::ppc_altivec_vcmpnezh_p: 10345 case Intrinsic::ppc_altivec_vcmpnezw_p: 10346 if (Subtarget.hasP9Altivec()) { 10347 switch (IntrinsicID) { 10348 default: 10349 llvm_unreachable("Unknown comparison intrinsic."); 10350 case Intrinsic::ppc_altivec_vcmpneb_p: 10351 CompareOpc = 7; 10352 break; 10353 case Intrinsic::ppc_altivec_vcmpneh_p: 10354 CompareOpc = 71; 10355 break; 10356 case Intrinsic::ppc_altivec_vcmpnew_p: 10357 CompareOpc = 135; 10358 break; 10359 case Intrinsic::ppc_altivec_vcmpnezb_p: 10360 CompareOpc = 263; 10361 break; 10362 case Intrinsic::ppc_altivec_vcmpnezh_p: 10363 CompareOpc = 327; 10364 break; 10365 case Intrinsic::ppc_altivec_vcmpnezw_p: 10366 CompareOpc = 391; 10367 break; 10368 } 10369 isDot = true; 10370 } else 10371 return false; 10372 break; 10373 case Intrinsic::ppc_altivec_vcmpgefp_p: 10374 CompareOpc = 454; 10375 isDot = true; 10376 break; 10377 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10378 CompareOpc = 710; 10379 isDot = true; 10380 break; 10381 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10382 CompareOpc = 774; 10383 isDot = true; 10384 break; 10385 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10386 CompareOpc = 838; 10387 isDot = true; 10388 break; 10389 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10390 CompareOpc = 902; 10391 isDot = true; 10392 break; 10393 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10394 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10395 CompareOpc = 967; 10396 isDot = true; 10397 } else 10398 return false; 10399 break; 10400 case Intrinsic::ppc_altivec_vcmpgtub_p: 10401 CompareOpc = 518; 10402 isDot = true; 10403 break; 10404 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10405 CompareOpc = 582; 10406 isDot = true; 10407 break; 10408 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10409 CompareOpc = 646; 10410 isDot = true; 10411 break; 10412 case Intrinsic::ppc_altivec_vcmpgtud_p: 10413 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10414 CompareOpc = 711; 10415 isDot = true; 10416 } else 10417 return false; 10418 break; 10419 10420 case Intrinsic::ppc_altivec_vcmpequq: 10421 case Intrinsic::ppc_altivec_vcmpgtsq: 10422 case Intrinsic::ppc_altivec_vcmpgtuq: 10423 if (!Subtarget.isISA3_1()) 10424 return false; 10425 switch (IntrinsicID) { 10426 default: 10427 llvm_unreachable("Unknown comparison intrinsic."); 10428 case Intrinsic::ppc_altivec_vcmpequq: 10429 CompareOpc = 455; 10430 break; 10431 case Intrinsic::ppc_altivec_vcmpgtsq: 10432 CompareOpc = 903; 10433 break; 10434 case Intrinsic::ppc_altivec_vcmpgtuq: 10435 CompareOpc = 647; 10436 break; 10437 } 10438 break; 10439 10440 // VSX predicate comparisons use the same infrastructure 10441 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10442 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10443 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10444 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10445 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10446 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10447 if (Subtarget.hasVSX()) { 10448 switch (IntrinsicID) { 10449 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10450 CompareOpc = 99; 10451 break; 10452 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10453 CompareOpc = 115; 10454 break; 10455 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10456 CompareOpc = 107; 10457 break; 10458 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10459 CompareOpc = 67; 10460 break; 10461 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10462 CompareOpc = 83; 10463 break; 10464 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10465 CompareOpc = 75; 10466 break; 10467 } 10468 isDot = true; 10469 } else 10470 return false; 10471 break; 10472 10473 // Normal Comparisons. 10474 case Intrinsic::ppc_altivec_vcmpbfp: 10475 CompareOpc = 966; 10476 break; 10477 case Intrinsic::ppc_altivec_vcmpeqfp: 10478 CompareOpc = 198; 10479 break; 10480 case Intrinsic::ppc_altivec_vcmpequb: 10481 CompareOpc = 6; 10482 break; 10483 case Intrinsic::ppc_altivec_vcmpequh: 10484 CompareOpc = 70; 10485 break; 10486 case Intrinsic::ppc_altivec_vcmpequw: 10487 CompareOpc = 134; 10488 break; 10489 case Intrinsic::ppc_altivec_vcmpequd: 10490 if (Subtarget.hasP8Altivec()) 10491 CompareOpc = 199; 10492 else 10493 return false; 10494 break; 10495 case Intrinsic::ppc_altivec_vcmpneb: 10496 case Intrinsic::ppc_altivec_vcmpneh: 10497 case Intrinsic::ppc_altivec_vcmpnew: 10498 case Intrinsic::ppc_altivec_vcmpnezb: 10499 case Intrinsic::ppc_altivec_vcmpnezh: 10500 case Intrinsic::ppc_altivec_vcmpnezw: 10501 if (Subtarget.hasP9Altivec()) 10502 switch (IntrinsicID) { 10503 default: 10504 llvm_unreachable("Unknown comparison intrinsic."); 10505 case Intrinsic::ppc_altivec_vcmpneb: 10506 CompareOpc = 7; 10507 break; 10508 case Intrinsic::ppc_altivec_vcmpneh: 10509 CompareOpc = 71; 10510 break; 10511 case Intrinsic::ppc_altivec_vcmpnew: 10512 CompareOpc = 135; 10513 break; 10514 case Intrinsic::ppc_altivec_vcmpnezb: 10515 CompareOpc = 263; 10516 break; 10517 case Intrinsic::ppc_altivec_vcmpnezh: 10518 CompareOpc = 327; 10519 break; 10520 case Intrinsic::ppc_altivec_vcmpnezw: 10521 CompareOpc = 391; 10522 break; 10523 } 10524 else 10525 return false; 10526 break; 10527 case Intrinsic::ppc_altivec_vcmpgefp: 10528 CompareOpc = 454; 10529 break; 10530 case Intrinsic::ppc_altivec_vcmpgtfp: 10531 CompareOpc = 710; 10532 break; 10533 case Intrinsic::ppc_altivec_vcmpgtsb: 10534 CompareOpc = 774; 10535 break; 10536 case Intrinsic::ppc_altivec_vcmpgtsh: 10537 CompareOpc = 838; 10538 break; 10539 case Intrinsic::ppc_altivec_vcmpgtsw: 10540 CompareOpc = 902; 10541 break; 10542 case Intrinsic::ppc_altivec_vcmpgtsd: 10543 if (Subtarget.hasP8Altivec()) 10544 CompareOpc = 967; 10545 else 10546 return false; 10547 break; 10548 case Intrinsic::ppc_altivec_vcmpgtub: 10549 CompareOpc = 518; 10550 break; 10551 case Intrinsic::ppc_altivec_vcmpgtuh: 10552 CompareOpc = 582; 10553 break; 10554 case Intrinsic::ppc_altivec_vcmpgtuw: 10555 CompareOpc = 646; 10556 break; 10557 case Intrinsic::ppc_altivec_vcmpgtud: 10558 if (Subtarget.hasP8Altivec()) 10559 CompareOpc = 711; 10560 else 10561 return false; 10562 break; 10563 case Intrinsic::ppc_altivec_vcmpequq_p: 10564 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10565 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10566 if (!Subtarget.isISA3_1()) 10567 return false; 10568 switch (IntrinsicID) { 10569 default: 10570 llvm_unreachable("Unknown comparison intrinsic."); 10571 case Intrinsic::ppc_altivec_vcmpequq_p: 10572 CompareOpc = 455; 10573 break; 10574 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10575 CompareOpc = 903; 10576 break; 10577 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10578 CompareOpc = 647; 10579 break; 10580 } 10581 isDot = true; 10582 break; 10583 } 10584 return true; 10585 } 10586 10587 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10588 /// lower, do it, otherwise return null. 10589 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10590 SelectionDAG &DAG) const { 10591 unsigned IntrinsicID = 10592 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10593 10594 SDLoc dl(Op); 10595 10596 switch (IntrinsicID) { 10597 case Intrinsic::thread_pointer: 10598 // Reads the thread pointer register, used for __builtin_thread_pointer. 10599 if (Subtarget.isPPC64()) 10600 return DAG.getRegister(PPC::X13, MVT::i64); 10601 return DAG.getRegister(PPC::R2, MVT::i32); 10602 10603 case Intrinsic::ppc_mma_disassemble_acc: { 10604 if (Subtarget.isISAFuture()) { 10605 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1}; 10606 SDValue WideVec = SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, 10607 ArrayRef(ReturnTypes, 2), 10608 Op.getOperand(1)), 10609 0); 10610 SmallVector<SDValue, 4> RetOps; 10611 SDValue Value = SDValue(WideVec.getNode(), 0); 10612 SDValue Value2 = SDValue(WideVec.getNode(), 1); 10613 10614 SDValue Extract; 10615 Extract = DAG.getNode( 10616 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10617 Subtarget.isLittleEndian() ? Value2 : Value, 10618 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0, 10619 dl, getPointerTy(DAG.getDataLayout()))); 10620 RetOps.push_back(Extract); 10621 Extract = DAG.getNode( 10622 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10623 Subtarget.isLittleEndian() ? Value2 : Value, 10624 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1, 10625 dl, getPointerTy(DAG.getDataLayout()))); 10626 RetOps.push_back(Extract); 10627 Extract = DAG.getNode( 10628 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10629 Subtarget.isLittleEndian() ? Value : Value2, 10630 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0, 10631 dl, getPointerTy(DAG.getDataLayout()))); 10632 RetOps.push_back(Extract); 10633 Extract = DAG.getNode( 10634 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10635 Subtarget.isLittleEndian() ? Value : Value2, 10636 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1, 10637 dl, getPointerTy(DAG.getDataLayout()))); 10638 RetOps.push_back(Extract); 10639 return DAG.getMergeValues(RetOps, dl); 10640 } 10641 LLVM_FALLTHROUGH; 10642 } 10643 case Intrinsic::ppc_vsx_disassemble_pair: { 10644 int NumVecs = 2; 10645 SDValue WideVec = Op.getOperand(1); 10646 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10647 NumVecs = 4; 10648 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10649 } 10650 SmallVector<SDValue, 4> RetOps; 10651 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10652 SDValue Extract = DAG.getNode( 10653 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10654 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10655 : VecNo, 10656 dl, getPointerTy(DAG.getDataLayout()))); 10657 RetOps.push_back(Extract); 10658 } 10659 return DAG.getMergeValues(RetOps, dl); 10660 } 10661 10662 case Intrinsic::ppc_unpack_longdouble: { 10663 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10664 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10665 "Argument of long double unpack must be 0 or 1!"); 10666 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10667 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10668 Idx->getValueType(0))); 10669 } 10670 10671 case Intrinsic::ppc_compare_exp_lt: 10672 case Intrinsic::ppc_compare_exp_gt: 10673 case Intrinsic::ppc_compare_exp_eq: 10674 case Intrinsic::ppc_compare_exp_uo: { 10675 unsigned Pred; 10676 switch (IntrinsicID) { 10677 case Intrinsic::ppc_compare_exp_lt: 10678 Pred = PPC::PRED_LT; 10679 break; 10680 case Intrinsic::ppc_compare_exp_gt: 10681 Pred = PPC::PRED_GT; 10682 break; 10683 case Intrinsic::ppc_compare_exp_eq: 10684 Pred = PPC::PRED_EQ; 10685 break; 10686 case Intrinsic::ppc_compare_exp_uo: 10687 Pred = PPC::PRED_UN; 10688 break; 10689 } 10690 return SDValue( 10691 DAG.getMachineNode( 10692 PPC::SELECT_CC_I4, dl, MVT::i32, 10693 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10694 Op.getOperand(1), Op.getOperand(2)), 10695 0), 10696 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10697 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10698 0); 10699 } 10700 case Intrinsic::ppc_test_data_class: { 10701 EVT OpVT = Op.getOperand(1).getValueType(); 10702 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP 10703 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP 10704 : PPC::XSTSTDCSP); 10705 return SDValue( 10706 DAG.getMachineNode( 10707 PPC::SELECT_CC_I4, dl, MVT::i32, 10708 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10709 Op.getOperand(1)), 10710 0), 10711 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10712 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10713 0); 10714 } 10715 case Intrinsic::ppc_fnmsub: { 10716 EVT VT = Op.getOperand(1).getValueType(); 10717 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128)) 10718 return DAG.getNode( 10719 ISD::FNEG, dl, VT, 10720 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2), 10721 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3)))); 10722 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1), 10723 Op.getOperand(2), Op.getOperand(3)); 10724 } 10725 case Intrinsic::ppc_convert_f128_to_ppcf128: 10726 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10727 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10728 ? RTLIB::CONVERT_PPCF128_F128 10729 : RTLIB::CONVERT_F128_PPCF128; 10730 MakeLibCallOptions CallOptions; 10731 std::pair<SDValue, SDValue> Result = 10732 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10733 dl, SDValue()); 10734 return Result.first; 10735 } 10736 case Intrinsic::ppc_maxfe: 10737 case Intrinsic::ppc_maxfl: 10738 case Intrinsic::ppc_maxfs: 10739 case Intrinsic::ppc_minfe: 10740 case Intrinsic::ppc_minfl: 10741 case Intrinsic::ppc_minfs: { 10742 EVT VT = Op.getValueType(); 10743 assert( 10744 all_of(Op->ops().drop_front(4), 10745 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && 10746 "ppc_[max|min]f[e|l|s] must have uniform type arguments"); 10747 (void)VT; 10748 ISD::CondCode CC = ISD::SETGT; 10749 if (IntrinsicID == Intrinsic::ppc_minfe || 10750 IntrinsicID == Intrinsic::ppc_minfl || 10751 IntrinsicID == Intrinsic::ppc_minfs) 10752 CC = ISD::SETLT; 10753 unsigned I = Op.getNumOperands() - 2, Cnt = I; 10754 SDValue Res = Op.getOperand(I); 10755 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) { 10756 Res = 10757 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC); 10758 } 10759 return Res; 10760 } 10761 } 10762 10763 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10764 // opcode number of the comparison. 10765 int CompareOpc; 10766 bool isDot; 10767 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10768 return SDValue(); // Don't custom lower most intrinsics. 10769 10770 // If this is a non-dot comparison, make the VCMP node and we are done. 10771 if (!isDot) { 10772 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10773 Op.getOperand(1), Op.getOperand(2), 10774 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10775 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10776 } 10777 10778 // Create the PPCISD altivec 'dot' comparison node. 10779 SDValue Ops[] = { 10780 Op.getOperand(2), // LHS 10781 Op.getOperand(3), // RHS 10782 DAG.getConstant(CompareOpc, dl, MVT::i32) 10783 }; 10784 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10785 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10786 10787 // Now that we have the comparison, emit a copy from the CR to a GPR. 10788 // This is flagged to the above dot comparison. 10789 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10790 DAG.getRegister(PPC::CR6, MVT::i32), 10791 CompNode.getValue(1)); 10792 10793 // Unpack the result based on how the target uses it. 10794 unsigned BitNo; // Bit # of CR6. 10795 bool InvertBit; // Invert result? 10796 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10797 default: // Can't happen, don't crash on invalid number though. 10798 case 0: // Return the value of the EQ bit of CR6. 10799 BitNo = 0; InvertBit = false; 10800 break; 10801 case 1: // Return the inverted value of the EQ bit of CR6. 10802 BitNo = 0; InvertBit = true; 10803 break; 10804 case 2: // Return the value of the LT bit of CR6. 10805 BitNo = 2; InvertBit = false; 10806 break; 10807 case 3: // Return the inverted value of the LT bit of CR6. 10808 BitNo = 2; InvertBit = true; 10809 break; 10810 } 10811 10812 // Shift the bit into the low position. 10813 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10814 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10815 // Isolate the bit. 10816 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10817 DAG.getConstant(1, dl, MVT::i32)); 10818 10819 // If we are supposed to, toggle the bit. 10820 if (InvertBit) 10821 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10822 DAG.getConstant(1, dl, MVT::i32)); 10823 return Flags; 10824 } 10825 10826 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10827 SelectionDAG &DAG) const { 10828 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10829 // the beginning of the argument list. 10830 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10831 SDLoc DL(Op); 10832 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10833 case Intrinsic::ppc_cfence: { 10834 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10835 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10836 SDValue Val = Op.getOperand(ArgStart + 1); 10837 EVT Ty = Val.getValueType(); 10838 if (Ty == MVT::i128) { 10839 // FIXME: Testing one of two paired registers is sufficient to guarantee 10840 // ordering? 10841 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10842 } 10843 return SDValue( 10844 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10845 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10846 Op.getOperand(0)), 10847 0); 10848 } 10849 default: 10850 break; 10851 } 10852 return SDValue(); 10853 } 10854 10855 // Lower scalar BSWAP64 to xxbrd. 10856 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10857 SDLoc dl(Op); 10858 if (!Subtarget.isPPC64()) 10859 return Op; 10860 // MTVSRDD 10861 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10862 Op.getOperand(0)); 10863 // XXBRD 10864 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10865 // MFVSRD 10866 int VectorIndex = 0; 10867 if (Subtarget.isLittleEndian()) 10868 VectorIndex = 1; 10869 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10870 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10871 return Op; 10872 } 10873 10874 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10875 // compared to a value that is atomically loaded (atomic loads zero-extend). 10876 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10877 SelectionDAG &DAG) const { 10878 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10879 "Expecting an atomic compare-and-swap here."); 10880 SDLoc dl(Op); 10881 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10882 EVT MemVT = AtomicNode->getMemoryVT(); 10883 if (MemVT.getSizeInBits() >= 32) 10884 return Op; 10885 10886 SDValue CmpOp = Op.getOperand(2); 10887 // If this is already correctly zero-extended, leave it alone. 10888 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10889 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10890 return Op; 10891 10892 // Clear the high bits of the compare operand. 10893 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10894 SDValue NewCmpOp = 10895 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10896 DAG.getConstant(MaskVal, dl, MVT::i32)); 10897 10898 // Replace the existing compare operand with the properly zero-extended one. 10899 SmallVector<SDValue, 4> Ops; 10900 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10901 Ops.push_back(AtomicNode->getOperand(i)); 10902 Ops[2] = NewCmpOp; 10903 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10904 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10905 auto NodeTy = 10906 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10907 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10908 } 10909 10910 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10911 SelectionDAG &DAG) const { 10912 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10913 EVT MemVT = N->getMemoryVT(); 10914 assert(MemVT.getSimpleVT() == MVT::i128 && 10915 "Expect quadword atomic operations"); 10916 SDLoc dl(N); 10917 unsigned Opc = N->getOpcode(); 10918 switch (Opc) { 10919 case ISD::ATOMIC_LOAD: { 10920 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10921 // lowered to ppc instructions by pattern matching instruction selector. 10922 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10923 SmallVector<SDValue, 4> Ops{ 10924 N->getOperand(0), 10925 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10926 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10927 Ops.push_back(N->getOperand(I)); 10928 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10929 Ops, MemVT, N->getMemOperand()); 10930 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10931 SDValue ValHi = 10932 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10933 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10934 DAG.getConstant(64, dl, MVT::i32)); 10935 SDValue Val = 10936 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10937 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10938 {Val, LoadedVal.getValue(2)}); 10939 } 10940 case ISD::ATOMIC_STORE: { 10941 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10942 // lowered to ppc instructions by pattern matching instruction selector. 10943 SDVTList Tys = DAG.getVTList(MVT::Other); 10944 SmallVector<SDValue, 4> Ops{ 10945 N->getOperand(0), 10946 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10947 SDValue Val = N->getOperand(2); 10948 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10949 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10950 DAG.getConstant(64, dl, MVT::i32)); 10951 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10952 Ops.push_back(ValLo); 10953 Ops.push_back(ValHi); 10954 Ops.push_back(N->getOperand(1)); 10955 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10956 N->getMemOperand()); 10957 } 10958 default: 10959 llvm_unreachable("Unexpected atomic opcode"); 10960 } 10961 } 10962 10963 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10964 SelectionDAG &DAG) const { 10965 SDLoc dl(Op); 10966 // Create a stack slot that is 16-byte aligned. 10967 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10968 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10969 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10970 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10971 10972 // Store the input value into Value#0 of the stack slot. 10973 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10974 MachinePointerInfo()); 10975 // Load it out. 10976 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10977 } 10978 10979 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10980 SelectionDAG &DAG) const { 10981 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10982 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10983 10984 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10985 10986 EVT VT = Op.getValueType(); 10987 SDLoc dl(Op); 10988 SDValue V1 = Op.getOperand(0); 10989 SDValue V2 = Op.getOperand(1); 10990 10991 if (VT == MVT::v2f64 && C) 10992 return Op; 10993 10994 if (Subtarget.hasP9Vector()) { 10995 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way 10996 // because on P10, it allows this specific insert_vector_elt load pattern to 10997 // utilize the refactored load and store infrastructure in order to exploit 10998 // prefixed loads. 10999 // On targets with inexpensive direct moves (Power9 and up), a 11000 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer 11001 // load since a single precision load will involve conversion to double 11002 // precision on the load followed by another conversion to single precision. 11003 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) && 11004 (isa<LoadSDNode>(V2))) { 11005 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1); 11006 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2); 11007 SDValue InsVecElt = 11008 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector, 11009 BitcastLoad, Op.getOperand(2)); 11010 return DAG.getBitcast(MVT::v4f32, InsVecElt); 11011 } 11012 } 11013 11014 if (Subtarget.isISA3_1()) { 11015 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 11016 return SDValue(); 11017 // On P10, we have legal lowering for constant and variable indices for 11018 // all vectors. 11019 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 11020 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 11021 return Op; 11022 } 11023 11024 // Before P10, we have legal lowering for constant indices but not for 11025 // variable ones. 11026 if (!C) 11027 return SDValue(); 11028 11029 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 11030 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 11031 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 11032 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 11033 unsigned InsertAtElement = C->getZExtValue(); 11034 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 11035 if (Subtarget.isLittleEndian()) { 11036 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 11037 } 11038 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 11039 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 11040 } 11041 return Op; 11042 } 11043 11044 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 11045 SelectionDAG &DAG) const { 11046 SDLoc dl(Op); 11047 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 11048 SDValue LoadChain = LN->getChain(); 11049 SDValue BasePtr = LN->getBasePtr(); 11050 EVT VT = Op.getValueType(); 11051 11052 if (VT != MVT::v256i1 && VT != MVT::v512i1) 11053 return Op; 11054 11055 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 11056 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 11057 // 2 or 4 vsx registers. 11058 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 11059 "Type unsupported without MMA"); 11060 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 11061 "Type unsupported without paired vector support"); 11062 Align Alignment = LN->getAlign(); 11063 SmallVector<SDValue, 4> Loads; 11064 SmallVector<SDValue, 4> LoadChains; 11065 unsigned NumVecs = VT.getSizeInBits() / 128; 11066 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 11067 SDValue Load = 11068 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 11069 LN->getPointerInfo().getWithOffset(Idx * 16), 11070 commonAlignment(Alignment, Idx * 16), 11071 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 11072 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11073 DAG.getConstant(16, dl, BasePtr.getValueType())); 11074 Loads.push_back(Load); 11075 LoadChains.push_back(Load.getValue(1)); 11076 } 11077 if (Subtarget.isLittleEndian()) { 11078 std::reverse(Loads.begin(), Loads.end()); 11079 std::reverse(LoadChains.begin(), LoadChains.end()); 11080 } 11081 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 11082 SDValue Value = 11083 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 11084 dl, VT, Loads); 11085 SDValue RetOps[] = {Value, TF}; 11086 return DAG.getMergeValues(RetOps, dl); 11087 } 11088 11089 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 11090 SelectionDAG &DAG) const { 11091 SDLoc dl(Op); 11092 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 11093 SDValue StoreChain = SN->getChain(); 11094 SDValue BasePtr = SN->getBasePtr(); 11095 SDValue Value = SN->getValue(); 11096 SDValue Value2 = SN->getValue(); 11097 EVT StoreVT = Value.getValueType(); 11098 11099 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 11100 return Op; 11101 11102 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 11103 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 11104 // underlying registers individually. 11105 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 11106 "Type unsupported without MMA"); 11107 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 11108 "Type unsupported without paired vector support"); 11109 Align Alignment = SN->getAlign(); 11110 SmallVector<SDValue, 4> Stores; 11111 unsigned NumVecs = 2; 11112 if (StoreVT == MVT::v512i1) { 11113 if (Subtarget.isISAFuture()) { 11114 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1}; 11115 MachineSDNode *ExtNode = DAG.getMachineNode( 11116 PPC::DMXXEXTFDMR512, dl, ArrayRef(ReturnTypes, 2), Op.getOperand(1)); 11117 11118 Value = SDValue(ExtNode, 0); 11119 Value2 = SDValue(ExtNode, 1); 11120 } else 11121 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 11122 NumVecs = 4; 11123 } 11124 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 11125 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 11126 SDValue Elt; 11127 if (Subtarget.isISAFuture()) { 11128 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2); 11129 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 11130 Idx > 1 ? Value2 : Value, 11131 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 11132 } else 11133 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 11134 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 11135 11136 SDValue Store = 11137 DAG.getStore(StoreChain, dl, Elt, BasePtr, 11138 SN->getPointerInfo().getWithOffset(Idx * 16), 11139 commonAlignment(Alignment, Idx * 16), 11140 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 11141 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11142 DAG.getConstant(16, dl, BasePtr.getValueType())); 11143 Stores.push_back(Store); 11144 } 11145 SDValue TF = DAG.getTokenFactor(dl, Stores); 11146 return TF; 11147 } 11148 11149 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 11150 SDLoc dl(Op); 11151 if (Op.getValueType() == MVT::v4i32) { 11152 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 11153 11154 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 11155 // +16 as shift amt. 11156 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 11157 SDValue RHSSwap = // = vrlw RHS, 16 11158 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 11159 11160 // Shrinkify inputs to v8i16. 11161 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 11162 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 11163 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 11164 11165 // Low parts multiplied together, generating 32-bit results (we ignore the 11166 // top parts). 11167 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 11168 LHS, RHS, DAG, dl, MVT::v4i32); 11169 11170 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 11171 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 11172 // Shift the high parts up 16 bits. 11173 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 11174 Neg16, DAG, dl); 11175 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 11176 } else if (Op.getValueType() == MVT::v16i8) { 11177 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 11178 bool isLittleEndian = Subtarget.isLittleEndian(); 11179 11180 // Multiply the even 8-bit parts, producing 16-bit sums. 11181 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 11182 LHS, RHS, DAG, dl, MVT::v8i16); 11183 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 11184 11185 // Multiply the odd 8-bit parts, producing 16-bit sums. 11186 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 11187 LHS, RHS, DAG, dl, MVT::v8i16); 11188 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 11189 11190 // Merge the results together. Because vmuleub and vmuloub are 11191 // instructions with a big-endian bias, we must reverse the 11192 // element numbering and reverse the meaning of "odd" and "even" 11193 // when generating little endian code. 11194 int Ops[16]; 11195 for (unsigned i = 0; i != 8; ++i) { 11196 if (isLittleEndian) { 11197 Ops[i*2 ] = 2*i; 11198 Ops[i*2+1] = 2*i+16; 11199 } else { 11200 Ops[i*2 ] = 2*i+1; 11201 Ops[i*2+1] = 2*i+1+16; 11202 } 11203 } 11204 if (isLittleEndian) 11205 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 11206 else 11207 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 11208 } else { 11209 llvm_unreachable("Unknown mul to lower!"); 11210 } 11211 } 11212 11213 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11214 bool IsStrict = Op->isStrictFPOpcode(); 11215 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 11216 !Subtarget.hasP9Vector()) 11217 return SDValue(); 11218 11219 return Op; 11220 } 11221 11222 // Custom lowering for fpext vf32 to v2f64 11223 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11224 11225 assert(Op.getOpcode() == ISD::FP_EXTEND && 11226 "Should only be called for ISD::FP_EXTEND"); 11227 11228 // FIXME: handle extends from half precision float vectors on P9. 11229 // We only want to custom lower an extend from v2f32 to v2f64. 11230 if (Op.getValueType() != MVT::v2f64 || 11231 Op.getOperand(0).getValueType() != MVT::v2f32) 11232 return SDValue(); 11233 11234 SDLoc dl(Op); 11235 SDValue Op0 = Op.getOperand(0); 11236 11237 switch (Op0.getOpcode()) { 11238 default: 11239 return SDValue(); 11240 case ISD::EXTRACT_SUBVECTOR: { 11241 assert(Op0.getNumOperands() == 2 && 11242 isa<ConstantSDNode>(Op0->getOperand(1)) && 11243 "Node should have 2 operands with second one being a constant!"); 11244 11245 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 11246 return SDValue(); 11247 11248 // Custom lower is only done for high or low doubleword. 11249 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 11250 if (Idx % 2 != 0) 11251 return SDValue(); 11252 11253 // Since input is v4f32, at this point Idx is either 0 or 2. 11254 // Shift to get the doubleword position we want. 11255 int DWord = Idx >> 1; 11256 11257 // High and low word positions are different on little endian. 11258 if (Subtarget.isLittleEndian()) 11259 DWord ^= 0x1; 11260 11261 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11262 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11263 } 11264 case ISD::FADD: 11265 case ISD::FMUL: 11266 case ISD::FSUB: { 11267 SDValue NewLoad[2]; 11268 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11269 // Ensure both input are loads. 11270 SDValue LdOp = Op0.getOperand(i); 11271 if (LdOp.getOpcode() != ISD::LOAD) 11272 return SDValue(); 11273 // Generate new load node. 11274 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11275 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11276 NewLoad[i] = DAG.getMemIntrinsicNode( 11277 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11278 LD->getMemoryVT(), LD->getMemOperand()); 11279 } 11280 SDValue NewOp = 11281 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11282 NewLoad[1], Op0.getNode()->getFlags()); 11283 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11284 DAG.getConstant(0, dl, MVT::i32)); 11285 } 11286 case ISD::LOAD: { 11287 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11288 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11289 SDValue NewLd = DAG.getMemIntrinsicNode( 11290 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11291 LD->getMemoryVT(), LD->getMemOperand()); 11292 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11293 DAG.getConstant(0, dl, MVT::i32)); 11294 } 11295 } 11296 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11297 } 11298 11299 /// LowerOperation - Provide custom lowering hooks for some operations. 11300 /// 11301 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11302 switch (Op.getOpcode()) { 11303 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11304 case ISD::FPOW: return lowerPow(Op, DAG); 11305 case ISD::FSIN: return lowerSin(Op, DAG); 11306 case ISD::FCOS: return lowerCos(Op, DAG); 11307 case ISD::FLOG: return lowerLog(Op, DAG); 11308 case ISD::FLOG10: return lowerLog10(Op, DAG); 11309 case ISD::FEXP: return lowerExp(Op, DAG); 11310 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11311 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11312 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11313 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11314 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11315 case ISD::STRICT_FSETCC: 11316 case ISD::STRICT_FSETCCS: 11317 case ISD::SETCC: return LowerSETCC(Op, DAG); 11318 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11319 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11320 11321 case ISD::INLINEASM: 11322 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11323 // Variable argument lowering. 11324 case ISD::VASTART: return LowerVASTART(Op, DAG); 11325 case ISD::VAARG: return LowerVAARG(Op, DAG); 11326 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11327 11328 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11329 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11330 case ISD::GET_DYNAMIC_AREA_OFFSET: 11331 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11332 11333 // Exception handling lowering. 11334 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11335 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11336 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11337 11338 case ISD::LOAD: return LowerLOAD(Op, DAG); 11339 case ISD::STORE: return LowerSTORE(Op, DAG); 11340 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11341 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11342 case ISD::STRICT_FP_TO_UINT: 11343 case ISD::STRICT_FP_TO_SINT: 11344 case ISD::FP_TO_UINT: 11345 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11346 case ISD::STRICT_UINT_TO_FP: 11347 case ISD::STRICT_SINT_TO_FP: 11348 case ISD::UINT_TO_FP: 11349 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11350 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG); 11351 11352 // Lower 64-bit shifts. 11353 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11354 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11355 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11356 11357 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11358 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11359 11360 // Vector-related lowering. 11361 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11362 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11363 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11364 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11365 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11366 case ISD::MUL: return LowerMUL(Op, DAG); 11367 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11368 case ISD::STRICT_FP_ROUND: 11369 case ISD::FP_ROUND: 11370 return LowerFP_ROUND(Op, DAG); 11371 case ISD::ROTL: return LowerROTL(Op, DAG); 11372 11373 // For counter-based loop handling. 11374 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11375 11376 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11377 11378 // Frame & Return address. 11379 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11380 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11381 11382 case ISD::INTRINSIC_VOID: 11383 return LowerINTRINSIC_VOID(Op, DAG); 11384 case ISD::BSWAP: 11385 return LowerBSWAP(Op, DAG); 11386 case ISD::ATOMIC_CMP_SWAP: 11387 return LowerATOMIC_CMP_SWAP(Op, DAG); 11388 case ISD::ATOMIC_STORE: 11389 return LowerATOMIC_LOAD_STORE(Op, DAG); 11390 } 11391 } 11392 11393 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11394 SmallVectorImpl<SDValue>&Results, 11395 SelectionDAG &DAG) const { 11396 SDLoc dl(N); 11397 switch (N->getOpcode()) { 11398 default: 11399 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11400 case ISD::ATOMIC_LOAD: { 11401 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11402 Results.push_back(Res); 11403 Results.push_back(Res.getValue(1)); 11404 break; 11405 } 11406 case ISD::READCYCLECOUNTER: { 11407 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11408 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11409 11410 Results.push_back( 11411 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11412 Results.push_back(RTB.getValue(2)); 11413 break; 11414 } 11415 case ISD::INTRINSIC_W_CHAIN: { 11416 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11417 Intrinsic::loop_decrement) 11418 break; 11419 11420 assert(N->getValueType(0) == MVT::i1 && 11421 "Unexpected result type for CTR decrement intrinsic"); 11422 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11423 N->getValueType(0)); 11424 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11425 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11426 N->getOperand(1)); 11427 11428 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11429 Results.push_back(NewInt.getValue(1)); 11430 break; 11431 } 11432 case ISD::INTRINSIC_WO_CHAIN: { 11433 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11434 case Intrinsic::ppc_pack_longdouble: 11435 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11436 N->getOperand(2), N->getOperand(1))); 11437 break; 11438 case Intrinsic::ppc_maxfe: 11439 case Intrinsic::ppc_minfe: 11440 case Intrinsic::ppc_fnmsub: 11441 case Intrinsic::ppc_convert_f128_to_ppcf128: 11442 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11443 break; 11444 } 11445 break; 11446 } 11447 case ISD::VAARG: { 11448 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11449 return; 11450 11451 EVT VT = N->getValueType(0); 11452 11453 if (VT == MVT::i64) { 11454 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11455 11456 Results.push_back(NewNode); 11457 Results.push_back(NewNode.getValue(1)); 11458 } 11459 return; 11460 } 11461 case ISD::STRICT_FP_TO_SINT: 11462 case ISD::STRICT_FP_TO_UINT: 11463 case ISD::FP_TO_SINT: 11464 case ISD::FP_TO_UINT: { 11465 // LowerFP_TO_INT() can only handle f32 and f64. 11466 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11467 MVT::ppcf128) 11468 return; 11469 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl); 11470 Results.push_back(LoweredValue); 11471 if (N->isStrictFPOpcode()) 11472 Results.push_back(LoweredValue.getValue(1)); 11473 return; 11474 } 11475 case ISD::TRUNCATE: { 11476 if (!N->getValueType(0).isVector()) 11477 return; 11478 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11479 if (Lowered) 11480 Results.push_back(Lowered); 11481 return; 11482 } 11483 case ISD::FSHL: 11484 case ISD::FSHR: 11485 // Don't handle funnel shifts here. 11486 return; 11487 case ISD::BITCAST: 11488 // Don't handle bitcast here. 11489 return; 11490 case ISD::FP_EXTEND: 11491 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11492 if (Lowered) 11493 Results.push_back(Lowered); 11494 return; 11495 } 11496 } 11497 11498 //===----------------------------------------------------------------------===// 11499 // Other Lowering Code 11500 //===----------------------------------------------------------------------===// 11501 11502 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11503 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11504 Function *Func = Intrinsic::getDeclaration(M, Id); 11505 return Builder.CreateCall(Func, {}); 11506 } 11507 11508 // The mappings for emitLeading/TrailingFence is taken from 11509 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11510 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11511 Instruction *Inst, 11512 AtomicOrdering Ord) const { 11513 if (Ord == AtomicOrdering::SequentiallyConsistent) 11514 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11515 if (isReleaseOrStronger(Ord)) 11516 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11517 return nullptr; 11518 } 11519 11520 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11521 Instruction *Inst, 11522 AtomicOrdering Ord) const { 11523 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11524 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11525 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11526 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11527 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11528 return Builder.CreateCall( 11529 Intrinsic::getDeclaration( 11530 Builder.GetInsertBlock()->getParent()->getParent(), 11531 Intrinsic::ppc_cfence, {Inst->getType()}), 11532 {Inst}); 11533 // FIXME: Can use isync for rmw operation. 11534 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11535 } 11536 return nullptr; 11537 } 11538 11539 MachineBasicBlock * 11540 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11541 unsigned AtomicSize, 11542 unsigned BinOpcode, 11543 unsigned CmpOpcode, 11544 unsigned CmpPred) const { 11545 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11546 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11547 11548 auto LoadMnemonic = PPC::LDARX; 11549 auto StoreMnemonic = PPC::STDCX; 11550 switch (AtomicSize) { 11551 default: 11552 llvm_unreachable("Unexpected size of atomic entity"); 11553 case 1: 11554 LoadMnemonic = PPC::LBARX; 11555 StoreMnemonic = PPC::STBCX; 11556 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11557 break; 11558 case 2: 11559 LoadMnemonic = PPC::LHARX; 11560 StoreMnemonic = PPC::STHCX; 11561 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11562 break; 11563 case 4: 11564 LoadMnemonic = PPC::LWARX; 11565 StoreMnemonic = PPC::STWCX; 11566 break; 11567 case 8: 11568 LoadMnemonic = PPC::LDARX; 11569 StoreMnemonic = PPC::STDCX; 11570 break; 11571 } 11572 11573 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11574 MachineFunction *F = BB->getParent(); 11575 MachineFunction::iterator It = ++BB->getIterator(); 11576 11577 Register dest = MI.getOperand(0).getReg(); 11578 Register ptrA = MI.getOperand(1).getReg(); 11579 Register ptrB = MI.getOperand(2).getReg(); 11580 Register incr = MI.getOperand(3).getReg(); 11581 DebugLoc dl = MI.getDebugLoc(); 11582 11583 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11584 MachineBasicBlock *loop2MBB = 11585 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11586 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11587 F->insert(It, loopMBB); 11588 if (CmpOpcode) 11589 F->insert(It, loop2MBB); 11590 F->insert(It, exitMBB); 11591 exitMBB->splice(exitMBB->begin(), BB, 11592 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11593 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11594 11595 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11596 Register TmpReg = (!BinOpcode) ? incr : 11597 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11598 : &PPC::GPRCRegClass); 11599 11600 // thisMBB: 11601 // ... 11602 // fallthrough --> loopMBB 11603 BB->addSuccessor(loopMBB); 11604 11605 // loopMBB: 11606 // l[wd]arx dest, ptr 11607 // add r0, dest, incr 11608 // st[wd]cx. r0, ptr 11609 // bne- loopMBB 11610 // fallthrough --> exitMBB 11611 11612 // For max/min... 11613 // loopMBB: 11614 // l[wd]arx dest, ptr 11615 // cmpl?[wd] dest, incr 11616 // bgt exitMBB 11617 // loop2MBB: 11618 // st[wd]cx. dest, ptr 11619 // bne- loopMBB 11620 // fallthrough --> exitMBB 11621 11622 BB = loopMBB; 11623 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11624 .addReg(ptrA).addReg(ptrB); 11625 if (BinOpcode) 11626 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11627 if (CmpOpcode) { 11628 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11629 // Signed comparisons of byte or halfword values must be sign-extended. 11630 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11631 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11632 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11633 ExtReg).addReg(dest); 11634 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr); 11635 } else 11636 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr); 11637 11638 BuildMI(BB, dl, TII->get(PPC::BCC)) 11639 .addImm(CmpPred) 11640 .addReg(CrReg) 11641 .addMBB(exitMBB); 11642 BB->addSuccessor(loop2MBB); 11643 BB->addSuccessor(exitMBB); 11644 BB = loop2MBB; 11645 } 11646 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11647 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11648 BuildMI(BB, dl, TII->get(PPC::BCC)) 11649 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11650 BB->addSuccessor(loopMBB); 11651 BB->addSuccessor(exitMBB); 11652 11653 // exitMBB: 11654 // ... 11655 BB = exitMBB; 11656 return BB; 11657 } 11658 11659 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11660 switch(MI.getOpcode()) { 11661 default: 11662 return false; 11663 case PPC::COPY: 11664 return TII->isSignExtended(MI.getOperand(1).getReg(), 11665 &MI.getMF()->getRegInfo()); 11666 case PPC::LHA: 11667 case PPC::LHA8: 11668 case PPC::LHAU: 11669 case PPC::LHAU8: 11670 case PPC::LHAUX: 11671 case PPC::LHAUX8: 11672 case PPC::LHAX: 11673 case PPC::LHAX8: 11674 case PPC::LWA: 11675 case PPC::LWAUX: 11676 case PPC::LWAX: 11677 case PPC::LWAX_32: 11678 case PPC::LWA_32: 11679 case PPC::PLHA: 11680 case PPC::PLHA8: 11681 case PPC::PLHA8pc: 11682 case PPC::PLHApc: 11683 case PPC::PLWA: 11684 case PPC::PLWA8: 11685 case PPC::PLWA8pc: 11686 case PPC::PLWApc: 11687 case PPC::EXTSB: 11688 case PPC::EXTSB8: 11689 case PPC::EXTSB8_32_64: 11690 case PPC::EXTSB8_rec: 11691 case PPC::EXTSB_rec: 11692 case PPC::EXTSH: 11693 case PPC::EXTSH8: 11694 case PPC::EXTSH8_32_64: 11695 case PPC::EXTSH8_rec: 11696 case PPC::EXTSH_rec: 11697 case PPC::EXTSW: 11698 case PPC::EXTSWSLI: 11699 case PPC::EXTSWSLI_32_64: 11700 case PPC::EXTSWSLI_32_64_rec: 11701 case PPC::EXTSWSLI_rec: 11702 case PPC::EXTSW_32: 11703 case PPC::EXTSW_32_64: 11704 case PPC::EXTSW_32_64_rec: 11705 case PPC::EXTSW_rec: 11706 case PPC::SRAW: 11707 case PPC::SRAWI: 11708 case PPC::SRAWI_rec: 11709 case PPC::SRAW_rec: 11710 return true; 11711 } 11712 return false; 11713 } 11714 11715 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11716 MachineInstr &MI, MachineBasicBlock *BB, 11717 bool is8bit, // operation 11718 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11719 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11720 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11721 11722 // If this is a signed comparison and the value being compared is not known 11723 // to be sign extended, sign extend it here. 11724 DebugLoc dl = MI.getDebugLoc(); 11725 MachineFunction *F = BB->getParent(); 11726 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11727 Register incr = MI.getOperand(3).getReg(); 11728 bool IsSignExtended = 11729 incr.isVirtual() && isSignExtended(*RegInfo.getVRegDef(incr), TII); 11730 11731 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11732 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11733 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11734 .addReg(MI.getOperand(3).getReg()); 11735 MI.getOperand(3).setReg(ValueReg); 11736 } 11737 // If we support part-word atomic mnemonics, just use them 11738 if (Subtarget.hasPartwordAtomics()) 11739 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11740 CmpPred); 11741 11742 // In 64 bit mode we have to use 64 bits for addresses, even though the 11743 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11744 // registers without caring whether they're 32 or 64, but here we're 11745 // doing actual arithmetic on the addresses. 11746 bool is64bit = Subtarget.isPPC64(); 11747 bool isLittleEndian = Subtarget.isLittleEndian(); 11748 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11749 11750 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11751 MachineFunction::iterator It = ++BB->getIterator(); 11752 11753 Register dest = MI.getOperand(0).getReg(); 11754 Register ptrA = MI.getOperand(1).getReg(); 11755 Register ptrB = MI.getOperand(2).getReg(); 11756 11757 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11758 MachineBasicBlock *loop2MBB = 11759 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11760 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11761 F->insert(It, loopMBB); 11762 if (CmpOpcode) 11763 F->insert(It, loop2MBB); 11764 F->insert(It, exitMBB); 11765 exitMBB->splice(exitMBB->begin(), BB, 11766 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11767 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11768 11769 const TargetRegisterClass *RC = 11770 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11771 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11772 11773 Register PtrReg = RegInfo.createVirtualRegister(RC); 11774 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11775 Register ShiftReg = 11776 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11777 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11778 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11779 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11780 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11781 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11782 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11783 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11784 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11785 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11786 Register Ptr1Reg; 11787 Register TmpReg = 11788 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11789 11790 // thisMBB: 11791 // ... 11792 // fallthrough --> loopMBB 11793 BB->addSuccessor(loopMBB); 11794 11795 // The 4-byte load must be aligned, while a char or short may be 11796 // anywhere in the word. Hence all this nasty bookkeeping code. 11797 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11798 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11799 // xori shift, shift1, 24 [16] 11800 // rlwinm ptr, ptr1, 0, 0, 29 11801 // slw incr2, incr, shift 11802 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11803 // slw mask, mask2, shift 11804 // loopMBB: 11805 // lwarx tmpDest, ptr 11806 // add tmp, tmpDest, incr2 11807 // andc tmp2, tmpDest, mask 11808 // and tmp3, tmp, mask 11809 // or tmp4, tmp3, tmp2 11810 // stwcx. tmp4, ptr 11811 // bne- loopMBB 11812 // fallthrough --> exitMBB 11813 // srw SrwDest, tmpDest, shift 11814 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11815 if (ptrA != ZeroReg) { 11816 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11817 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11818 .addReg(ptrA) 11819 .addReg(ptrB); 11820 } else { 11821 Ptr1Reg = ptrB; 11822 } 11823 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11824 // mode. 11825 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11826 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11827 .addImm(3) 11828 .addImm(27) 11829 .addImm(is8bit ? 28 : 27); 11830 if (!isLittleEndian) 11831 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11832 .addReg(Shift1Reg) 11833 .addImm(is8bit ? 24 : 16); 11834 if (is64bit) 11835 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11836 .addReg(Ptr1Reg) 11837 .addImm(0) 11838 .addImm(61); 11839 else 11840 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11841 .addReg(Ptr1Reg) 11842 .addImm(0) 11843 .addImm(0) 11844 .addImm(29); 11845 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11846 if (is8bit) 11847 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11848 else { 11849 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11850 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11851 .addReg(Mask3Reg) 11852 .addImm(65535); 11853 } 11854 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11855 .addReg(Mask2Reg) 11856 .addReg(ShiftReg); 11857 11858 BB = loopMBB; 11859 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11860 .addReg(ZeroReg) 11861 .addReg(PtrReg); 11862 if (BinOpcode) 11863 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11864 .addReg(Incr2Reg) 11865 .addReg(TmpDestReg); 11866 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11867 .addReg(TmpDestReg) 11868 .addReg(MaskReg); 11869 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11870 if (CmpOpcode) { 11871 // For unsigned comparisons, we can directly compare the shifted values. 11872 // For signed comparisons we shift and sign extend. 11873 Register SReg = RegInfo.createVirtualRegister(GPRC); 11874 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11875 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11876 .addReg(TmpDestReg) 11877 .addReg(MaskReg); 11878 unsigned ValueReg = SReg; 11879 unsigned CmpReg = Incr2Reg; 11880 if (CmpOpcode == PPC::CMPW) { 11881 ValueReg = RegInfo.createVirtualRegister(GPRC); 11882 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11883 .addReg(SReg) 11884 .addReg(ShiftReg); 11885 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11886 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11887 .addReg(ValueReg); 11888 ValueReg = ValueSReg; 11889 CmpReg = incr; 11890 } 11891 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg); 11892 BuildMI(BB, dl, TII->get(PPC::BCC)) 11893 .addImm(CmpPred) 11894 .addReg(CrReg) 11895 .addMBB(exitMBB); 11896 BB->addSuccessor(loop2MBB); 11897 BB->addSuccessor(exitMBB); 11898 BB = loop2MBB; 11899 } 11900 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11901 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11902 .addReg(Tmp4Reg) 11903 .addReg(ZeroReg) 11904 .addReg(PtrReg); 11905 BuildMI(BB, dl, TII->get(PPC::BCC)) 11906 .addImm(PPC::PRED_NE) 11907 .addReg(PPC::CR0) 11908 .addMBB(loopMBB); 11909 BB->addSuccessor(loopMBB); 11910 BB->addSuccessor(exitMBB); 11911 11912 // exitMBB: 11913 // ... 11914 BB = exitMBB; 11915 // Since the shift amount is not a constant, we need to clear 11916 // the upper bits with a separate RLWINM. 11917 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11918 .addReg(SrwDestReg) 11919 .addImm(0) 11920 .addImm(is8bit ? 24 : 16) 11921 .addImm(31); 11922 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11923 .addReg(TmpDestReg) 11924 .addReg(ShiftReg); 11925 return BB; 11926 } 11927 11928 llvm::MachineBasicBlock * 11929 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11930 MachineBasicBlock *MBB) const { 11931 DebugLoc DL = MI.getDebugLoc(); 11932 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11933 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11934 11935 MachineFunction *MF = MBB->getParent(); 11936 MachineRegisterInfo &MRI = MF->getRegInfo(); 11937 11938 const BasicBlock *BB = MBB->getBasicBlock(); 11939 MachineFunction::iterator I = ++MBB->getIterator(); 11940 11941 Register DstReg = MI.getOperand(0).getReg(); 11942 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11943 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11944 Register mainDstReg = MRI.createVirtualRegister(RC); 11945 Register restoreDstReg = MRI.createVirtualRegister(RC); 11946 11947 MVT PVT = getPointerTy(MF->getDataLayout()); 11948 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11949 "Invalid Pointer Size!"); 11950 // For v = setjmp(buf), we generate 11951 // 11952 // thisMBB: 11953 // SjLjSetup mainMBB 11954 // bl mainMBB 11955 // v_restore = 1 11956 // b sinkMBB 11957 // 11958 // mainMBB: 11959 // buf[LabelOffset] = LR 11960 // v_main = 0 11961 // 11962 // sinkMBB: 11963 // v = phi(main, restore) 11964 // 11965 11966 MachineBasicBlock *thisMBB = MBB; 11967 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11968 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11969 MF->insert(I, mainMBB); 11970 MF->insert(I, sinkMBB); 11971 11972 MachineInstrBuilder MIB; 11973 11974 // Transfer the remainder of BB and its successor edges to sinkMBB. 11975 sinkMBB->splice(sinkMBB->begin(), MBB, 11976 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11977 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11978 11979 // Note that the structure of the jmp_buf used here is not compatible 11980 // with that used by libc, and is not designed to be. Specifically, it 11981 // stores only those 'reserved' registers that LLVM does not otherwise 11982 // understand how to spill. Also, by convention, by the time this 11983 // intrinsic is called, Clang has already stored the frame address in the 11984 // first slot of the buffer and stack address in the third. Following the 11985 // X86 target code, we'll store the jump address in the second slot. We also 11986 // need to save the TOC pointer (R2) to handle jumps between shared 11987 // libraries, and that will be stored in the fourth slot. The thread 11988 // identifier (R13) is not affected. 11989 11990 // thisMBB: 11991 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11992 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11993 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11994 11995 // Prepare IP either in reg. 11996 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11997 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11998 Register BufReg = MI.getOperand(1).getReg(); 11999 12000 if (Subtarget.is64BitELFABI()) { 12001 setUsesTOCBasePtr(*MBB->getParent()); 12002 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 12003 .addReg(PPC::X2) 12004 .addImm(TOCOffset) 12005 .addReg(BufReg) 12006 .cloneMemRefs(MI); 12007 } 12008 12009 // Naked functions never have a base pointer, and so we use r1. For all 12010 // other functions, this decision must be delayed until during PEI. 12011 unsigned BaseReg; 12012 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 12013 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 12014 else 12015 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 12016 12017 MIB = BuildMI(*thisMBB, MI, DL, 12018 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 12019 .addReg(BaseReg) 12020 .addImm(BPOffset) 12021 .addReg(BufReg) 12022 .cloneMemRefs(MI); 12023 12024 // Setup 12025 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 12026 MIB.addRegMask(TRI->getNoPreservedMask()); 12027 12028 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 12029 12030 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 12031 .addMBB(mainMBB); 12032 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 12033 12034 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 12035 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 12036 12037 // mainMBB: 12038 // mainDstReg = 0 12039 MIB = 12040 BuildMI(mainMBB, DL, 12041 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 12042 12043 // Store IP 12044 if (Subtarget.isPPC64()) { 12045 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 12046 .addReg(LabelReg) 12047 .addImm(LabelOffset) 12048 .addReg(BufReg); 12049 } else { 12050 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 12051 .addReg(LabelReg) 12052 .addImm(LabelOffset) 12053 .addReg(BufReg); 12054 } 12055 MIB.cloneMemRefs(MI); 12056 12057 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 12058 mainMBB->addSuccessor(sinkMBB); 12059 12060 // sinkMBB: 12061 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12062 TII->get(PPC::PHI), DstReg) 12063 .addReg(mainDstReg).addMBB(mainMBB) 12064 .addReg(restoreDstReg).addMBB(thisMBB); 12065 12066 MI.eraseFromParent(); 12067 return sinkMBB; 12068 } 12069 12070 MachineBasicBlock * 12071 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 12072 MachineBasicBlock *MBB) const { 12073 DebugLoc DL = MI.getDebugLoc(); 12074 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12075 12076 MachineFunction *MF = MBB->getParent(); 12077 MachineRegisterInfo &MRI = MF->getRegInfo(); 12078 12079 MVT PVT = getPointerTy(MF->getDataLayout()); 12080 assert((PVT == MVT::i64 || PVT == MVT::i32) && 12081 "Invalid Pointer Size!"); 12082 12083 const TargetRegisterClass *RC = 12084 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12085 Register Tmp = MRI.createVirtualRegister(RC); 12086 // Since FP is only updated here but NOT referenced, it's treated as GPR. 12087 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 12088 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 12089 unsigned BP = 12090 (PVT == MVT::i64) 12091 ? PPC::X30 12092 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 12093 : PPC::R30); 12094 12095 MachineInstrBuilder MIB; 12096 12097 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 12098 const int64_t SPOffset = 2 * PVT.getStoreSize(); 12099 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 12100 const int64_t BPOffset = 4 * PVT.getStoreSize(); 12101 12102 Register BufReg = MI.getOperand(0).getReg(); 12103 12104 // Reload FP (the jumped-to function may not have had a 12105 // frame pointer, and if so, then its r31 will be restored 12106 // as necessary). 12107 if (PVT == MVT::i64) { 12108 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 12109 .addImm(0) 12110 .addReg(BufReg); 12111 } else { 12112 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 12113 .addImm(0) 12114 .addReg(BufReg); 12115 } 12116 MIB.cloneMemRefs(MI); 12117 12118 // Reload IP 12119 if (PVT == MVT::i64) { 12120 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 12121 .addImm(LabelOffset) 12122 .addReg(BufReg); 12123 } else { 12124 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 12125 .addImm(LabelOffset) 12126 .addReg(BufReg); 12127 } 12128 MIB.cloneMemRefs(MI); 12129 12130 // Reload SP 12131 if (PVT == MVT::i64) { 12132 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 12133 .addImm(SPOffset) 12134 .addReg(BufReg); 12135 } else { 12136 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 12137 .addImm(SPOffset) 12138 .addReg(BufReg); 12139 } 12140 MIB.cloneMemRefs(MI); 12141 12142 // Reload BP 12143 if (PVT == MVT::i64) { 12144 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 12145 .addImm(BPOffset) 12146 .addReg(BufReg); 12147 } else { 12148 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 12149 .addImm(BPOffset) 12150 .addReg(BufReg); 12151 } 12152 MIB.cloneMemRefs(MI); 12153 12154 // Reload TOC 12155 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 12156 setUsesTOCBasePtr(*MBB->getParent()); 12157 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 12158 .addImm(TOCOffset) 12159 .addReg(BufReg) 12160 .cloneMemRefs(MI); 12161 } 12162 12163 // Jump 12164 BuildMI(*MBB, MI, DL, 12165 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 12166 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 12167 12168 MI.eraseFromParent(); 12169 return MBB; 12170 } 12171 12172 bool PPCTargetLowering::hasInlineStackProbe(const MachineFunction &MF) const { 12173 // If the function specifically requests inline stack probes, emit them. 12174 if (MF.getFunction().hasFnAttribute("probe-stack")) 12175 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 12176 "inline-asm"; 12177 return false; 12178 } 12179 12180 unsigned PPCTargetLowering::getStackProbeSize(const MachineFunction &MF) const { 12181 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 12182 unsigned StackAlign = TFI->getStackAlignment(); 12183 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 12184 "Unexpected stack alignment"); 12185 // The default stack probe size is 4096 if the function has no 12186 // stack-probe-size attribute. 12187 const Function &Fn = MF.getFunction(); 12188 unsigned StackProbeSize = 12189 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096); 12190 // Round down to the stack alignment. 12191 StackProbeSize &= ~(StackAlign - 1); 12192 return StackProbeSize ? StackProbeSize : StackAlign; 12193 } 12194 12195 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 12196 // into three phases. In the first phase, it uses pseudo instruction 12197 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 12198 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 12199 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 12200 // MaxCallFrameSize so that it can calculate correct data area pointer. 12201 MachineBasicBlock * 12202 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 12203 MachineBasicBlock *MBB) const { 12204 const bool isPPC64 = Subtarget.isPPC64(); 12205 MachineFunction *MF = MBB->getParent(); 12206 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12207 DebugLoc DL = MI.getDebugLoc(); 12208 const unsigned ProbeSize = getStackProbeSize(*MF); 12209 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 12210 MachineRegisterInfo &MRI = MF->getRegInfo(); 12211 // The CFG of probing stack looks as 12212 // +-----+ 12213 // | MBB | 12214 // +--+--+ 12215 // | 12216 // +----v----+ 12217 // +--->+ TestMBB +---+ 12218 // | +----+----+ | 12219 // | | | 12220 // | +-----v----+ | 12221 // +---+ BlockMBB | | 12222 // +----------+ | 12223 // | 12224 // +---------+ | 12225 // | TailMBB +<--+ 12226 // +---------+ 12227 // In MBB, calculate previous frame pointer and final stack pointer. 12228 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 12229 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 12230 // TailMBB is spliced via \p MI. 12231 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 12232 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 12233 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 12234 12235 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 12236 MF->insert(MBBIter, TestMBB); 12237 MF->insert(MBBIter, BlockMBB); 12238 MF->insert(MBBIter, TailMBB); 12239 12240 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 12241 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12242 12243 Register DstReg = MI.getOperand(0).getReg(); 12244 Register NegSizeReg = MI.getOperand(1).getReg(); 12245 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 12246 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12247 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12248 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12249 12250 // Since value of NegSizeReg might be realigned in prologepilog, insert a 12251 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 12252 // NegSize. 12253 unsigned ProbeOpc; 12254 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 12255 ProbeOpc = 12256 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 12257 else 12258 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 12259 // and NegSizeReg will be allocated in the same phyreg to avoid 12260 // redundant copy when NegSizeReg has only one use which is current MI and 12261 // will be replaced by PREPARE_PROBED_ALLOCA then. 12262 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 12263 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 12264 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 12265 .addDef(ActualNegSizeReg) 12266 .addReg(NegSizeReg) 12267 .add(MI.getOperand(2)) 12268 .add(MI.getOperand(3)); 12269 12270 // Calculate final stack pointer, which equals to SP + ActualNegSize. 12271 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 12272 FinalStackPtr) 12273 .addReg(SPReg) 12274 .addReg(ActualNegSizeReg); 12275 12276 // Materialize a scratch register for update. 12277 int64_t NegProbeSize = -(int64_t)ProbeSize; 12278 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12279 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12280 if (!isInt<16>(NegProbeSize)) { 12281 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12282 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12283 .addImm(NegProbeSize >> 16); 12284 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12285 ScratchReg) 12286 .addReg(TempReg) 12287 .addImm(NegProbeSize & 0xFFFF); 12288 } else 12289 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12290 .addImm(NegProbeSize); 12291 12292 { 12293 // Probing leading residual part. 12294 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12295 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12296 .addReg(ActualNegSizeReg) 12297 .addReg(ScratchReg); 12298 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12299 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12300 .addReg(Div) 12301 .addReg(ScratchReg); 12302 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12303 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12304 .addReg(Mul) 12305 .addReg(ActualNegSizeReg); 12306 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12307 .addReg(FramePointer) 12308 .addReg(SPReg) 12309 .addReg(NegMod); 12310 } 12311 12312 { 12313 // Remaining part should be multiple of ProbeSize. 12314 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12315 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12316 .addReg(SPReg) 12317 .addReg(FinalStackPtr); 12318 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12319 .addImm(PPC::PRED_EQ) 12320 .addReg(CmpResult) 12321 .addMBB(TailMBB); 12322 TestMBB->addSuccessor(BlockMBB); 12323 TestMBB->addSuccessor(TailMBB); 12324 } 12325 12326 { 12327 // Touch the block. 12328 // |P...|P...|P... 12329 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12330 .addReg(FramePointer) 12331 .addReg(SPReg) 12332 .addReg(ScratchReg); 12333 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12334 BlockMBB->addSuccessor(TestMBB); 12335 } 12336 12337 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12338 // DYNAREAOFFSET pseudo instruction to get the future result. 12339 Register MaxCallFrameSizeReg = 12340 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12341 BuildMI(TailMBB, DL, 12342 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12343 MaxCallFrameSizeReg) 12344 .add(MI.getOperand(2)) 12345 .add(MI.getOperand(3)); 12346 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12347 .addReg(SPReg) 12348 .addReg(MaxCallFrameSizeReg); 12349 12350 // Splice instructions after MI to TailMBB. 12351 TailMBB->splice(TailMBB->end(), MBB, 12352 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12353 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12354 MBB->addSuccessor(TestMBB); 12355 12356 // Delete the pseudo instruction. 12357 MI.eraseFromParent(); 12358 12359 ++NumDynamicAllocaProbed; 12360 return TailMBB; 12361 } 12362 12363 MachineBasicBlock * 12364 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12365 MachineBasicBlock *BB) const { 12366 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12367 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12368 if (Subtarget.is64BitELFABI() && 12369 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12370 !Subtarget.isUsingPCRelativeCalls()) { 12371 // Call lowering should have added an r2 operand to indicate a dependence 12372 // on the TOC base pointer value. It can't however, because there is no 12373 // way to mark the dependence as implicit there, and so the stackmap code 12374 // will confuse it with a regular operand. Instead, add the dependence 12375 // here. 12376 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12377 } 12378 12379 return emitPatchPoint(MI, BB); 12380 } 12381 12382 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12383 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12384 return emitEHSjLjSetJmp(MI, BB); 12385 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12386 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12387 return emitEHSjLjLongJmp(MI, BB); 12388 } 12389 12390 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12391 12392 // To "insert" these instructions we actually have to insert their 12393 // control-flow patterns. 12394 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12395 MachineFunction::iterator It = ++BB->getIterator(); 12396 12397 MachineFunction *F = BB->getParent(); 12398 MachineRegisterInfo &MRI = F->getRegInfo(); 12399 12400 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12401 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12402 MI.getOpcode() == PPC::SELECT_I8) { 12403 SmallVector<MachineOperand, 2> Cond; 12404 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12405 MI.getOpcode() == PPC::SELECT_CC_I8) 12406 Cond.push_back(MI.getOperand(4)); 12407 else 12408 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12409 Cond.push_back(MI.getOperand(1)); 12410 12411 DebugLoc dl = MI.getDebugLoc(); 12412 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12413 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12414 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12415 MI.getOpcode() == PPC::SELECT_CC_F8 || 12416 MI.getOpcode() == PPC::SELECT_CC_F16 || 12417 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12418 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12419 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12420 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12421 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12422 MI.getOpcode() == PPC::SELECT_CC_SPE || 12423 MI.getOpcode() == PPC::SELECT_F4 || 12424 MI.getOpcode() == PPC::SELECT_F8 || 12425 MI.getOpcode() == PPC::SELECT_F16 || 12426 MI.getOpcode() == PPC::SELECT_SPE || 12427 MI.getOpcode() == PPC::SELECT_SPE4 || 12428 MI.getOpcode() == PPC::SELECT_VRRC || 12429 MI.getOpcode() == PPC::SELECT_VSFRC || 12430 MI.getOpcode() == PPC::SELECT_VSSRC || 12431 MI.getOpcode() == PPC::SELECT_VSRC) { 12432 // The incoming instruction knows the destination vreg to set, the 12433 // condition code register to branch on, the true/false values to 12434 // select between, and a branch opcode to use. 12435 12436 // thisMBB: 12437 // ... 12438 // TrueVal = ... 12439 // cmpTY ccX, r1, r2 12440 // bCC copy1MBB 12441 // fallthrough --> copy0MBB 12442 MachineBasicBlock *thisMBB = BB; 12443 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12444 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12445 DebugLoc dl = MI.getDebugLoc(); 12446 F->insert(It, copy0MBB); 12447 F->insert(It, sinkMBB); 12448 12449 // Transfer the remainder of BB and its successor edges to sinkMBB. 12450 sinkMBB->splice(sinkMBB->begin(), BB, 12451 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12452 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12453 12454 // Next, add the true and fallthrough blocks as its successors. 12455 BB->addSuccessor(copy0MBB); 12456 BB->addSuccessor(sinkMBB); 12457 12458 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12459 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12460 MI.getOpcode() == PPC::SELECT_F16 || 12461 MI.getOpcode() == PPC::SELECT_SPE4 || 12462 MI.getOpcode() == PPC::SELECT_SPE || 12463 MI.getOpcode() == PPC::SELECT_VRRC || 12464 MI.getOpcode() == PPC::SELECT_VSFRC || 12465 MI.getOpcode() == PPC::SELECT_VSSRC || 12466 MI.getOpcode() == PPC::SELECT_VSRC) { 12467 BuildMI(BB, dl, TII->get(PPC::BC)) 12468 .addReg(MI.getOperand(1).getReg()) 12469 .addMBB(sinkMBB); 12470 } else { 12471 unsigned SelectPred = MI.getOperand(4).getImm(); 12472 BuildMI(BB, dl, TII->get(PPC::BCC)) 12473 .addImm(SelectPred) 12474 .addReg(MI.getOperand(1).getReg()) 12475 .addMBB(sinkMBB); 12476 } 12477 12478 // copy0MBB: 12479 // %FalseValue = ... 12480 // # fallthrough to sinkMBB 12481 BB = copy0MBB; 12482 12483 // Update machine-CFG edges 12484 BB->addSuccessor(sinkMBB); 12485 12486 // sinkMBB: 12487 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12488 // ... 12489 BB = sinkMBB; 12490 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12491 .addReg(MI.getOperand(3).getReg()) 12492 .addMBB(copy0MBB) 12493 .addReg(MI.getOperand(2).getReg()) 12494 .addMBB(thisMBB); 12495 } else if (MI.getOpcode() == PPC::ReadTB) { 12496 // To read the 64-bit time-base register on a 32-bit target, we read the 12497 // two halves. Should the counter have wrapped while it was being read, we 12498 // need to try again. 12499 // ... 12500 // readLoop: 12501 // mfspr Rx,TBU # load from TBU 12502 // mfspr Ry,TB # load from TB 12503 // mfspr Rz,TBU # load from TBU 12504 // cmpw crX,Rx,Rz # check if 'old'='new' 12505 // bne readLoop # branch if they're not equal 12506 // ... 12507 12508 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12509 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12510 DebugLoc dl = MI.getDebugLoc(); 12511 F->insert(It, readMBB); 12512 F->insert(It, sinkMBB); 12513 12514 // Transfer the remainder of BB and its successor edges to sinkMBB. 12515 sinkMBB->splice(sinkMBB->begin(), BB, 12516 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12517 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12518 12519 BB->addSuccessor(readMBB); 12520 BB = readMBB; 12521 12522 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12523 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12524 Register LoReg = MI.getOperand(0).getReg(); 12525 Register HiReg = MI.getOperand(1).getReg(); 12526 12527 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12528 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12529 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12530 12531 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12532 12533 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12534 .addReg(HiReg) 12535 .addReg(ReadAgainReg); 12536 BuildMI(BB, dl, TII->get(PPC::BCC)) 12537 .addImm(PPC::PRED_NE) 12538 .addReg(CmpReg) 12539 .addMBB(readMBB); 12540 12541 BB->addSuccessor(readMBB); 12542 BB->addSuccessor(sinkMBB); 12543 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12544 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12546 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12548 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12550 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12551 12552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12553 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12555 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12557 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12559 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12560 12561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12562 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12564 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12566 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12568 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12569 12570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12571 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12573 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12575 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12576 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12577 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12578 12579 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12580 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12582 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12583 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12584 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12585 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12586 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12587 12588 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12589 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12591 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12592 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12593 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12594 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12595 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12596 12597 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12598 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LT); 12599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12600 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LT); 12601 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12602 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LT); 12603 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12604 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LT); 12605 12606 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12607 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GT); 12608 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12609 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GT); 12610 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12611 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GT); 12612 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12613 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GT); 12614 12615 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12616 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LT); 12617 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12618 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LT); 12619 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12620 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LT); 12621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12622 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LT); 12623 12624 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12625 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GT); 12626 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12627 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GT); 12628 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12629 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GT); 12630 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12631 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GT); 12632 12633 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12634 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12635 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12636 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12637 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12638 BB = EmitAtomicBinary(MI, BB, 4, 0); 12639 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12640 BB = EmitAtomicBinary(MI, BB, 8, 0); 12641 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12642 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12643 (Subtarget.hasPartwordAtomics() && 12644 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12645 (Subtarget.hasPartwordAtomics() && 12646 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12647 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12648 12649 auto LoadMnemonic = PPC::LDARX; 12650 auto StoreMnemonic = PPC::STDCX; 12651 switch (MI.getOpcode()) { 12652 default: 12653 llvm_unreachable("Compare and swap of unknown size"); 12654 case PPC::ATOMIC_CMP_SWAP_I8: 12655 LoadMnemonic = PPC::LBARX; 12656 StoreMnemonic = PPC::STBCX; 12657 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12658 break; 12659 case PPC::ATOMIC_CMP_SWAP_I16: 12660 LoadMnemonic = PPC::LHARX; 12661 StoreMnemonic = PPC::STHCX; 12662 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12663 break; 12664 case PPC::ATOMIC_CMP_SWAP_I32: 12665 LoadMnemonic = PPC::LWARX; 12666 StoreMnemonic = PPC::STWCX; 12667 break; 12668 case PPC::ATOMIC_CMP_SWAP_I64: 12669 LoadMnemonic = PPC::LDARX; 12670 StoreMnemonic = PPC::STDCX; 12671 break; 12672 } 12673 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12674 Register dest = MI.getOperand(0).getReg(); 12675 Register ptrA = MI.getOperand(1).getReg(); 12676 Register ptrB = MI.getOperand(2).getReg(); 12677 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12678 Register oldval = MI.getOperand(3).getReg(); 12679 Register newval = MI.getOperand(4).getReg(); 12680 DebugLoc dl = MI.getDebugLoc(); 12681 12682 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12683 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12684 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12685 F->insert(It, loop1MBB); 12686 F->insert(It, loop2MBB); 12687 F->insert(It, exitMBB); 12688 exitMBB->splice(exitMBB->begin(), BB, 12689 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12690 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12691 12692 // thisMBB: 12693 // ... 12694 // fallthrough --> loopMBB 12695 BB->addSuccessor(loop1MBB); 12696 12697 // loop1MBB: 12698 // l[bhwd]arx dest, ptr 12699 // cmp[wd] dest, oldval 12700 // bne- exitBB 12701 // loop2MBB: 12702 // st[bhwd]cx. newval, ptr 12703 // bne- loopMBB 12704 // b exitBB 12705 // exitBB: 12706 BB = loop1MBB; 12707 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12708 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg) 12709 .addReg(dest) 12710 .addReg(oldval); 12711 BuildMI(BB, dl, TII->get(PPC::BCC)) 12712 .addImm(PPC::PRED_NE) 12713 .addReg(CrReg) 12714 .addMBB(exitMBB); 12715 BB->addSuccessor(loop2MBB); 12716 BB->addSuccessor(exitMBB); 12717 12718 BB = loop2MBB; 12719 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12720 .addReg(newval) 12721 .addReg(ptrA) 12722 .addReg(ptrB); 12723 BuildMI(BB, dl, TII->get(PPC::BCC)) 12724 .addImm(PPC::PRED_NE) 12725 .addReg(PPC::CR0) 12726 .addMBB(loop1MBB); 12727 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12728 BB->addSuccessor(loop1MBB); 12729 BB->addSuccessor(exitMBB); 12730 12731 // exitMBB: 12732 // ... 12733 BB = exitMBB; 12734 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12735 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12736 // We must use 64-bit registers for addresses when targeting 64-bit, 12737 // since we're actually doing arithmetic on them. Other registers 12738 // can be 32-bit. 12739 bool is64bit = Subtarget.isPPC64(); 12740 bool isLittleEndian = Subtarget.isLittleEndian(); 12741 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12742 12743 Register dest = MI.getOperand(0).getReg(); 12744 Register ptrA = MI.getOperand(1).getReg(); 12745 Register ptrB = MI.getOperand(2).getReg(); 12746 Register oldval = MI.getOperand(3).getReg(); 12747 Register newval = MI.getOperand(4).getReg(); 12748 DebugLoc dl = MI.getDebugLoc(); 12749 12750 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12751 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12752 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12753 F->insert(It, loop1MBB); 12754 F->insert(It, loop2MBB); 12755 F->insert(It, exitMBB); 12756 exitMBB->splice(exitMBB->begin(), BB, 12757 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12758 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12759 12760 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12761 const TargetRegisterClass *RC = 12762 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12763 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12764 12765 Register PtrReg = RegInfo.createVirtualRegister(RC); 12766 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12767 Register ShiftReg = 12768 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12769 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12770 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12771 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12772 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12773 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12774 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12775 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12776 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12777 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12778 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12779 Register Ptr1Reg; 12780 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12781 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12782 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12783 // thisMBB: 12784 // ... 12785 // fallthrough --> loopMBB 12786 BB->addSuccessor(loop1MBB); 12787 12788 // The 4-byte load must be aligned, while a char or short may be 12789 // anywhere in the word. Hence all this nasty bookkeeping code. 12790 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12791 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12792 // xori shift, shift1, 24 [16] 12793 // rlwinm ptr, ptr1, 0, 0, 29 12794 // slw newval2, newval, shift 12795 // slw oldval2, oldval,shift 12796 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12797 // slw mask, mask2, shift 12798 // and newval3, newval2, mask 12799 // and oldval3, oldval2, mask 12800 // loop1MBB: 12801 // lwarx tmpDest, ptr 12802 // and tmp, tmpDest, mask 12803 // cmpw tmp, oldval3 12804 // bne- exitBB 12805 // loop2MBB: 12806 // andc tmp2, tmpDest, mask 12807 // or tmp4, tmp2, newval3 12808 // stwcx. tmp4, ptr 12809 // bne- loop1MBB 12810 // b exitBB 12811 // exitBB: 12812 // srw dest, tmpDest, shift 12813 if (ptrA != ZeroReg) { 12814 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12815 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12816 .addReg(ptrA) 12817 .addReg(ptrB); 12818 } else { 12819 Ptr1Reg = ptrB; 12820 } 12821 12822 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12823 // mode. 12824 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12825 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12826 .addImm(3) 12827 .addImm(27) 12828 .addImm(is8bit ? 28 : 27); 12829 if (!isLittleEndian) 12830 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12831 .addReg(Shift1Reg) 12832 .addImm(is8bit ? 24 : 16); 12833 if (is64bit) 12834 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12835 .addReg(Ptr1Reg) 12836 .addImm(0) 12837 .addImm(61); 12838 else 12839 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12840 .addReg(Ptr1Reg) 12841 .addImm(0) 12842 .addImm(0) 12843 .addImm(29); 12844 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12845 .addReg(newval) 12846 .addReg(ShiftReg); 12847 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12848 .addReg(oldval) 12849 .addReg(ShiftReg); 12850 if (is8bit) 12851 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12852 else { 12853 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12854 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12855 .addReg(Mask3Reg) 12856 .addImm(65535); 12857 } 12858 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12859 .addReg(Mask2Reg) 12860 .addReg(ShiftReg); 12861 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12862 .addReg(NewVal2Reg) 12863 .addReg(MaskReg); 12864 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12865 .addReg(OldVal2Reg) 12866 .addReg(MaskReg); 12867 12868 BB = loop1MBB; 12869 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12870 .addReg(ZeroReg) 12871 .addReg(PtrReg); 12872 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12873 .addReg(TmpDestReg) 12874 .addReg(MaskReg); 12875 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg) 12876 .addReg(TmpReg) 12877 .addReg(OldVal3Reg); 12878 BuildMI(BB, dl, TII->get(PPC::BCC)) 12879 .addImm(PPC::PRED_NE) 12880 .addReg(CrReg) 12881 .addMBB(exitMBB); 12882 BB->addSuccessor(loop2MBB); 12883 BB->addSuccessor(exitMBB); 12884 12885 BB = loop2MBB; 12886 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12887 .addReg(TmpDestReg) 12888 .addReg(MaskReg); 12889 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12890 .addReg(Tmp2Reg) 12891 .addReg(NewVal3Reg); 12892 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12893 .addReg(Tmp4Reg) 12894 .addReg(ZeroReg) 12895 .addReg(PtrReg); 12896 BuildMI(BB, dl, TII->get(PPC::BCC)) 12897 .addImm(PPC::PRED_NE) 12898 .addReg(PPC::CR0) 12899 .addMBB(loop1MBB); 12900 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12901 BB->addSuccessor(loop1MBB); 12902 BB->addSuccessor(exitMBB); 12903 12904 // exitMBB: 12905 // ... 12906 BB = exitMBB; 12907 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12908 .addReg(TmpReg) 12909 .addReg(ShiftReg); 12910 } else if (MI.getOpcode() == PPC::FADDrtz) { 12911 // This pseudo performs an FADD with rounding mode temporarily forced 12912 // to round-to-zero. We emit this via custom inserter since the FPSCR 12913 // is not modeled at the SelectionDAG level. 12914 Register Dest = MI.getOperand(0).getReg(); 12915 Register Src1 = MI.getOperand(1).getReg(); 12916 Register Src2 = MI.getOperand(2).getReg(); 12917 DebugLoc dl = MI.getDebugLoc(); 12918 12919 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12920 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12921 12922 // Save FPSCR value. 12923 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12924 12925 // Set rounding mode to round-to-zero. 12926 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12927 .addImm(31) 12928 .addReg(PPC::RM, RegState::ImplicitDefine); 12929 12930 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12931 .addImm(30) 12932 .addReg(PPC::RM, RegState::ImplicitDefine); 12933 12934 // Perform addition. 12935 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12936 .addReg(Src1) 12937 .addReg(Src2); 12938 if (MI.getFlag(MachineInstr::NoFPExcept)) 12939 MIB.setMIFlag(MachineInstr::NoFPExcept); 12940 12941 // Restore FPSCR value. 12942 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12943 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12944 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12945 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12946 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12947 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12948 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12949 ? PPC::ANDI8_rec 12950 : PPC::ANDI_rec; 12951 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12952 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12953 12954 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12955 Register Dest = RegInfo.createVirtualRegister( 12956 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12957 12958 DebugLoc Dl = MI.getDebugLoc(); 12959 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12960 .addReg(MI.getOperand(1).getReg()) 12961 .addImm(1); 12962 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12963 MI.getOperand(0).getReg()) 12964 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12965 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12966 DebugLoc Dl = MI.getDebugLoc(); 12967 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12968 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12969 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12970 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12971 MI.getOperand(0).getReg()) 12972 .addReg(CRReg); 12973 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12974 DebugLoc Dl = MI.getDebugLoc(); 12975 unsigned Imm = MI.getOperand(1).getImm(); 12976 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12977 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12978 MI.getOperand(0).getReg()) 12979 .addReg(PPC::CR0EQ); 12980 } else if (MI.getOpcode() == PPC::SETRNDi) { 12981 DebugLoc dl = MI.getDebugLoc(); 12982 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12983 12984 // Save FPSCR value. 12985 if (MRI.use_empty(OldFPSCRReg)) 12986 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12987 else 12988 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12989 12990 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12991 // the following settings: 12992 // 00 Round to nearest 12993 // 01 Round to 0 12994 // 10 Round to +inf 12995 // 11 Round to -inf 12996 12997 // When the operand is immediate, using the two least significant bits of 12998 // the immediate to set the bits 62:63 of FPSCR. 12999 unsigned Mode = MI.getOperand(1).getImm(); 13000 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 13001 .addImm(31) 13002 .addReg(PPC::RM, RegState::ImplicitDefine); 13003 13004 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 13005 .addImm(30) 13006 .addReg(PPC::RM, RegState::ImplicitDefine); 13007 } else if (MI.getOpcode() == PPC::SETRND) { 13008 DebugLoc dl = MI.getDebugLoc(); 13009 13010 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 13011 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 13012 // If the target doesn't have DirectMove, we should use stack to do the 13013 // conversion, because the target doesn't have the instructions like mtvsrd 13014 // or mfvsrd to do this conversion directly. 13015 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 13016 if (Subtarget.hasDirectMove()) { 13017 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 13018 .addReg(SrcReg); 13019 } else { 13020 // Use stack to do the register copy. 13021 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 13022 MachineRegisterInfo &RegInfo = F->getRegInfo(); 13023 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 13024 if (RC == &PPC::F8RCRegClass) { 13025 // Copy register from F8RCRegClass to G8RCRegclass. 13026 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 13027 "Unsupported RegClass."); 13028 13029 StoreOp = PPC::STFD; 13030 LoadOp = PPC::LD; 13031 } else { 13032 // Copy register from G8RCRegClass to F8RCRegclass. 13033 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 13034 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 13035 "Unsupported RegClass."); 13036 } 13037 13038 MachineFrameInfo &MFI = F->getFrameInfo(); 13039 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 13040 13041 MachineMemOperand *MMOStore = F->getMachineMemOperand( 13042 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 13043 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 13044 MFI.getObjectAlign(FrameIdx)); 13045 13046 // Store the SrcReg into the stack. 13047 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 13048 .addReg(SrcReg) 13049 .addImm(0) 13050 .addFrameIndex(FrameIdx) 13051 .addMemOperand(MMOStore); 13052 13053 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 13054 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 13055 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 13056 MFI.getObjectAlign(FrameIdx)); 13057 13058 // Load from the stack where SrcReg is stored, and save to DestReg, 13059 // so we have done the RegClass conversion from RegClass::SrcReg to 13060 // RegClass::DestReg. 13061 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 13062 .addImm(0) 13063 .addFrameIndex(FrameIdx) 13064 .addMemOperand(MMOLoad); 13065 } 13066 }; 13067 13068 Register OldFPSCRReg = MI.getOperand(0).getReg(); 13069 13070 // Save FPSCR value. 13071 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 13072 13073 // When the operand is gprc register, use two least significant bits of the 13074 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 13075 // 13076 // copy OldFPSCRTmpReg, OldFPSCRReg 13077 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 13078 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 13079 // copy NewFPSCRReg, NewFPSCRTmpReg 13080 // mtfsf 255, NewFPSCRReg 13081 MachineOperand SrcOp = MI.getOperand(1); 13082 MachineRegisterInfo &RegInfo = F->getRegInfo(); 13083 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13084 13085 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 13086 13087 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13088 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13089 13090 // The first operand of INSERT_SUBREG should be a register which has 13091 // subregisters, we only care about its RegClass, so we should use an 13092 // IMPLICIT_DEF register. 13093 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 13094 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 13095 .addReg(ImDefReg) 13096 .add(SrcOp) 13097 .addImm(1); 13098 13099 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13100 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 13101 .addReg(OldFPSCRTmpReg) 13102 .addReg(ExtSrcReg) 13103 .addImm(0) 13104 .addImm(62); 13105 13106 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 13107 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 13108 13109 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 13110 // bits of FPSCR. 13111 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 13112 .addImm(255) 13113 .addReg(NewFPSCRReg) 13114 .addImm(0) 13115 .addImm(0); 13116 } else if (MI.getOpcode() == PPC::SETFLM) { 13117 DebugLoc Dl = MI.getDebugLoc(); 13118 13119 // Result of setflm is previous FPSCR content, so we need to save it first. 13120 Register OldFPSCRReg = MI.getOperand(0).getReg(); 13121 if (MRI.use_empty(OldFPSCRReg)) 13122 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 13123 else 13124 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 13125 13126 // Put bits in 32:63 to FPSCR. 13127 Register NewFPSCRReg = MI.getOperand(1).getReg(); 13128 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 13129 .addImm(255) 13130 .addReg(NewFPSCRReg) 13131 .addImm(0) 13132 .addImm(0); 13133 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 13134 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 13135 return emitProbedAlloca(MI, BB); 13136 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 13137 DebugLoc DL = MI.getDebugLoc(); 13138 Register Src = MI.getOperand(2).getReg(); 13139 Register Lo = MI.getOperand(0).getReg(); 13140 Register Hi = MI.getOperand(1).getReg(); 13141 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 13142 .addDef(Lo) 13143 .addUse(Src, 0, PPC::sub_gp8_x1); 13144 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 13145 .addDef(Hi) 13146 .addUse(Src, 0, PPC::sub_gp8_x0); 13147 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 13148 MI.getOpcode() == PPC::STQX_PSEUDO) { 13149 DebugLoc DL = MI.getDebugLoc(); 13150 // Ptr is used as the ptr_rc_no_r0 part 13151 // of LQ/STQ's memory operand and adding result of RA and RB, 13152 // so it has to be g8rc_and_g8rc_nox0. 13153 Register Ptr = 13154 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 13155 Register Val = MI.getOperand(0).getReg(); 13156 Register RA = MI.getOperand(1).getReg(); 13157 Register RB = MI.getOperand(2).getReg(); 13158 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 13159 BuildMI(*BB, MI, DL, 13160 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 13161 : TII->get(PPC::STQ)) 13162 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 13163 .addImm(0) 13164 .addReg(Ptr); 13165 } else { 13166 llvm_unreachable("Unexpected instr type to insert"); 13167 } 13168 13169 MI.eraseFromParent(); // The pseudo instruction is gone now. 13170 return BB; 13171 } 13172 13173 //===----------------------------------------------------------------------===// 13174 // Target Optimization Hooks 13175 //===----------------------------------------------------------------------===// 13176 13177 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 13178 // For the estimates, convergence is quadratic, so we essentially double the 13179 // number of digits correct after every iteration. For both FRE and FRSQRTE, 13180 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 13181 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 13182 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 13183 if (VT.getScalarType() == MVT::f64) 13184 RefinementSteps++; 13185 return RefinementSteps; 13186 } 13187 13188 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 13189 const DenormalMode &Mode) const { 13190 // We only have VSX Vector Test for software Square Root. 13191 EVT VT = Op.getValueType(); 13192 if (!isTypeLegal(MVT::i1) || 13193 (VT != MVT::f64 && 13194 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 13195 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 13196 13197 SDLoc DL(Op); 13198 // The output register of FTSQRT is CR field. 13199 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 13200 // ftsqrt BF,FRB 13201 // Let e_b be the unbiased exponent of the double-precision 13202 // floating-point operand in register FRB. 13203 // fe_flag is set to 1 if either of the following conditions occurs. 13204 // - The double-precision floating-point operand in register FRB is a zero, 13205 // a NaN, or an infinity, or a negative value. 13206 // - e_b is less than or equal to -970. 13207 // Otherwise fe_flag is set to 0. 13208 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 13209 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 13210 // exponent is less than -970) 13211 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 13212 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 13213 FTSQRT, SRIdxVal), 13214 0); 13215 } 13216 13217 SDValue 13218 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 13219 SelectionDAG &DAG) const { 13220 // We only have VSX Vector Square Root. 13221 EVT VT = Op.getValueType(); 13222 if (VT != MVT::f64 && 13223 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 13224 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 13225 13226 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 13227 } 13228 13229 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 13230 int Enabled, int &RefinementSteps, 13231 bool &UseOneConstNR, 13232 bool Reciprocal) const { 13233 EVT VT = Operand.getValueType(); 13234 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 13235 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 13236 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13237 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13238 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13239 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13240 13241 // The Newton-Raphson computation with a single constant does not provide 13242 // enough accuracy on some CPUs. 13243 UseOneConstNR = !Subtarget.needsTwoConstNR(); 13244 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 13245 } 13246 return SDValue(); 13247 } 13248 13249 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 13250 int Enabled, 13251 int &RefinementSteps) const { 13252 EVT VT = Operand.getValueType(); 13253 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 13254 (VT == MVT::f64 && Subtarget.hasFRE()) || 13255 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13256 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13257 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13258 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13259 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 13260 } 13261 return SDValue(); 13262 } 13263 13264 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 13265 // Note: This functionality is used only when unsafe-fp-math is enabled, and 13266 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13267 // enabled for division), this functionality is redundant with the default 13268 // combiner logic (once the division -> reciprocal/multiply transformation 13269 // has taken place). As a result, this matters more for older cores than for 13270 // newer ones. 13271 13272 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13273 // reciprocal if there are two or more FDIVs (for embedded cores with only 13274 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13275 switch (Subtarget.getCPUDirective()) { 13276 default: 13277 return 3; 13278 case PPC::DIR_440: 13279 case PPC::DIR_A2: 13280 case PPC::DIR_E500: 13281 case PPC::DIR_E500mc: 13282 case PPC::DIR_E5500: 13283 return 2; 13284 } 13285 } 13286 13287 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13288 // collapsed, and so we need to look through chains of them. 13289 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13290 int64_t& Offset, SelectionDAG &DAG) { 13291 if (DAG.isBaseWithConstantOffset(Loc)) { 13292 Base = Loc.getOperand(0); 13293 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13294 13295 // The base might itself be a base plus an offset, and if so, accumulate 13296 // that as well. 13297 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13298 } 13299 } 13300 13301 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13302 unsigned Bytes, int Dist, 13303 SelectionDAG &DAG) { 13304 if (VT.getSizeInBits() / 8 != Bytes) 13305 return false; 13306 13307 SDValue BaseLoc = Base->getBasePtr(); 13308 if (Loc.getOpcode() == ISD::FrameIndex) { 13309 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13310 return false; 13311 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13312 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13313 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13314 int FS = MFI.getObjectSize(FI); 13315 int BFS = MFI.getObjectSize(BFI); 13316 if (FS != BFS || FS != (int)Bytes) return false; 13317 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13318 } 13319 13320 SDValue Base1 = Loc, Base2 = BaseLoc; 13321 int64_t Offset1 = 0, Offset2 = 0; 13322 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13323 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13324 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13325 return true; 13326 13327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13328 const GlobalValue *GV1 = nullptr; 13329 const GlobalValue *GV2 = nullptr; 13330 Offset1 = 0; 13331 Offset2 = 0; 13332 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13333 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13334 if (isGA1 && isGA2 && GV1 == GV2) 13335 return Offset1 == (Offset2 + Dist*Bytes); 13336 return false; 13337 } 13338 13339 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13340 // not enforce equality of the chain operands. 13341 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13342 unsigned Bytes, int Dist, 13343 SelectionDAG &DAG) { 13344 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13345 EVT VT = LS->getMemoryVT(); 13346 SDValue Loc = LS->getBasePtr(); 13347 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13348 } 13349 13350 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13351 EVT VT; 13352 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13353 default: return false; 13354 case Intrinsic::ppc_altivec_lvx: 13355 case Intrinsic::ppc_altivec_lvxl: 13356 case Intrinsic::ppc_vsx_lxvw4x: 13357 case Intrinsic::ppc_vsx_lxvw4x_be: 13358 VT = MVT::v4i32; 13359 break; 13360 case Intrinsic::ppc_vsx_lxvd2x: 13361 case Intrinsic::ppc_vsx_lxvd2x_be: 13362 VT = MVT::v2f64; 13363 break; 13364 case Intrinsic::ppc_altivec_lvebx: 13365 VT = MVT::i8; 13366 break; 13367 case Intrinsic::ppc_altivec_lvehx: 13368 VT = MVT::i16; 13369 break; 13370 case Intrinsic::ppc_altivec_lvewx: 13371 VT = MVT::i32; 13372 break; 13373 } 13374 13375 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13376 } 13377 13378 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13379 EVT VT; 13380 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13381 default: return false; 13382 case Intrinsic::ppc_altivec_stvx: 13383 case Intrinsic::ppc_altivec_stvxl: 13384 case Intrinsic::ppc_vsx_stxvw4x: 13385 VT = MVT::v4i32; 13386 break; 13387 case Intrinsic::ppc_vsx_stxvd2x: 13388 VT = MVT::v2f64; 13389 break; 13390 case Intrinsic::ppc_vsx_stxvw4x_be: 13391 VT = MVT::v4i32; 13392 break; 13393 case Intrinsic::ppc_vsx_stxvd2x_be: 13394 VT = MVT::v2f64; 13395 break; 13396 case Intrinsic::ppc_altivec_stvebx: 13397 VT = MVT::i8; 13398 break; 13399 case Intrinsic::ppc_altivec_stvehx: 13400 VT = MVT::i16; 13401 break; 13402 case Intrinsic::ppc_altivec_stvewx: 13403 VT = MVT::i32; 13404 break; 13405 } 13406 13407 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13408 } 13409 13410 return false; 13411 } 13412 13413 // Return true is there is a nearyby consecutive load to the one provided 13414 // (regardless of alignment). We search up and down the chain, looking though 13415 // token factors and other loads (but nothing else). As a result, a true result 13416 // indicates that it is safe to create a new consecutive load adjacent to the 13417 // load provided. 13418 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13419 SDValue Chain = LD->getChain(); 13420 EVT VT = LD->getMemoryVT(); 13421 13422 SmallSet<SDNode *, 16> LoadRoots; 13423 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13424 SmallSet<SDNode *, 16> Visited; 13425 13426 // First, search up the chain, branching to follow all token-factor operands. 13427 // If we find a consecutive load, then we're done, otherwise, record all 13428 // nodes just above the top-level loads and token factors. 13429 while (!Queue.empty()) { 13430 SDNode *ChainNext = Queue.pop_back_val(); 13431 if (!Visited.insert(ChainNext).second) 13432 continue; 13433 13434 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13435 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13436 return true; 13437 13438 if (!Visited.count(ChainLD->getChain().getNode())) 13439 Queue.push_back(ChainLD->getChain().getNode()); 13440 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13441 for (const SDUse &O : ChainNext->ops()) 13442 if (!Visited.count(O.getNode())) 13443 Queue.push_back(O.getNode()); 13444 } else 13445 LoadRoots.insert(ChainNext); 13446 } 13447 13448 // Second, search down the chain, starting from the top-level nodes recorded 13449 // in the first phase. These top-level nodes are the nodes just above all 13450 // loads and token factors. Starting with their uses, recursively look though 13451 // all loads (just the chain uses) and token factors to find a consecutive 13452 // load. 13453 Visited.clear(); 13454 Queue.clear(); 13455 13456 for (SDNode *I : LoadRoots) { 13457 Queue.push_back(I); 13458 13459 while (!Queue.empty()) { 13460 SDNode *LoadRoot = Queue.pop_back_val(); 13461 if (!Visited.insert(LoadRoot).second) 13462 continue; 13463 13464 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13465 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13466 return true; 13467 13468 for (SDNode *U : LoadRoot->uses()) 13469 if (((isa<MemSDNode>(U) && 13470 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13471 U->getOpcode() == ISD::TokenFactor) && 13472 !Visited.count(U)) 13473 Queue.push_back(U); 13474 } 13475 } 13476 13477 return false; 13478 } 13479 13480 /// This function is called when we have proved that a SETCC node can be replaced 13481 /// by subtraction (and other supporting instructions) so that the result of 13482 /// comparison is kept in a GPR instead of CR. This function is purely for 13483 /// codegen purposes and has some flags to guide the codegen process. 13484 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13485 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13486 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13487 13488 // Zero extend the operands to the largest legal integer. Originally, they 13489 // must be of a strictly smaller size. 13490 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13491 DAG.getConstant(Size, DL, MVT::i32)); 13492 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13493 DAG.getConstant(Size, DL, MVT::i32)); 13494 13495 // Swap if needed. Depends on the condition code. 13496 if (Swap) 13497 std::swap(Op0, Op1); 13498 13499 // Subtract extended integers. 13500 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13501 13502 // Move the sign bit to the least significant position and zero out the rest. 13503 // Now the least significant bit carries the result of original comparison. 13504 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13505 DAG.getConstant(Size - 1, DL, MVT::i32)); 13506 auto Final = Shifted; 13507 13508 // Complement the result if needed. Based on the condition code. 13509 if (Complement) 13510 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13511 DAG.getConstant(1, DL, MVT::i64)); 13512 13513 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13514 } 13515 13516 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13517 DAGCombinerInfo &DCI) const { 13518 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13519 13520 SelectionDAG &DAG = DCI.DAG; 13521 SDLoc DL(N); 13522 13523 // Size of integers being compared has a critical role in the following 13524 // analysis, so we prefer to do this when all types are legal. 13525 if (!DCI.isAfterLegalizeDAG()) 13526 return SDValue(); 13527 13528 // If all users of SETCC extend its value to a legal integer type 13529 // then we replace SETCC with a subtraction 13530 for (const SDNode *U : N->uses()) 13531 if (U->getOpcode() != ISD::ZERO_EXTEND) 13532 return SDValue(); 13533 13534 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13535 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13536 13537 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13538 13539 if (OpSize < Size) { 13540 switch (CC) { 13541 default: break; 13542 case ISD::SETULT: 13543 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13544 case ISD::SETULE: 13545 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13546 case ISD::SETUGT: 13547 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13548 case ISD::SETUGE: 13549 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13550 } 13551 } 13552 13553 return SDValue(); 13554 } 13555 13556 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13557 DAGCombinerInfo &DCI) const { 13558 SelectionDAG &DAG = DCI.DAG; 13559 SDLoc dl(N); 13560 13561 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13562 // If we're tracking CR bits, we need to be careful that we don't have: 13563 // trunc(binary-ops(zext(x), zext(y))) 13564 // or 13565 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13566 // such that we're unnecessarily moving things into GPRs when it would be 13567 // better to keep them in CR bits. 13568 13569 // Note that trunc here can be an actual i1 trunc, or can be the effective 13570 // truncation that comes from a setcc or select_cc. 13571 if (N->getOpcode() == ISD::TRUNCATE && 13572 N->getValueType(0) != MVT::i1) 13573 return SDValue(); 13574 13575 if (N->getOperand(0).getValueType() != MVT::i32 && 13576 N->getOperand(0).getValueType() != MVT::i64) 13577 return SDValue(); 13578 13579 if (N->getOpcode() == ISD::SETCC || 13580 N->getOpcode() == ISD::SELECT_CC) { 13581 // If we're looking at a comparison, then we need to make sure that the 13582 // high bits (all except for the first) don't matter the result. 13583 ISD::CondCode CC = 13584 cast<CondCodeSDNode>(N->getOperand( 13585 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13586 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13587 13588 if (ISD::isSignedIntSetCC(CC)) { 13589 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13590 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13591 return SDValue(); 13592 } else if (ISD::isUnsignedIntSetCC(CC)) { 13593 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13594 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13595 !DAG.MaskedValueIsZero(N->getOperand(1), 13596 APInt::getHighBitsSet(OpBits, OpBits-1))) 13597 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13598 : SDValue()); 13599 } else { 13600 // This is neither a signed nor an unsigned comparison, just make sure 13601 // that the high bits are equal. 13602 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13603 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13604 13605 // We don't really care about what is known about the first bit (if 13606 // anything), so pretend that it is known zero for both to ensure they can 13607 // be compared as constants. 13608 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13609 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13610 13611 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13612 Op1Known.getConstant() != Op2Known.getConstant()) 13613 return SDValue(); 13614 } 13615 } 13616 13617 // We now know that the higher-order bits are irrelevant, we just need to 13618 // make sure that all of the intermediate operations are bit operations, and 13619 // all inputs are extensions. 13620 if (N->getOperand(0).getOpcode() != ISD::AND && 13621 N->getOperand(0).getOpcode() != ISD::OR && 13622 N->getOperand(0).getOpcode() != ISD::XOR && 13623 N->getOperand(0).getOpcode() != ISD::SELECT && 13624 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13625 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13626 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13627 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13628 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13629 return SDValue(); 13630 13631 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13632 N->getOperand(1).getOpcode() != ISD::AND && 13633 N->getOperand(1).getOpcode() != ISD::OR && 13634 N->getOperand(1).getOpcode() != ISD::XOR && 13635 N->getOperand(1).getOpcode() != ISD::SELECT && 13636 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13637 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13638 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13639 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13640 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13641 return SDValue(); 13642 13643 SmallVector<SDValue, 4> Inputs; 13644 SmallVector<SDValue, 8> BinOps, PromOps; 13645 SmallPtrSet<SDNode *, 16> Visited; 13646 13647 for (unsigned i = 0; i < 2; ++i) { 13648 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13649 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13650 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13651 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13652 isa<ConstantSDNode>(N->getOperand(i))) 13653 Inputs.push_back(N->getOperand(i)); 13654 else 13655 BinOps.push_back(N->getOperand(i)); 13656 13657 if (N->getOpcode() == ISD::TRUNCATE) 13658 break; 13659 } 13660 13661 // Visit all inputs, collect all binary operations (and, or, xor and 13662 // select) that are all fed by extensions. 13663 while (!BinOps.empty()) { 13664 SDValue BinOp = BinOps.pop_back_val(); 13665 13666 if (!Visited.insert(BinOp.getNode()).second) 13667 continue; 13668 13669 PromOps.push_back(BinOp); 13670 13671 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13672 // The condition of the select is not promoted. 13673 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13674 continue; 13675 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13676 continue; 13677 13678 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13679 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13680 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13681 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13682 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13683 Inputs.push_back(BinOp.getOperand(i)); 13684 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13685 BinOp.getOperand(i).getOpcode() == ISD::OR || 13686 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13687 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13688 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13689 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13690 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13691 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13692 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13693 BinOps.push_back(BinOp.getOperand(i)); 13694 } else { 13695 // We have an input that is not an extension or another binary 13696 // operation; we'll abort this transformation. 13697 return SDValue(); 13698 } 13699 } 13700 } 13701 13702 // Make sure that this is a self-contained cluster of operations (which 13703 // is not quite the same thing as saying that everything has only one 13704 // use). 13705 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13706 if (isa<ConstantSDNode>(Inputs[i])) 13707 continue; 13708 13709 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13710 if (User != N && !Visited.count(User)) 13711 return SDValue(); 13712 13713 // Make sure that we're not going to promote the non-output-value 13714 // operand(s) or SELECT or SELECT_CC. 13715 // FIXME: Although we could sometimes handle this, and it does occur in 13716 // practice that one of the condition inputs to the select is also one of 13717 // the outputs, we currently can't deal with this. 13718 if (User->getOpcode() == ISD::SELECT) { 13719 if (User->getOperand(0) == Inputs[i]) 13720 return SDValue(); 13721 } else if (User->getOpcode() == ISD::SELECT_CC) { 13722 if (User->getOperand(0) == Inputs[i] || 13723 User->getOperand(1) == Inputs[i]) 13724 return SDValue(); 13725 } 13726 } 13727 } 13728 13729 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13730 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13731 if (User != N && !Visited.count(User)) 13732 return SDValue(); 13733 13734 // Make sure that we're not going to promote the non-output-value 13735 // operand(s) or SELECT or SELECT_CC. 13736 // FIXME: Although we could sometimes handle this, and it does occur in 13737 // practice that one of the condition inputs to the select is also one of 13738 // the outputs, we currently can't deal with this. 13739 if (User->getOpcode() == ISD::SELECT) { 13740 if (User->getOperand(0) == PromOps[i]) 13741 return SDValue(); 13742 } else if (User->getOpcode() == ISD::SELECT_CC) { 13743 if (User->getOperand(0) == PromOps[i] || 13744 User->getOperand(1) == PromOps[i]) 13745 return SDValue(); 13746 } 13747 } 13748 } 13749 13750 // Replace all inputs with the extension operand. 13751 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13752 // Constants may have users outside the cluster of to-be-promoted nodes, 13753 // and so we need to replace those as we do the promotions. 13754 if (isa<ConstantSDNode>(Inputs[i])) 13755 continue; 13756 else 13757 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13758 } 13759 13760 std::list<HandleSDNode> PromOpHandles; 13761 for (auto &PromOp : PromOps) 13762 PromOpHandles.emplace_back(PromOp); 13763 13764 // Replace all operations (these are all the same, but have a different 13765 // (i1) return type). DAG.getNode will validate that the types of 13766 // a binary operator match, so go through the list in reverse so that 13767 // we've likely promoted both operands first. Any intermediate truncations or 13768 // extensions disappear. 13769 while (!PromOpHandles.empty()) { 13770 SDValue PromOp = PromOpHandles.back().getValue(); 13771 PromOpHandles.pop_back(); 13772 13773 if (PromOp.getOpcode() == ISD::TRUNCATE || 13774 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13775 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13776 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13777 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13778 PromOp.getOperand(0).getValueType() != MVT::i1) { 13779 // The operand is not yet ready (see comment below). 13780 PromOpHandles.emplace_front(PromOp); 13781 continue; 13782 } 13783 13784 SDValue RepValue = PromOp.getOperand(0); 13785 if (isa<ConstantSDNode>(RepValue)) 13786 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13787 13788 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13789 continue; 13790 } 13791 13792 unsigned C; 13793 switch (PromOp.getOpcode()) { 13794 default: C = 0; break; 13795 case ISD::SELECT: C = 1; break; 13796 case ISD::SELECT_CC: C = 2; break; 13797 } 13798 13799 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13800 PromOp.getOperand(C).getValueType() != MVT::i1) || 13801 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13802 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13803 // The to-be-promoted operands of this node have not yet been 13804 // promoted (this should be rare because we're going through the 13805 // list backward, but if one of the operands has several users in 13806 // this cluster of to-be-promoted nodes, it is possible). 13807 PromOpHandles.emplace_front(PromOp); 13808 continue; 13809 } 13810 13811 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13812 PromOp.getNode()->op_end()); 13813 13814 // If there are any constant inputs, make sure they're replaced now. 13815 for (unsigned i = 0; i < 2; ++i) 13816 if (isa<ConstantSDNode>(Ops[C+i])) 13817 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13818 13819 DAG.ReplaceAllUsesOfValueWith(PromOp, 13820 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13821 } 13822 13823 // Now we're left with the initial truncation itself. 13824 if (N->getOpcode() == ISD::TRUNCATE) 13825 return N->getOperand(0); 13826 13827 // Otherwise, this is a comparison. The operands to be compared have just 13828 // changed type (to i1), but everything else is the same. 13829 return SDValue(N, 0); 13830 } 13831 13832 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13833 DAGCombinerInfo &DCI) const { 13834 SelectionDAG &DAG = DCI.DAG; 13835 SDLoc dl(N); 13836 13837 // If we're tracking CR bits, we need to be careful that we don't have: 13838 // zext(binary-ops(trunc(x), trunc(y))) 13839 // or 13840 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13841 // such that we're unnecessarily moving things into CR bits that can more 13842 // efficiently stay in GPRs. Note that if we're not certain that the high 13843 // bits are set as required by the final extension, we still may need to do 13844 // some masking to get the proper behavior. 13845 13846 // This same functionality is important on PPC64 when dealing with 13847 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13848 // the return values of functions. Because it is so similar, it is handled 13849 // here as well. 13850 13851 if (N->getValueType(0) != MVT::i32 && 13852 N->getValueType(0) != MVT::i64) 13853 return SDValue(); 13854 13855 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13856 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13857 return SDValue(); 13858 13859 if (N->getOperand(0).getOpcode() != ISD::AND && 13860 N->getOperand(0).getOpcode() != ISD::OR && 13861 N->getOperand(0).getOpcode() != ISD::XOR && 13862 N->getOperand(0).getOpcode() != ISD::SELECT && 13863 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13864 return SDValue(); 13865 13866 SmallVector<SDValue, 4> Inputs; 13867 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13868 SmallPtrSet<SDNode *, 16> Visited; 13869 13870 // Visit all inputs, collect all binary operations (and, or, xor and 13871 // select) that are all fed by truncations. 13872 while (!BinOps.empty()) { 13873 SDValue BinOp = BinOps.pop_back_val(); 13874 13875 if (!Visited.insert(BinOp.getNode()).second) 13876 continue; 13877 13878 PromOps.push_back(BinOp); 13879 13880 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13881 // The condition of the select is not promoted. 13882 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13883 continue; 13884 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13885 continue; 13886 13887 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13888 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13889 Inputs.push_back(BinOp.getOperand(i)); 13890 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13891 BinOp.getOperand(i).getOpcode() == ISD::OR || 13892 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13893 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13894 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13895 BinOps.push_back(BinOp.getOperand(i)); 13896 } else { 13897 // We have an input that is not a truncation or another binary 13898 // operation; we'll abort this transformation. 13899 return SDValue(); 13900 } 13901 } 13902 } 13903 13904 // The operands of a select that must be truncated when the select is 13905 // promoted because the operand is actually part of the to-be-promoted set. 13906 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13907 13908 // Make sure that this is a self-contained cluster of operations (which 13909 // is not quite the same thing as saying that everything has only one 13910 // use). 13911 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13912 if (isa<ConstantSDNode>(Inputs[i])) 13913 continue; 13914 13915 for (SDNode *User : Inputs[i].getNode()->uses()) { 13916 if (User != N && !Visited.count(User)) 13917 return SDValue(); 13918 13919 // If we're going to promote the non-output-value operand(s) or SELECT or 13920 // SELECT_CC, record them for truncation. 13921 if (User->getOpcode() == ISD::SELECT) { 13922 if (User->getOperand(0) == Inputs[i]) 13923 SelectTruncOp[0].insert(std::make_pair(User, 13924 User->getOperand(0).getValueType())); 13925 } else if (User->getOpcode() == ISD::SELECT_CC) { 13926 if (User->getOperand(0) == Inputs[i]) 13927 SelectTruncOp[0].insert(std::make_pair(User, 13928 User->getOperand(0).getValueType())); 13929 if (User->getOperand(1) == Inputs[i]) 13930 SelectTruncOp[1].insert(std::make_pair(User, 13931 User->getOperand(1).getValueType())); 13932 } 13933 } 13934 } 13935 13936 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13937 for (SDNode *User : PromOps[i].getNode()->uses()) { 13938 if (User != N && !Visited.count(User)) 13939 return SDValue(); 13940 13941 // If we're going to promote the non-output-value operand(s) or SELECT or 13942 // SELECT_CC, record them for truncation. 13943 if (User->getOpcode() == ISD::SELECT) { 13944 if (User->getOperand(0) == PromOps[i]) 13945 SelectTruncOp[0].insert(std::make_pair(User, 13946 User->getOperand(0).getValueType())); 13947 } else if (User->getOpcode() == ISD::SELECT_CC) { 13948 if (User->getOperand(0) == PromOps[i]) 13949 SelectTruncOp[0].insert(std::make_pair(User, 13950 User->getOperand(0).getValueType())); 13951 if (User->getOperand(1) == PromOps[i]) 13952 SelectTruncOp[1].insert(std::make_pair(User, 13953 User->getOperand(1).getValueType())); 13954 } 13955 } 13956 } 13957 13958 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13959 bool ReallyNeedsExt = false; 13960 if (N->getOpcode() != ISD::ANY_EXTEND) { 13961 // If all of the inputs are not already sign/zero extended, then 13962 // we'll still need to do that at the end. 13963 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13964 if (isa<ConstantSDNode>(Inputs[i])) 13965 continue; 13966 13967 unsigned OpBits = 13968 Inputs[i].getOperand(0).getValueSizeInBits(); 13969 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13970 13971 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13972 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13973 APInt::getHighBitsSet(OpBits, 13974 OpBits-PromBits))) || 13975 (N->getOpcode() == ISD::SIGN_EXTEND && 13976 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13977 (OpBits-(PromBits-1)))) { 13978 ReallyNeedsExt = true; 13979 break; 13980 } 13981 } 13982 } 13983 13984 // Replace all inputs, either with the truncation operand, or a 13985 // truncation or extension to the final output type. 13986 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13987 // Constant inputs need to be replaced with the to-be-promoted nodes that 13988 // use them because they might have users outside of the cluster of 13989 // promoted nodes. 13990 if (isa<ConstantSDNode>(Inputs[i])) 13991 continue; 13992 13993 SDValue InSrc = Inputs[i].getOperand(0); 13994 if (Inputs[i].getValueType() == N->getValueType(0)) 13995 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13996 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13997 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13998 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13999 else if (N->getOpcode() == ISD::ZERO_EXTEND) 14000 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 14001 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 14002 else 14003 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 14004 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 14005 } 14006 14007 std::list<HandleSDNode> PromOpHandles; 14008 for (auto &PromOp : PromOps) 14009 PromOpHandles.emplace_back(PromOp); 14010 14011 // Replace all operations (these are all the same, but have a different 14012 // (promoted) return type). DAG.getNode will validate that the types of 14013 // a binary operator match, so go through the list in reverse so that 14014 // we've likely promoted both operands first. 14015 while (!PromOpHandles.empty()) { 14016 SDValue PromOp = PromOpHandles.back().getValue(); 14017 PromOpHandles.pop_back(); 14018 14019 unsigned C; 14020 switch (PromOp.getOpcode()) { 14021 default: C = 0; break; 14022 case ISD::SELECT: C = 1; break; 14023 case ISD::SELECT_CC: C = 2; break; 14024 } 14025 14026 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 14027 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 14028 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 14029 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 14030 // The to-be-promoted operands of this node have not yet been 14031 // promoted (this should be rare because we're going through the 14032 // list backward, but if one of the operands has several users in 14033 // this cluster of to-be-promoted nodes, it is possible). 14034 PromOpHandles.emplace_front(PromOp); 14035 continue; 14036 } 14037 14038 // For SELECT and SELECT_CC nodes, we do a similar check for any 14039 // to-be-promoted comparison inputs. 14040 if (PromOp.getOpcode() == ISD::SELECT || 14041 PromOp.getOpcode() == ISD::SELECT_CC) { 14042 if ((SelectTruncOp[0].count(PromOp.getNode()) && 14043 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 14044 (SelectTruncOp[1].count(PromOp.getNode()) && 14045 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 14046 PromOpHandles.emplace_front(PromOp); 14047 continue; 14048 } 14049 } 14050 14051 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 14052 PromOp.getNode()->op_end()); 14053 14054 // If this node has constant inputs, then they'll need to be promoted here. 14055 for (unsigned i = 0; i < 2; ++i) { 14056 if (!isa<ConstantSDNode>(Ops[C+i])) 14057 continue; 14058 if (Ops[C+i].getValueType() == N->getValueType(0)) 14059 continue; 14060 14061 if (N->getOpcode() == ISD::SIGN_EXTEND) 14062 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14063 else if (N->getOpcode() == ISD::ZERO_EXTEND) 14064 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14065 else 14066 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14067 } 14068 14069 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 14070 // truncate them again to the original value type. 14071 if (PromOp.getOpcode() == ISD::SELECT || 14072 PromOp.getOpcode() == ISD::SELECT_CC) { 14073 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 14074 if (SI0 != SelectTruncOp[0].end()) 14075 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 14076 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 14077 if (SI1 != SelectTruncOp[1].end()) 14078 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 14079 } 14080 14081 DAG.ReplaceAllUsesOfValueWith(PromOp, 14082 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 14083 } 14084 14085 // Now we're left with the initial extension itself. 14086 if (!ReallyNeedsExt) 14087 return N->getOperand(0); 14088 14089 // To zero extend, just mask off everything except for the first bit (in the 14090 // i1 case). 14091 if (N->getOpcode() == ISD::ZERO_EXTEND) 14092 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 14093 DAG.getConstant(APInt::getLowBitsSet( 14094 N->getValueSizeInBits(0), PromBits), 14095 dl, N->getValueType(0))); 14096 14097 assert(N->getOpcode() == ISD::SIGN_EXTEND && 14098 "Invalid extension type"); 14099 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 14100 SDValue ShiftCst = 14101 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 14102 return DAG.getNode( 14103 ISD::SRA, dl, N->getValueType(0), 14104 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 14105 ShiftCst); 14106 } 14107 14108 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 14109 DAGCombinerInfo &DCI) const { 14110 assert(N->getOpcode() == ISD::SETCC && 14111 "Should be called with a SETCC node"); 14112 14113 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 14114 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 14115 SDValue LHS = N->getOperand(0); 14116 SDValue RHS = N->getOperand(1); 14117 14118 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 14119 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 14120 LHS.hasOneUse()) 14121 std::swap(LHS, RHS); 14122 14123 // x == 0-y --> x+y == 0 14124 // x != 0-y --> x+y != 0 14125 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 14126 RHS.hasOneUse()) { 14127 SDLoc DL(N); 14128 SelectionDAG &DAG = DCI.DAG; 14129 EVT VT = N->getValueType(0); 14130 EVT OpVT = LHS.getValueType(); 14131 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 14132 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 14133 } 14134 } 14135 14136 return DAGCombineTruncBoolExt(N, DCI); 14137 } 14138 14139 // Is this an extending load from an f32 to an f64? 14140 static bool isFPExtLoad(SDValue Op) { 14141 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 14142 return LD->getExtensionType() == ISD::EXTLOAD && 14143 Op.getValueType() == MVT::f64; 14144 return false; 14145 } 14146 14147 /// Reduces the number of fp-to-int conversion when building a vector. 14148 /// 14149 /// If this vector is built out of floating to integer conversions, 14150 /// transform it to a vector built out of floating point values followed by a 14151 /// single floating to integer conversion of the vector. 14152 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 14153 /// becomes (fptosi (build_vector ($A, $B, ...))) 14154 SDValue PPCTargetLowering:: 14155 combineElementTruncationToVectorTruncation(SDNode *N, 14156 DAGCombinerInfo &DCI) const { 14157 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14158 "Should be called with a BUILD_VECTOR node"); 14159 14160 SelectionDAG &DAG = DCI.DAG; 14161 SDLoc dl(N); 14162 14163 SDValue FirstInput = N->getOperand(0); 14164 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 14165 "The input operand must be an fp-to-int conversion."); 14166 14167 // This combine happens after legalization so the fp_to_[su]i nodes are 14168 // already converted to PPCSISD nodes. 14169 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 14170 if (FirstConversion == PPCISD::FCTIDZ || 14171 FirstConversion == PPCISD::FCTIDUZ || 14172 FirstConversion == PPCISD::FCTIWZ || 14173 FirstConversion == PPCISD::FCTIWUZ) { 14174 bool IsSplat = true; 14175 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 14176 FirstConversion == PPCISD::FCTIWUZ; 14177 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 14178 SmallVector<SDValue, 4> Ops; 14179 EVT TargetVT = N->getValueType(0); 14180 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14181 SDValue NextOp = N->getOperand(i); 14182 if (NextOp.getOpcode() != PPCISD::MFVSR) 14183 return SDValue(); 14184 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 14185 if (NextConversion != FirstConversion) 14186 return SDValue(); 14187 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 14188 // This is not valid if the input was originally double precision. It is 14189 // also not profitable to do unless this is an extending load in which 14190 // case doing this combine will allow us to combine consecutive loads. 14191 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 14192 return SDValue(); 14193 if (N->getOperand(i) != FirstInput) 14194 IsSplat = false; 14195 } 14196 14197 // If this is a splat, we leave it as-is since there will be only a single 14198 // fp-to-int conversion followed by a splat of the integer. This is better 14199 // for 32-bit and smaller ints and neutral for 64-bit ints. 14200 if (IsSplat) 14201 return SDValue(); 14202 14203 // Now that we know we have the right type of node, get its operands 14204 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14205 SDValue In = N->getOperand(i).getOperand(0); 14206 if (Is32Bit) { 14207 // For 32-bit values, we need to add an FP_ROUND node (if we made it 14208 // here, we know that all inputs are extending loads so this is safe). 14209 if (In.isUndef()) 14210 Ops.push_back(DAG.getUNDEF(SrcVT)); 14211 else { 14212 SDValue Trunc = 14213 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0), 14214 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true)); 14215 Ops.push_back(Trunc); 14216 } 14217 } else 14218 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 14219 } 14220 14221 unsigned Opcode; 14222 if (FirstConversion == PPCISD::FCTIDZ || 14223 FirstConversion == PPCISD::FCTIWZ) 14224 Opcode = ISD::FP_TO_SINT; 14225 else 14226 Opcode = ISD::FP_TO_UINT; 14227 14228 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 14229 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 14230 return DAG.getNode(Opcode, dl, TargetVT, BV); 14231 } 14232 return SDValue(); 14233 } 14234 14235 /// Reduce the number of loads when building a vector. 14236 /// 14237 /// Building a vector out of multiple loads can be converted to a load 14238 /// of the vector type if the loads are consecutive. If the loads are 14239 /// consecutive but in descending order, a shuffle is added at the end 14240 /// to reorder the vector. 14241 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 14242 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14243 "Should be called with a BUILD_VECTOR node"); 14244 14245 SDLoc dl(N); 14246 14247 // Return early for non byte-sized type, as they can't be consecutive. 14248 if (!N->getValueType(0).getVectorElementType().isByteSized()) 14249 return SDValue(); 14250 14251 bool InputsAreConsecutiveLoads = true; 14252 bool InputsAreReverseConsecutive = true; 14253 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 14254 SDValue FirstInput = N->getOperand(0); 14255 bool IsRoundOfExtLoad = false; 14256 LoadSDNode *FirstLoad = nullptr; 14257 14258 if (FirstInput.getOpcode() == ISD::FP_ROUND && 14259 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 14260 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0)); 14261 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD; 14262 } 14263 // Not a build vector of (possibly fp_rounded) loads. 14264 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 14265 N->getNumOperands() == 1) 14266 return SDValue(); 14267 14268 if (!IsRoundOfExtLoad) 14269 FirstLoad = cast<LoadSDNode>(FirstInput); 14270 14271 SmallVector<LoadSDNode *, 4> InputLoads; 14272 InputLoads.push_back(FirstLoad); 14273 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14274 // If any inputs are fp_round(extload), they all must be. 14275 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14276 return SDValue(); 14277 14278 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14279 N->getOperand(i); 14280 if (NextInput.getOpcode() != ISD::LOAD) 14281 return SDValue(); 14282 14283 SDValue PreviousInput = 14284 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14285 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput); 14286 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput); 14287 14288 // If any inputs are fp_round(extload), they all must be. 14289 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14290 return SDValue(); 14291 14292 // We only care about regular loads. The PPC-specific load intrinsics 14293 // will not lead to a merge opportunity. 14294 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1)) 14295 InputsAreConsecutiveLoads = false; 14296 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1)) 14297 InputsAreReverseConsecutive = false; 14298 14299 // Exit early if the loads are neither consecutive nor reverse consecutive. 14300 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14301 return SDValue(); 14302 InputLoads.push_back(LD2); 14303 } 14304 14305 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14306 "The loads cannot be both consecutive and reverse consecutive."); 14307 14308 SDValue WideLoad; 14309 SDValue ReturnSDVal; 14310 if (InputsAreConsecutiveLoads) { 14311 assert(FirstLoad && "Input needs to be a LoadSDNode."); 14312 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(), 14313 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 14314 FirstLoad->getAlign()); 14315 ReturnSDVal = WideLoad; 14316 } else if (InputsAreReverseConsecutive) { 14317 LoadSDNode *LastLoad = InputLoads.back(); 14318 assert(LastLoad && "Input needs to be a LoadSDNode."); 14319 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(), 14320 LastLoad->getBasePtr(), LastLoad->getPointerInfo(), 14321 LastLoad->getAlign()); 14322 SmallVector<int, 16> Ops; 14323 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14324 Ops.push_back(i); 14325 14326 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad, 14327 DAG.getUNDEF(N->getValueType(0)), Ops); 14328 } else 14329 return SDValue(); 14330 14331 for (auto *LD : InputLoads) 14332 DAG.makeEquivalentMemoryOrdering(LD, WideLoad); 14333 return ReturnSDVal; 14334 } 14335 14336 // This function adds the required vector_shuffle needed to get 14337 // the elements of the vector extract in the correct position 14338 // as specified by the CorrectElems encoding. 14339 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14340 SDValue Input, uint64_t Elems, 14341 uint64_t CorrectElems) { 14342 SDLoc dl(N); 14343 14344 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14345 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14346 14347 // Knowing the element indices being extracted from the original 14348 // vector and the order in which they're being inserted, just put 14349 // them at element indices required for the instruction. 14350 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14351 if (DAG.getDataLayout().isLittleEndian()) 14352 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14353 else 14354 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14355 CorrectElems = CorrectElems >> 8; 14356 Elems = Elems >> 8; 14357 } 14358 14359 SDValue Shuffle = 14360 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14361 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14362 14363 EVT VT = N->getValueType(0); 14364 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14365 14366 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14367 Input.getValueType().getVectorElementType(), 14368 VT.getVectorNumElements()); 14369 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14370 DAG.getValueType(ExtVT)); 14371 } 14372 14373 // Look for build vector patterns where input operands come from sign 14374 // extended vector_extract elements of specific indices. If the correct indices 14375 // aren't used, add a vector shuffle to fix up the indices and create 14376 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14377 // during instruction selection. 14378 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14379 // This array encodes the indices that the vector sign extend instructions 14380 // extract from when extending from one type to another for both BE and LE. 14381 // The right nibble of each byte corresponds to the LE incides. 14382 // and the left nibble of each byte corresponds to the BE incides. 14383 // For example: 0x3074B8FC byte->word 14384 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14385 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14386 // For example: 0x000070F8 byte->double word 14387 // For LE: the allowed indices are: 0x0,0x8 14388 // For BE: the allowed indices are: 0x7,0xF 14389 uint64_t TargetElems[] = { 14390 0x3074B8FC, // b->w 14391 0x000070F8, // b->d 14392 0x10325476, // h->w 14393 0x00003074, // h->d 14394 0x00001032, // w->d 14395 }; 14396 14397 uint64_t Elems = 0; 14398 int Index; 14399 SDValue Input; 14400 14401 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14402 if (!Op) 14403 return false; 14404 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14405 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14406 return false; 14407 14408 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14409 // of the right width. 14410 SDValue Extract = Op.getOperand(0); 14411 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14412 Extract = Extract.getOperand(0); 14413 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14414 return false; 14415 14416 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14417 if (!ExtOp) 14418 return false; 14419 14420 Index = ExtOp->getZExtValue(); 14421 if (Input && Input != Extract.getOperand(0)) 14422 return false; 14423 14424 if (!Input) 14425 Input = Extract.getOperand(0); 14426 14427 Elems = Elems << 8; 14428 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14429 Elems |= Index; 14430 14431 return true; 14432 }; 14433 14434 // If the build vector operands aren't sign extended vector extracts, 14435 // of the same input vector, then return. 14436 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14437 if (!isSExtOfVecExtract(N->getOperand(i))) { 14438 return SDValue(); 14439 } 14440 } 14441 14442 // If the vector extract indicies are not correct, add the appropriate 14443 // vector_shuffle. 14444 int TgtElemArrayIdx; 14445 int InputSize = Input.getValueType().getScalarSizeInBits(); 14446 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14447 if (InputSize + OutputSize == 40) 14448 TgtElemArrayIdx = 0; 14449 else if (InputSize + OutputSize == 72) 14450 TgtElemArrayIdx = 1; 14451 else if (InputSize + OutputSize == 48) 14452 TgtElemArrayIdx = 2; 14453 else if (InputSize + OutputSize == 80) 14454 TgtElemArrayIdx = 3; 14455 else if (InputSize + OutputSize == 96) 14456 TgtElemArrayIdx = 4; 14457 else 14458 return SDValue(); 14459 14460 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14461 CorrectElems = DAG.getDataLayout().isLittleEndian() 14462 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14463 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14464 if (Elems != CorrectElems) { 14465 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14466 } 14467 14468 // Regular lowering will catch cases where a shuffle is not needed. 14469 return SDValue(); 14470 } 14471 14472 // Look for the pattern of a load from a narrow width to i128, feeding 14473 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14474 // (LXVRZX). This node represents a zero extending load that will be matched 14475 // to the Load VSX Vector Rightmost instructions. 14476 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14477 SDLoc DL(N); 14478 14479 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14480 if (N->getValueType(0) != MVT::v1i128) 14481 return SDValue(); 14482 14483 SDValue Operand = N->getOperand(0); 14484 // Proceed with the transformation if the operand to the BUILD_VECTOR 14485 // is a load instruction. 14486 if (Operand.getOpcode() != ISD::LOAD) 14487 return SDValue(); 14488 14489 auto *LD = cast<LoadSDNode>(Operand); 14490 EVT MemoryType = LD->getMemoryVT(); 14491 14492 // This transformation is only valid if the we are loading either a byte, 14493 // halfword, word, or doubleword. 14494 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14495 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14496 14497 // Ensure that the load from the narrow width is being zero extended to i128. 14498 if (!ValidLDType || 14499 (LD->getExtensionType() != ISD::ZEXTLOAD && 14500 LD->getExtensionType() != ISD::EXTLOAD)) 14501 return SDValue(); 14502 14503 SDValue LoadOps[] = { 14504 LD->getChain(), LD->getBasePtr(), 14505 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14506 14507 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14508 DAG.getVTList(MVT::v1i128, MVT::Other), 14509 LoadOps, MemoryType, LD->getMemOperand()); 14510 } 14511 14512 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14513 DAGCombinerInfo &DCI) const { 14514 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14515 "Should be called with a BUILD_VECTOR node"); 14516 14517 SelectionDAG &DAG = DCI.DAG; 14518 SDLoc dl(N); 14519 14520 if (!Subtarget.hasVSX()) 14521 return SDValue(); 14522 14523 // The target independent DAG combiner will leave a build_vector of 14524 // float-to-int conversions intact. We can generate MUCH better code for 14525 // a float-to-int conversion of a vector of floats. 14526 SDValue FirstInput = N->getOperand(0); 14527 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14528 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14529 if (Reduced) 14530 return Reduced; 14531 } 14532 14533 // If we're building a vector out of consecutive loads, just load that 14534 // vector type. 14535 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14536 if (Reduced) 14537 return Reduced; 14538 14539 // If we're building a vector out of extended elements from another vector 14540 // we have P9 vector integer extend instructions. The code assumes legal 14541 // input types (i.e. it can't handle things like v4i16) so do not run before 14542 // legalization. 14543 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14544 Reduced = combineBVOfVecSExt(N, DAG); 14545 if (Reduced) 14546 return Reduced; 14547 } 14548 14549 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14550 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14551 // is a load from <valid narrow width> to i128. 14552 if (Subtarget.isISA3_1()) { 14553 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14554 if (BVOfZLoad) 14555 return BVOfZLoad; 14556 } 14557 14558 if (N->getValueType(0) != MVT::v2f64) 14559 return SDValue(); 14560 14561 // Looking for: 14562 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14563 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14564 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14565 return SDValue(); 14566 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14567 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14568 return SDValue(); 14569 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14570 return SDValue(); 14571 14572 SDValue Ext1 = FirstInput.getOperand(0); 14573 SDValue Ext2 = N->getOperand(1).getOperand(0); 14574 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14575 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14576 return SDValue(); 14577 14578 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14579 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14580 if (!Ext1Op || !Ext2Op) 14581 return SDValue(); 14582 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14583 Ext1.getOperand(0) != Ext2.getOperand(0)) 14584 return SDValue(); 14585 14586 int FirstElem = Ext1Op->getZExtValue(); 14587 int SecondElem = Ext2Op->getZExtValue(); 14588 int SubvecIdx; 14589 if (FirstElem == 0 && SecondElem == 1) 14590 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14591 else if (FirstElem == 2 && SecondElem == 3) 14592 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14593 else 14594 return SDValue(); 14595 14596 SDValue SrcVec = Ext1.getOperand(0); 14597 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14598 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14599 return DAG.getNode(NodeType, dl, MVT::v2f64, 14600 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14601 } 14602 14603 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14604 DAGCombinerInfo &DCI) const { 14605 assert((N->getOpcode() == ISD::SINT_TO_FP || 14606 N->getOpcode() == ISD::UINT_TO_FP) && 14607 "Need an int -> FP conversion node here"); 14608 14609 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14610 return SDValue(); 14611 14612 SelectionDAG &DAG = DCI.DAG; 14613 SDLoc dl(N); 14614 SDValue Op(N, 0); 14615 14616 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14617 // from the hardware. 14618 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14619 return SDValue(); 14620 if (!Op.getOperand(0).getValueType().isSimple()) 14621 return SDValue(); 14622 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14623 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14624 return SDValue(); 14625 14626 SDValue FirstOperand(Op.getOperand(0)); 14627 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14628 (FirstOperand.getValueType() == MVT::i8 || 14629 FirstOperand.getValueType() == MVT::i16); 14630 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14631 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14632 bool DstDouble = Op.getValueType() == MVT::f64; 14633 unsigned ConvOp = Signed ? 14634 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14635 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14636 SDValue WidthConst = 14637 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14638 dl, false); 14639 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14640 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14641 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14642 DAG.getVTList(MVT::f64, MVT::Other), 14643 Ops, MVT::i8, LDN->getMemOperand()); 14644 14645 // For signed conversion, we need to sign-extend the value in the VSR 14646 if (Signed) { 14647 SDValue ExtOps[] = { Ld, WidthConst }; 14648 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14649 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14650 } else 14651 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14652 } 14653 14654 14655 // For i32 intermediate values, unfortunately, the conversion functions 14656 // leave the upper 32 bits of the value are undefined. Within the set of 14657 // scalar instructions, we have no method for zero- or sign-extending the 14658 // value. Thus, we cannot handle i32 intermediate values here. 14659 if (Op.getOperand(0).getValueType() == MVT::i32) 14660 return SDValue(); 14661 14662 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14663 "UINT_TO_FP is supported only with FPCVT"); 14664 14665 // If we have FCFIDS, then use it when converting to single-precision. 14666 // Otherwise, convert to double-precision and then round. 14667 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14668 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14669 : PPCISD::FCFIDS) 14670 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14671 : PPCISD::FCFID); 14672 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14673 ? MVT::f32 14674 : MVT::f64; 14675 14676 // If we're converting from a float, to an int, and back to a float again, 14677 // then we don't need the store/load pair at all. 14678 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14679 Subtarget.hasFPCVT()) || 14680 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14681 SDValue Src = Op.getOperand(0).getOperand(0); 14682 if (Src.getValueType() == MVT::f32) { 14683 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14684 DCI.AddToWorklist(Src.getNode()); 14685 } else if (Src.getValueType() != MVT::f64) { 14686 // Make sure that we don't pick up a ppc_fp128 source value. 14687 return SDValue(); 14688 } 14689 14690 unsigned FCTOp = 14691 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14692 PPCISD::FCTIDUZ; 14693 14694 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14695 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14696 14697 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14698 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 14699 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 14700 DCI.AddToWorklist(FP.getNode()); 14701 } 14702 14703 return FP; 14704 } 14705 14706 return SDValue(); 14707 } 14708 14709 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14710 // builtins) into loads with swaps. 14711 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14712 DAGCombinerInfo &DCI) const { 14713 // Delay VSX load for LE combine until after LegalizeOps to prioritize other 14714 // load combines. 14715 if (DCI.isBeforeLegalizeOps()) 14716 return SDValue(); 14717 14718 SelectionDAG &DAG = DCI.DAG; 14719 SDLoc dl(N); 14720 SDValue Chain; 14721 SDValue Base; 14722 MachineMemOperand *MMO; 14723 14724 switch (N->getOpcode()) { 14725 default: 14726 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14727 case ISD::LOAD: { 14728 LoadSDNode *LD = cast<LoadSDNode>(N); 14729 Chain = LD->getChain(); 14730 Base = LD->getBasePtr(); 14731 MMO = LD->getMemOperand(); 14732 // If the MMO suggests this isn't a load of a full vector, leave 14733 // things alone. For a built-in, we have to make the change for 14734 // correctness, so if there is a size problem that will be a bug. 14735 if (MMO->getSize() < 16) 14736 return SDValue(); 14737 break; 14738 } 14739 case ISD::INTRINSIC_W_CHAIN: { 14740 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14741 Chain = Intrin->getChain(); 14742 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14743 // us what we want. Get operand 2 instead. 14744 Base = Intrin->getOperand(2); 14745 MMO = Intrin->getMemOperand(); 14746 break; 14747 } 14748 } 14749 14750 MVT VecTy = N->getValueType(0).getSimpleVT(); 14751 14752 SDValue LoadOps[] = { Chain, Base }; 14753 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14754 DAG.getVTList(MVT::v2f64, MVT::Other), 14755 LoadOps, MVT::v2f64, MMO); 14756 14757 DCI.AddToWorklist(Load.getNode()); 14758 Chain = Load.getValue(1); 14759 SDValue Swap = DAG.getNode( 14760 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14761 DCI.AddToWorklist(Swap.getNode()); 14762 14763 // Add a bitcast if the resulting load type doesn't match v2f64. 14764 if (VecTy != MVT::v2f64) { 14765 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14766 DCI.AddToWorklist(N.getNode()); 14767 // Package {bitcast value, swap's chain} to match Load's shape. 14768 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14769 N, Swap.getValue(1)); 14770 } 14771 14772 return Swap; 14773 } 14774 14775 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14776 // builtins) into stores with swaps. 14777 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14778 DAGCombinerInfo &DCI) const { 14779 // Delay VSX store for LE combine until after LegalizeOps to prioritize other 14780 // store combines. 14781 if (DCI.isBeforeLegalizeOps()) 14782 return SDValue(); 14783 14784 SelectionDAG &DAG = DCI.DAG; 14785 SDLoc dl(N); 14786 SDValue Chain; 14787 SDValue Base; 14788 unsigned SrcOpnd; 14789 MachineMemOperand *MMO; 14790 14791 switch (N->getOpcode()) { 14792 default: 14793 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14794 case ISD::STORE: { 14795 StoreSDNode *ST = cast<StoreSDNode>(N); 14796 Chain = ST->getChain(); 14797 Base = ST->getBasePtr(); 14798 MMO = ST->getMemOperand(); 14799 SrcOpnd = 1; 14800 // If the MMO suggests this isn't a store of a full vector, leave 14801 // things alone. For a built-in, we have to make the change for 14802 // correctness, so if there is a size problem that will be a bug. 14803 if (MMO->getSize() < 16) 14804 return SDValue(); 14805 break; 14806 } 14807 case ISD::INTRINSIC_VOID: { 14808 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14809 Chain = Intrin->getChain(); 14810 // Intrin->getBasePtr() oddly does not get what we want. 14811 Base = Intrin->getOperand(3); 14812 MMO = Intrin->getMemOperand(); 14813 SrcOpnd = 2; 14814 break; 14815 } 14816 } 14817 14818 SDValue Src = N->getOperand(SrcOpnd); 14819 MVT VecTy = Src.getValueType().getSimpleVT(); 14820 14821 // All stores are done as v2f64 and possible bit cast. 14822 if (VecTy != MVT::v2f64) { 14823 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14824 DCI.AddToWorklist(Src.getNode()); 14825 } 14826 14827 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14828 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14829 DCI.AddToWorklist(Swap.getNode()); 14830 Chain = Swap.getValue(1); 14831 SDValue StoreOps[] = { Chain, Swap, Base }; 14832 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14833 DAG.getVTList(MVT::Other), 14834 StoreOps, VecTy, MMO); 14835 DCI.AddToWorklist(Store.getNode()); 14836 return Store; 14837 } 14838 14839 // Handle DAG combine for STORE (FP_TO_INT F). 14840 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14841 DAGCombinerInfo &DCI) const { 14842 14843 SelectionDAG &DAG = DCI.DAG; 14844 SDLoc dl(N); 14845 unsigned Opcode = N->getOperand(1).getOpcode(); 14846 14847 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14848 && "Not a FP_TO_INT Instruction!"); 14849 14850 SDValue Val = N->getOperand(1).getOperand(0); 14851 EVT Op1VT = N->getOperand(1).getValueType(); 14852 EVT ResVT = Val.getValueType(); 14853 14854 if (!isTypeLegal(ResVT)) 14855 return SDValue(); 14856 14857 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14858 bool ValidTypeForStoreFltAsInt = 14859 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14860 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14861 14862 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14863 return SDValue(); 14864 14865 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14866 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14867 return SDValue(); 14868 14869 // Extend f32 values to f64 14870 if (ResVT.getScalarSizeInBits() == 32) { 14871 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14872 DCI.AddToWorklist(Val.getNode()); 14873 } 14874 14875 // Set signed or unsigned conversion opcode. 14876 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14877 PPCISD::FP_TO_SINT_IN_VSR : 14878 PPCISD::FP_TO_UINT_IN_VSR; 14879 14880 Val = DAG.getNode(ConvOpcode, 14881 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14882 DCI.AddToWorklist(Val.getNode()); 14883 14884 // Set number of bytes being converted. 14885 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14886 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14887 DAG.getIntPtrConstant(ByteSize, dl, false), 14888 DAG.getValueType(Op1VT) }; 14889 14890 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14891 DAG.getVTList(MVT::Other), Ops, 14892 cast<StoreSDNode>(N)->getMemoryVT(), 14893 cast<StoreSDNode>(N)->getMemOperand()); 14894 14895 DCI.AddToWorklist(Val.getNode()); 14896 return Val; 14897 } 14898 14899 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14900 // Check that the source of the element keeps flipping 14901 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14902 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14903 for (int i = 1, e = Mask.size(); i < e; i++) { 14904 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14905 return false; 14906 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14907 return false; 14908 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14909 } 14910 return true; 14911 } 14912 14913 static bool isSplatBV(SDValue Op) { 14914 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14915 return false; 14916 SDValue FirstOp; 14917 14918 // Find first non-undef input. 14919 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14920 FirstOp = Op.getOperand(i); 14921 if (!FirstOp.isUndef()) 14922 break; 14923 } 14924 14925 // All inputs are undef or the same as the first non-undef input. 14926 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14927 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14928 return false; 14929 return true; 14930 } 14931 14932 static SDValue isScalarToVec(SDValue Op) { 14933 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14934 return Op; 14935 if (Op.getOpcode() != ISD::BITCAST) 14936 return SDValue(); 14937 Op = Op.getOperand(0); 14938 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14939 return Op; 14940 return SDValue(); 14941 } 14942 14943 // Fix up the shuffle mask to account for the fact that the result of 14944 // scalar_to_vector is not in lane zero. This just takes all values in 14945 // the ranges specified by the min/max indices and adds the number of 14946 // elements required to ensure each element comes from the respective 14947 // position in the valid lane. 14948 // On little endian, that's just the corresponding element in the other 14949 // half of the vector. On big endian, it is in the same half but right 14950 // justified rather than left justified in that half. 14951 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14952 int LHSMaxIdx, int RHSMinIdx, 14953 int RHSMaxIdx, int HalfVec, 14954 unsigned ValidLaneWidth, 14955 const PPCSubtarget &Subtarget) { 14956 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14957 int Idx = ShuffV[i]; 14958 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14959 ShuffV[i] += 14960 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14961 } 14962 } 14963 14964 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14965 // the original is: 14966 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14967 // In such a case, just change the shuffle mask to extract the element 14968 // from the permuted index. 14969 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14970 const PPCSubtarget &Subtarget) { 14971 SDLoc dl(OrigSToV); 14972 EVT VT = OrigSToV.getValueType(); 14973 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14974 "Expecting a SCALAR_TO_VECTOR here"); 14975 SDValue Input = OrigSToV.getOperand(0); 14976 14977 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14978 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14979 SDValue OrigVector = Input.getOperand(0); 14980 14981 // Can't handle non-const element indices or different vector types 14982 // for the input to the extract and the output of the scalar_to_vector. 14983 if (Idx && VT == OrigVector.getValueType()) { 14984 unsigned NumElts = VT.getVectorNumElements(); 14985 assert( 14986 NumElts > 1 && 14987 "Cannot produce a permuted scalar_to_vector for one element vector"); 14988 SmallVector<int, 16> NewMask(NumElts, -1); 14989 unsigned ResultInElt = NumElts / 2; 14990 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14991 NewMask[ResultInElt] = Idx->getZExtValue(); 14992 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14993 } 14994 } 14995 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14996 OrigSToV.getOperand(0)); 14997 } 14998 14999 // On little endian subtargets, combine shuffles such as: 15000 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 15001 // into: 15002 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 15003 // because the latter can be matched to a single instruction merge. 15004 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 15005 // to put the value into element zero. Adjust the shuffle mask so that the 15006 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 15007 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 15008 // nodes with elements smaller than doubleword because all the ways 15009 // of getting scalar data into a vector register put the value in the 15010 // rightmost element of the left half of the vector. 15011 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 15012 SelectionDAG &DAG) const { 15013 SDValue LHS = SVN->getOperand(0); 15014 SDValue RHS = SVN->getOperand(1); 15015 auto Mask = SVN->getMask(); 15016 int NumElts = LHS.getValueType().getVectorNumElements(); 15017 SDValue Res(SVN, 0); 15018 SDLoc dl(SVN); 15019 bool IsLittleEndian = Subtarget.isLittleEndian(); 15020 15021 // On big endian targets this is only useful for subtargets with direct moves. 15022 // On little endian targets it would be useful for all subtargets with VSX. 15023 // However adding special handling for LE subtargets without direct moves 15024 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 15025 // which includes direct moves. 15026 if (!Subtarget.hasDirectMove()) 15027 return Res; 15028 15029 // If this is not a shuffle of a shuffle and the first element comes from 15030 // the second vector, canonicalize to the commuted form. This will make it 15031 // more likely to match one of the single instruction patterns. 15032 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 15033 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 15034 std::swap(LHS, RHS); 15035 Res = DAG.getCommutedVectorShuffle(*SVN); 15036 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 15037 } 15038 15039 // Adjust the shuffle mask if either input vector comes from a 15040 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 15041 // form (to prevent the need for a swap). 15042 SmallVector<int, 16> ShuffV(Mask); 15043 SDValue SToVLHS = isScalarToVec(LHS); 15044 SDValue SToVRHS = isScalarToVec(RHS); 15045 if (SToVLHS || SToVRHS) { 15046 // FIXME: If both LHS and RHS are SCALAR_TO_VECTOR, but are not the 15047 // same type and have differing element sizes, then do not perform 15048 // the following transformation. The current transformation for 15049 // SCALAR_TO_VECTOR assumes that both input vectors have the same 15050 // element size. This will be updated in the future to account for 15051 // differing sizes of the LHS and RHS. 15052 if (SToVLHS && SToVRHS && 15053 (SToVLHS.getValueType().getScalarSizeInBits() != 15054 SToVRHS.getValueType().getScalarSizeInBits())) 15055 return Res; 15056 15057 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 15058 : SToVRHS.getValueType().getVectorNumElements(); 15059 int NumEltsOut = ShuffV.size(); 15060 // The width of the "valid lane" (i.e. the lane that contains the value that 15061 // is vectorized) needs to be expressed in terms of the number of elements 15062 // of the shuffle. It is thereby the ratio of the values before and after 15063 // any bitcast. 15064 unsigned ValidLaneWidth = 15065 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 15066 LHS.getValueType().getScalarSizeInBits() 15067 : SToVRHS.getValueType().getScalarSizeInBits() / 15068 RHS.getValueType().getScalarSizeInBits(); 15069 15070 // Initially assume that neither input is permuted. These will be adjusted 15071 // accordingly if either input is. 15072 int LHSMaxIdx = -1; 15073 int RHSMinIdx = -1; 15074 int RHSMaxIdx = -1; 15075 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 15076 15077 // Get the permuted scalar to vector nodes for the source(s) that come from 15078 // ISD::SCALAR_TO_VECTOR. 15079 // On big endian systems, this only makes sense for element sizes smaller 15080 // than 64 bits since for 64-bit elements, all instructions already put 15081 // the value into element zero. Since scalar size of LHS and RHS may differ 15082 // after isScalarToVec, this should be checked using their own sizes. 15083 if (SToVLHS) { 15084 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 15085 return Res; 15086 // Set up the values for the shuffle vector fixup. 15087 LHSMaxIdx = NumEltsOut / NumEltsIn; 15088 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 15089 if (SToVLHS.getValueType() != LHS.getValueType()) 15090 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 15091 LHS = SToVLHS; 15092 } 15093 if (SToVRHS) { 15094 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 15095 return Res; 15096 RHSMinIdx = NumEltsOut; 15097 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 15098 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 15099 if (SToVRHS.getValueType() != RHS.getValueType()) 15100 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 15101 RHS = SToVRHS; 15102 } 15103 15104 // Fix up the shuffle mask to reflect where the desired element actually is. 15105 // The minimum and maximum indices that correspond to element zero for both 15106 // the LHS and RHS are computed and will control which shuffle mask entries 15107 // are to be changed. For example, if the RHS is permuted, any shuffle mask 15108 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 15109 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 15110 HalfVec, ValidLaneWidth, Subtarget); 15111 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 15112 15113 // We may have simplified away the shuffle. We won't be able to do anything 15114 // further with it here. 15115 if (!isa<ShuffleVectorSDNode>(Res)) 15116 return Res; 15117 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 15118 } 15119 15120 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 15121 // The common case after we commuted the shuffle is that the RHS is a splat 15122 // and we have elements coming in from the splat at indices that are not 15123 // conducive to using a merge. 15124 // Example: 15125 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 15126 if (!isSplatBV(TheSplat)) 15127 return Res; 15128 15129 // We are looking for a mask such that all even elements are from 15130 // one vector and all odd elements from the other. 15131 if (!isAlternatingShuffMask(Mask, NumElts)) 15132 return Res; 15133 15134 // Adjust the mask so we are pulling in the same index from the splat 15135 // as the index from the interesting vector in consecutive elements. 15136 if (IsLittleEndian) { 15137 // Example (even elements from first vector): 15138 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 15139 if (Mask[0] < NumElts) 15140 for (int i = 1, e = Mask.size(); i < e; i += 2) { 15141 if (ShuffV[i] < 0) 15142 continue; 15143 ShuffV[i] = (ShuffV[i - 1] + NumElts); 15144 } 15145 // Example (odd elements from first vector): 15146 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 15147 else 15148 for (int i = 0, e = Mask.size(); i < e; i += 2) { 15149 if (ShuffV[i] < 0) 15150 continue; 15151 ShuffV[i] = (ShuffV[i + 1] + NumElts); 15152 } 15153 } else { 15154 // Example (even elements from first vector): 15155 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 15156 if (Mask[0] < NumElts) 15157 for (int i = 0, e = Mask.size(); i < e; i += 2) { 15158 if (ShuffV[i] < 0) 15159 continue; 15160 ShuffV[i] = ShuffV[i + 1] - NumElts; 15161 } 15162 // Example (odd elements from first vector): 15163 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 15164 else 15165 for (int i = 1, e = Mask.size(); i < e; i += 2) { 15166 if (ShuffV[i] < 0) 15167 continue; 15168 ShuffV[i] = ShuffV[i - 1] - NumElts; 15169 } 15170 } 15171 15172 // If the RHS has undefs, we need to remove them since we may have created 15173 // a shuffle that adds those instead of the splat value. 15174 SDValue SplatVal = 15175 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 15176 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 15177 15178 if (IsLittleEndian) 15179 RHS = TheSplat; 15180 else 15181 LHS = TheSplat; 15182 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 15183 } 15184 15185 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 15186 LSBaseSDNode *LSBase, 15187 DAGCombinerInfo &DCI) const { 15188 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 15189 "Not a reverse memop pattern!"); 15190 15191 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 15192 auto Mask = SVN->getMask(); 15193 int i = 0; 15194 auto I = Mask.rbegin(); 15195 auto E = Mask.rend(); 15196 15197 for (; I != E; ++I) { 15198 if (*I != i) 15199 return false; 15200 i++; 15201 } 15202 return true; 15203 }; 15204 15205 SelectionDAG &DAG = DCI.DAG; 15206 EVT VT = SVN->getValueType(0); 15207 15208 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 15209 return SDValue(); 15210 15211 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 15212 // See comment in PPCVSXSwapRemoval.cpp. 15213 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 15214 if (!Subtarget.hasP9Vector()) 15215 return SDValue(); 15216 15217 if(!IsElementReverse(SVN)) 15218 return SDValue(); 15219 15220 if (LSBase->getOpcode() == ISD::LOAD) { 15221 // If the load return value 0 has more than one user except the 15222 // shufflevector instruction, it is not profitable to replace the 15223 // shufflevector with a reverse load. 15224 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 15225 UI != UE; ++UI) 15226 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 15227 return SDValue(); 15228 15229 SDLoc dl(LSBase); 15230 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 15231 return DAG.getMemIntrinsicNode( 15232 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 15233 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15234 } 15235 15236 if (LSBase->getOpcode() == ISD::STORE) { 15237 // If there are other uses of the shuffle, the swap cannot be avoided. 15238 // Forcing the use of an X-Form (since swapped stores only have 15239 // X-Forms) without removing the swap is unprofitable. 15240 if (!SVN->hasOneUse()) 15241 return SDValue(); 15242 15243 SDLoc dl(LSBase); 15244 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 15245 LSBase->getBasePtr()}; 15246 return DAG.getMemIntrinsicNode( 15247 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 15248 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15249 } 15250 15251 llvm_unreachable("Expected a load or store node here"); 15252 } 15253 15254 static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) { 15255 unsigned IntrinsicID = 15256 cast<ConstantSDNode>(Intrin.getOperand(1))->getZExtValue(); 15257 if (IntrinsicID == Intrinsic::ppc_stdcx) 15258 StoreWidth = 8; 15259 else if (IntrinsicID == Intrinsic::ppc_stwcx) 15260 StoreWidth = 4; 15261 else if (IntrinsicID == Intrinsic::ppc_sthcx) 15262 StoreWidth = 2; 15263 else if (IntrinsicID == Intrinsic::ppc_stbcx) 15264 StoreWidth = 1; 15265 else 15266 return false; 15267 return true; 15268 } 15269 15270 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 15271 DAGCombinerInfo &DCI) const { 15272 SelectionDAG &DAG = DCI.DAG; 15273 SDLoc dl(N); 15274 switch (N->getOpcode()) { 15275 default: break; 15276 case ISD::ADD: 15277 return combineADD(N, DCI); 15278 case ISD::SHL: 15279 return combineSHL(N, DCI); 15280 case ISD::SRA: 15281 return combineSRA(N, DCI); 15282 case ISD::SRL: 15283 return combineSRL(N, DCI); 15284 case ISD::MUL: 15285 return combineMUL(N, DCI); 15286 case ISD::FMA: 15287 case PPCISD::FNMSUB: 15288 return combineFMALike(N, DCI); 15289 case PPCISD::SHL: 15290 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 15291 return N->getOperand(0); 15292 break; 15293 case PPCISD::SRL: 15294 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 15295 return N->getOperand(0); 15296 break; 15297 case PPCISD::SRA: 15298 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 15299 if (C->isZero() || // 0 >>s V -> 0. 15300 C->isAllOnes()) // -1 >>s V -> -1. 15301 return N->getOperand(0); 15302 } 15303 break; 15304 case ISD::SIGN_EXTEND: 15305 case ISD::ZERO_EXTEND: 15306 case ISD::ANY_EXTEND: 15307 return DAGCombineExtBoolTrunc(N, DCI); 15308 case ISD::TRUNCATE: 15309 return combineTRUNCATE(N, DCI); 15310 case ISD::SETCC: 15311 if (SDValue CSCC = combineSetCC(N, DCI)) 15312 return CSCC; 15313 [[fallthrough]]; 15314 case ISD::SELECT_CC: 15315 return DAGCombineTruncBoolExt(N, DCI); 15316 case ISD::SINT_TO_FP: 15317 case ISD::UINT_TO_FP: 15318 return combineFPToIntToFP(N, DCI); 15319 case ISD::VECTOR_SHUFFLE: 15320 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15321 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15322 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15323 } 15324 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15325 case ISD::STORE: { 15326 15327 EVT Op1VT = N->getOperand(1).getValueType(); 15328 unsigned Opcode = N->getOperand(1).getOpcode(); 15329 15330 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15331 SDValue Val= combineStoreFPToInt(N, DCI); 15332 if (Val) 15333 return Val; 15334 } 15335 15336 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15337 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15338 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15339 if (Val) 15340 return Val; 15341 } 15342 15343 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15344 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15345 N->getOperand(1).getNode()->hasOneUse() && 15346 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15347 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15348 15349 // STBRX can only handle simple types and it makes no sense to store less 15350 // two bytes in byte-reversed order. 15351 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15352 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15353 break; 15354 15355 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15356 // Do an any-extend to 32-bits if this is a half-word input. 15357 if (BSwapOp.getValueType() == MVT::i16) 15358 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15359 15360 // If the type of BSWAP operand is wider than stored memory width 15361 // it need to be shifted to the right side before STBRX. 15362 if (Op1VT.bitsGT(mVT)) { 15363 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15364 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15365 DAG.getConstant(Shift, dl, MVT::i32)); 15366 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15367 if (Op1VT == MVT::i64) 15368 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15369 } 15370 15371 SDValue Ops[] = { 15372 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15373 }; 15374 return 15375 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15376 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15377 cast<StoreSDNode>(N)->getMemOperand()); 15378 } 15379 15380 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15381 // So it can increase the chance of CSE constant construction. 15382 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15383 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15384 // Need to sign-extended to 64-bits to handle negative values. 15385 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15386 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15387 MemVT.getSizeInBits()); 15388 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15389 15390 // DAG.getTruncStore() can't be used here because it doesn't accept 15391 // the general (base + offset) addressing mode. 15392 // So we use UpdateNodeOperands and setTruncatingStore instead. 15393 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15394 N->getOperand(3)); 15395 cast<StoreSDNode>(N)->setTruncatingStore(true); 15396 return SDValue(N, 0); 15397 } 15398 15399 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15400 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15401 if (Op1VT.isSimple()) { 15402 MVT StoreVT = Op1VT.getSimpleVT(); 15403 if (Subtarget.needsSwapsForVSXMemOps() && 15404 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15405 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15406 return expandVSXStoreForLE(N, DCI); 15407 } 15408 break; 15409 } 15410 case ISD::LOAD: { 15411 LoadSDNode *LD = cast<LoadSDNode>(N); 15412 EVT VT = LD->getValueType(0); 15413 15414 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15415 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15416 if (VT.isSimple()) { 15417 MVT LoadVT = VT.getSimpleVT(); 15418 if (Subtarget.needsSwapsForVSXMemOps() && 15419 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15420 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15421 return expandVSXLoadForLE(N, DCI); 15422 } 15423 15424 // We sometimes end up with a 64-bit integer load, from which we extract 15425 // two single-precision floating-point numbers. This happens with 15426 // std::complex<float>, and other similar structures, because of the way we 15427 // canonicalize structure copies. However, if we lack direct moves, 15428 // then the final bitcasts from the extracted integer values to the 15429 // floating-point numbers turn into store/load pairs. Even with direct moves, 15430 // just loading the two floating-point numbers is likely better. 15431 auto ReplaceTwoFloatLoad = [&]() { 15432 if (VT != MVT::i64) 15433 return false; 15434 15435 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15436 LD->isVolatile()) 15437 return false; 15438 15439 // We're looking for a sequence like this: 15440 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15441 // t16: i64 = srl t13, Constant:i32<32> 15442 // t17: i32 = truncate t16 15443 // t18: f32 = bitcast t17 15444 // t19: i32 = truncate t13 15445 // t20: f32 = bitcast t19 15446 15447 if (!LD->hasNUsesOfValue(2, 0)) 15448 return false; 15449 15450 auto UI = LD->use_begin(); 15451 while (UI.getUse().getResNo() != 0) ++UI; 15452 SDNode *Trunc = *UI++; 15453 while (UI.getUse().getResNo() != 0) ++UI; 15454 SDNode *RightShift = *UI; 15455 if (Trunc->getOpcode() != ISD::TRUNCATE) 15456 std::swap(Trunc, RightShift); 15457 15458 if (Trunc->getOpcode() != ISD::TRUNCATE || 15459 Trunc->getValueType(0) != MVT::i32 || 15460 !Trunc->hasOneUse()) 15461 return false; 15462 if (RightShift->getOpcode() != ISD::SRL || 15463 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15464 RightShift->getConstantOperandVal(1) != 32 || 15465 !RightShift->hasOneUse()) 15466 return false; 15467 15468 SDNode *Trunc2 = *RightShift->use_begin(); 15469 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15470 Trunc2->getValueType(0) != MVT::i32 || 15471 !Trunc2->hasOneUse()) 15472 return false; 15473 15474 SDNode *Bitcast = *Trunc->use_begin(); 15475 SDNode *Bitcast2 = *Trunc2->use_begin(); 15476 15477 if (Bitcast->getOpcode() != ISD::BITCAST || 15478 Bitcast->getValueType(0) != MVT::f32) 15479 return false; 15480 if (Bitcast2->getOpcode() != ISD::BITCAST || 15481 Bitcast2->getValueType(0) != MVT::f32) 15482 return false; 15483 15484 if (Subtarget.isLittleEndian()) 15485 std::swap(Bitcast, Bitcast2); 15486 15487 // Bitcast has the second float (in memory-layout order) and Bitcast2 15488 // has the first one. 15489 15490 SDValue BasePtr = LD->getBasePtr(); 15491 if (LD->isIndexed()) { 15492 assert(LD->getAddressingMode() == ISD::PRE_INC && 15493 "Non-pre-inc AM on PPC?"); 15494 BasePtr = 15495 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15496 LD->getOffset()); 15497 } 15498 15499 auto MMOFlags = 15500 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15501 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15502 LD->getPointerInfo(), LD->getAlign(), 15503 MMOFlags, LD->getAAInfo()); 15504 SDValue AddPtr = 15505 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15506 BasePtr, DAG.getIntPtrConstant(4, dl)); 15507 SDValue FloatLoad2 = DAG.getLoad( 15508 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15509 LD->getPointerInfo().getWithOffset(4), 15510 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo()); 15511 15512 if (LD->isIndexed()) { 15513 // Note that DAGCombine should re-form any pre-increment load(s) from 15514 // what is produced here if that makes sense. 15515 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15516 } 15517 15518 DCI.CombineTo(Bitcast2, FloatLoad); 15519 DCI.CombineTo(Bitcast, FloatLoad2); 15520 15521 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15522 SDValue(FloatLoad2.getNode(), 1)); 15523 return true; 15524 }; 15525 15526 if (ReplaceTwoFloatLoad()) 15527 return SDValue(N, 0); 15528 15529 EVT MemVT = LD->getMemoryVT(); 15530 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15531 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15532 if (LD->isUnindexed() && VT.isVector() && 15533 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15534 // P8 and later hardware should just use LOAD. 15535 !Subtarget.hasP8Vector() && 15536 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15537 VT == MVT::v4f32))) && 15538 LD->getAlign() < ABIAlignment) { 15539 // This is a type-legal unaligned Altivec load. 15540 SDValue Chain = LD->getChain(); 15541 SDValue Ptr = LD->getBasePtr(); 15542 bool isLittleEndian = Subtarget.isLittleEndian(); 15543 15544 // This implements the loading of unaligned vectors as described in 15545 // the venerable Apple Velocity Engine overview. Specifically: 15546 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15547 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15548 // 15549 // The general idea is to expand a sequence of one or more unaligned 15550 // loads into an alignment-based permutation-control instruction (lvsl 15551 // or lvsr), a series of regular vector loads (which always truncate 15552 // their input address to an aligned address), and a series of 15553 // permutations. The results of these permutations are the requested 15554 // loaded values. The trick is that the last "extra" load is not taken 15555 // from the address you might suspect (sizeof(vector) bytes after the 15556 // last requested load), but rather sizeof(vector) - 1 bytes after the 15557 // last requested vector. The point of this is to avoid a page fault if 15558 // the base address happened to be aligned. This works because if the 15559 // base address is aligned, then adding less than a full vector length 15560 // will cause the last vector in the sequence to be (re)loaded. 15561 // Otherwise, the next vector will be fetched as you might suspect was 15562 // necessary. 15563 15564 // We might be able to reuse the permutation generation from 15565 // a different base address offset from this one by an aligned amount. 15566 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15567 // optimization later. 15568 Intrinsic::ID Intr, IntrLD, IntrPerm; 15569 MVT PermCntlTy, PermTy, LDTy; 15570 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15571 : Intrinsic::ppc_altivec_lvsl; 15572 IntrLD = Intrinsic::ppc_altivec_lvx; 15573 IntrPerm = Intrinsic::ppc_altivec_vperm; 15574 PermCntlTy = MVT::v16i8; 15575 PermTy = MVT::v4i32; 15576 LDTy = MVT::v4i32; 15577 15578 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15579 15580 // Create the new MMO for the new base load. It is like the original MMO, 15581 // but represents an area in memory almost twice the vector size centered 15582 // on the original address. If the address is unaligned, we might start 15583 // reading up to (sizeof(vector)-1) bytes below the address of the 15584 // original unaligned load. 15585 MachineFunction &MF = DAG.getMachineFunction(); 15586 MachineMemOperand *BaseMMO = 15587 MF.getMachineMemOperand(LD->getMemOperand(), 15588 -(int64_t)MemVT.getStoreSize()+1, 15589 2*MemVT.getStoreSize()-1); 15590 15591 // Create the new base load. 15592 SDValue LDXIntID = 15593 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15594 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15595 SDValue BaseLoad = 15596 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15597 DAG.getVTList(PermTy, MVT::Other), 15598 BaseLoadOps, LDTy, BaseMMO); 15599 15600 // Note that the value of IncOffset (which is provided to the next 15601 // load's pointer info offset value, and thus used to calculate the 15602 // alignment), and the value of IncValue (which is actually used to 15603 // increment the pointer value) are different! This is because we 15604 // require the next load to appear to be aligned, even though it 15605 // is actually offset from the base pointer by a lesser amount. 15606 int IncOffset = VT.getSizeInBits() / 8; 15607 int IncValue = IncOffset; 15608 15609 // Walk (both up and down) the chain looking for another load at the real 15610 // (aligned) offset (the alignment of the other load does not matter in 15611 // this case). If found, then do not use the offset reduction trick, as 15612 // that will prevent the loads from being later combined (as they would 15613 // otherwise be duplicates). 15614 if (!findConsecutiveLoad(LD, DAG)) 15615 --IncValue; 15616 15617 SDValue Increment = 15618 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15619 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15620 15621 MachineMemOperand *ExtraMMO = 15622 MF.getMachineMemOperand(LD->getMemOperand(), 15623 1, 2*MemVT.getStoreSize()-1); 15624 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15625 SDValue ExtraLoad = 15626 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15627 DAG.getVTList(PermTy, MVT::Other), 15628 ExtraLoadOps, LDTy, ExtraMMO); 15629 15630 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15631 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15632 15633 // Because vperm has a big-endian bias, we must reverse the order 15634 // of the input vectors and complement the permute control vector 15635 // when generating little endian code. We have already handled the 15636 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15637 // and ExtraLoad here. 15638 SDValue Perm; 15639 if (isLittleEndian) 15640 Perm = BuildIntrinsicOp(IntrPerm, 15641 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15642 else 15643 Perm = BuildIntrinsicOp(IntrPerm, 15644 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15645 15646 if (VT != PermTy) 15647 Perm = Subtarget.hasAltivec() 15648 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15649 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15650 DAG.getTargetConstant(1, dl, MVT::i64)); 15651 // second argument is 1 because this rounding 15652 // is always exact. 15653 15654 // The output of the permutation is our loaded result, the TokenFactor is 15655 // our new chain. 15656 DCI.CombineTo(N, Perm, TF); 15657 return SDValue(N, 0); 15658 } 15659 } 15660 break; 15661 case ISD::INTRINSIC_WO_CHAIN: { 15662 bool isLittleEndian = Subtarget.isLittleEndian(); 15663 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15664 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15665 : Intrinsic::ppc_altivec_lvsl); 15666 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15667 SDValue Add = N->getOperand(1); 15668 15669 int Bits = 4 /* 16 byte alignment */; 15670 15671 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15672 APInt::getAllOnes(Bits /* alignment */) 15673 .zext(Add.getScalarValueSizeInBits()))) { 15674 SDNode *BasePtr = Add->getOperand(0).getNode(); 15675 for (SDNode *U : BasePtr->uses()) { 15676 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15677 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15678 // We've found another LVSL/LVSR, and this address is an aligned 15679 // multiple of that one. The results will be the same, so use the 15680 // one we've just found instead. 15681 15682 return SDValue(U, 0); 15683 } 15684 } 15685 } 15686 15687 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15688 SDNode *BasePtr = Add->getOperand(0).getNode(); 15689 for (SDNode *U : BasePtr->uses()) { 15690 if (U->getOpcode() == ISD::ADD && 15691 isa<ConstantSDNode>(U->getOperand(1)) && 15692 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15693 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15694 (1ULL << Bits) == 15695 0) { 15696 SDNode *OtherAdd = U; 15697 for (SDNode *V : OtherAdd->uses()) { 15698 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15699 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15700 IID) { 15701 return SDValue(V, 0); 15702 } 15703 } 15704 } 15705 } 15706 } 15707 } 15708 15709 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15710 // Expose the vabsduw/h/b opportunity for down stream 15711 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15712 (IID == Intrinsic::ppc_altivec_vmaxsw || 15713 IID == Intrinsic::ppc_altivec_vmaxsh || 15714 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15715 SDValue V1 = N->getOperand(1); 15716 SDValue V2 = N->getOperand(2); 15717 if ((V1.getSimpleValueType() == MVT::v4i32 || 15718 V1.getSimpleValueType() == MVT::v8i16 || 15719 V1.getSimpleValueType() == MVT::v16i8) && 15720 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15721 // (0-a, a) 15722 if (V1.getOpcode() == ISD::SUB && 15723 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15724 V1.getOperand(1) == V2) { 15725 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15726 } 15727 // (a, 0-a) 15728 if (V2.getOpcode() == ISD::SUB && 15729 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15730 V2.getOperand(1) == V1) { 15731 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15732 } 15733 // (x-y, y-x) 15734 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15735 V1.getOperand(0) == V2.getOperand(1) && 15736 V1.getOperand(1) == V2.getOperand(0)) { 15737 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15738 } 15739 } 15740 } 15741 } 15742 15743 break; 15744 case ISD::INTRINSIC_W_CHAIN: 15745 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15746 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15747 if (Subtarget.needsSwapsForVSXMemOps()) { 15748 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15749 default: 15750 break; 15751 case Intrinsic::ppc_vsx_lxvw4x: 15752 case Intrinsic::ppc_vsx_lxvd2x: 15753 return expandVSXLoadForLE(N, DCI); 15754 } 15755 } 15756 break; 15757 case ISD::INTRINSIC_VOID: 15758 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15759 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15760 if (Subtarget.needsSwapsForVSXMemOps()) { 15761 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15762 default: 15763 break; 15764 case Intrinsic::ppc_vsx_stxvw4x: 15765 case Intrinsic::ppc_vsx_stxvd2x: 15766 return expandVSXStoreForLE(N, DCI); 15767 } 15768 } 15769 break; 15770 case ISD::BSWAP: { 15771 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15772 // For subtargets without LDBRX, we can still do better than the default 15773 // expansion even for 64-bit BSWAP (LOAD). 15774 bool Is64BitBswapOn64BitTgt = 15775 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15776 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15777 N->getOperand(0).hasOneUse(); 15778 if (IsSingleUseNormalLd && 15779 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15780 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15781 SDValue Load = N->getOperand(0); 15782 LoadSDNode *LD = cast<LoadSDNode>(Load); 15783 // Create the byte-swapping load. 15784 SDValue Ops[] = { 15785 LD->getChain(), // Chain 15786 LD->getBasePtr(), // Ptr 15787 DAG.getValueType(N->getValueType(0)) // VT 15788 }; 15789 SDValue BSLoad = 15790 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15791 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15792 MVT::i64 : MVT::i32, MVT::Other), 15793 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15794 15795 // If this is an i16 load, insert the truncate. 15796 SDValue ResVal = BSLoad; 15797 if (N->getValueType(0) == MVT::i16) 15798 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15799 15800 // First, combine the bswap away. This makes the value produced by the 15801 // load dead. 15802 DCI.CombineTo(N, ResVal); 15803 15804 // Next, combine the load away, we give it a bogus result value but a real 15805 // chain result. The result value is dead because the bswap is dead. 15806 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15807 15808 // Return N so it doesn't get rechecked! 15809 return SDValue(N, 0); 15810 } 15811 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15812 // before legalization so that the BUILD_PAIR is handled correctly. 15813 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15814 !IsSingleUseNormalLd) 15815 return SDValue(); 15816 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15817 15818 // Can't split volatile or atomic loads. 15819 if (!LD->isSimple()) 15820 return SDValue(); 15821 SDValue BasePtr = LD->getBasePtr(); 15822 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15823 LD->getPointerInfo(), LD->getAlign()); 15824 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15825 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15826 DAG.getIntPtrConstant(4, dl)); 15827 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15828 LD->getMemOperand(), 4, 4); 15829 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15830 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15831 SDValue Res; 15832 if (Subtarget.isLittleEndian()) 15833 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15834 else 15835 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15836 SDValue TF = 15837 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15838 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15839 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15840 return Res; 15841 } 15842 case PPCISD::VCMP: 15843 // If a VCMP_rec node already exists with exactly the same operands as this 15844 // node, use its result instead of this node (VCMP_rec computes both a CR6 15845 // and a normal output). 15846 // 15847 if (!N->getOperand(0).hasOneUse() && 15848 !N->getOperand(1).hasOneUse() && 15849 !N->getOperand(2).hasOneUse()) { 15850 15851 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15852 SDNode *VCMPrecNode = nullptr; 15853 15854 SDNode *LHSN = N->getOperand(0).getNode(); 15855 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15856 UI != E; ++UI) 15857 if (UI->getOpcode() == PPCISD::VCMP_rec && 15858 UI->getOperand(1) == N->getOperand(1) && 15859 UI->getOperand(2) == N->getOperand(2) && 15860 UI->getOperand(0) == N->getOperand(0)) { 15861 VCMPrecNode = *UI; 15862 break; 15863 } 15864 15865 // If there is no VCMP_rec node, or if the flag value has a single use, 15866 // don't transform this. 15867 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15868 break; 15869 15870 // Look at the (necessarily single) use of the flag value. If it has a 15871 // chain, this transformation is more complex. Note that multiple things 15872 // could use the value result, which we should ignore. 15873 SDNode *FlagUser = nullptr; 15874 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15875 FlagUser == nullptr; ++UI) { 15876 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15877 SDNode *User = *UI; 15878 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15879 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15880 FlagUser = User; 15881 break; 15882 } 15883 } 15884 } 15885 15886 // If the user is a MFOCRF instruction, we know this is safe. 15887 // Otherwise we give up for right now. 15888 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15889 return SDValue(VCMPrecNode, 0); 15890 } 15891 break; 15892 case ISD::BR_CC: { 15893 // If this is a branch on an altivec predicate comparison, lower this so 15894 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15895 // lowering is done pre-legalize, because the legalizer lowers the predicate 15896 // compare down to code that is difficult to reassemble. 15897 // This code also handles branches that depend on the result of a store 15898 // conditional. 15899 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15900 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15901 15902 int CompareOpc; 15903 bool isDot; 15904 15905 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE)) 15906 break; 15907 15908 // Since we are doing this pre-legalize, the RHS can be a constant of 15909 // arbitrary bitwidth which may cause issues when trying to get the value 15910 // from the underlying APInt. 15911 auto RHSAPInt = cast<ConstantSDNode>(RHS)->getAPIntValue(); 15912 if (!RHSAPInt.isIntN(64)) 15913 break; 15914 15915 unsigned Val = RHSAPInt.getZExtValue(); 15916 auto isImpossibleCompare = [&]() { 15917 // If this is a comparison against something other than 0/1, then we know 15918 // that the condition is never/always true. 15919 if (Val != 0 && Val != 1) { 15920 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15921 return N->getOperand(0); 15922 // Always !=, turn it into an unconditional branch. 15923 return DAG.getNode(ISD::BR, dl, MVT::Other, 15924 N->getOperand(0), N->getOperand(4)); 15925 } 15926 return SDValue(); 15927 }; 15928 // Combine branches fed by store conditional instructions (st[bhwd]cx). 15929 unsigned StoreWidth = 0; 15930 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15931 isStoreConditional(LHS, StoreWidth)) { 15932 if (SDValue Impossible = isImpossibleCompare()) 15933 return Impossible; 15934 PPC::Predicate CompOpc; 15935 // eq 0 => ne 15936 // ne 0 => eq 15937 // eq 1 => eq 15938 // ne 1 => ne 15939 if (Val == 0) 15940 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ; 15941 else 15942 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE; 15943 15944 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3), 15945 DAG.getConstant(StoreWidth, dl, MVT::i32)}; 15946 auto *MemNode = cast<MemSDNode>(LHS); 15947 SDValue ConstSt = DAG.getMemIntrinsicNode( 15948 PPCISD::STORE_COND, dl, 15949 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops, 15950 MemNode->getMemoryVT(), MemNode->getMemOperand()); 15951 15952 SDValue InChain; 15953 // Unchain the branch from the original store conditional. 15954 if (N->getOperand(0) == LHS.getValue(1)) 15955 InChain = LHS.getOperand(0); 15956 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) { 15957 SmallVector<SDValue, 4> InChains; 15958 SDValue InTF = N->getOperand(0); 15959 for (int i = 0, e = InTF.getNumOperands(); i < e; i++) 15960 if (InTF.getOperand(i) != LHS.getValue(1)) 15961 InChains.push_back(InTF.getOperand(i)); 15962 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains); 15963 } 15964 15965 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain, 15966 DAG.getConstant(CompOpc, dl, MVT::i32), 15967 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4), 15968 ConstSt.getValue(2)); 15969 } 15970 15971 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15972 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15973 assert(isDot && "Can't compare against a vector result!"); 15974 15975 if (SDValue Impossible = isImpossibleCompare()) 15976 return Impossible; 15977 15978 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15979 // Create the PPCISD altivec 'dot' comparison node. 15980 SDValue Ops[] = { 15981 LHS.getOperand(2), // LHS of compare 15982 LHS.getOperand(3), // RHS of compare 15983 DAG.getConstant(CompareOpc, dl, MVT::i32) 15984 }; 15985 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15986 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15987 15988 // Unpack the result based on how the target uses it. 15989 PPC::Predicate CompOpc; 15990 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15991 default: // Can't happen, don't crash on invalid number though. 15992 case 0: // Branch on the value of the EQ bit of CR6. 15993 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15994 break; 15995 case 1: // Branch on the inverted value of the EQ bit of CR6. 15996 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15997 break; 15998 case 2: // Branch on the value of the LT bit of CR6. 15999 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 16000 break; 16001 case 3: // Branch on the inverted value of the LT bit of CR6. 16002 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 16003 break; 16004 } 16005 16006 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 16007 DAG.getConstant(CompOpc, dl, MVT::i32), 16008 DAG.getRegister(PPC::CR6, MVT::i32), 16009 N->getOperand(4), CompNode.getValue(1)); 16010 } 16011 break; 16012 } 16013 case ISD::BUILD_VECTOR: 16014 return DAGCombineBuildVector(N, DCI); 16015 case ISD::VSELECT: 16016 return combineVSelect(N, DCI); 16017 } 16018 16019 return SDValue(); 16020 } 16021 16022 SDValue 16023 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 16024 SelectionDAG &DAG, 16025 SmallVectorImpl<SDNode *> &Created) const { 16026 // fold (sdiv X, pow2) 16027 EVT VT = N->getValueType(0); 16028 if (VT == MVT::i64 && !Subtarget.isPPC64()) 16029 return SDValue(); 16030 if ((VT != MVT::i32 && VT != MVT::i64) || 16031 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 16032 return SDValue(); 16033 16034 SDLoc DL(N); 16035 SDValue N0 = N->getOperand(0); 16036 16037 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 16038 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 16039 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 16040 16041 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 16042 Created.push_back(Op.getNode()); 16043 16044 if (IsNegPow2) { 16045 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 16046 Created.push_back(Op.getNode()); 16047 } 16048 16049 return Op; 16050 } 16051 16052 //===----------------------------------------------------------------------===// 16053 // Inline Assembly Support 16054 //===----------------------------------------------------------------------===// 16055 16056 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 16057 KnownBits &Known, 16058 const APInt &DemandedElts, 16059 const SelectionDAG &DAG, 16060 unsigned Depth) const { 16061 Known.resetAll(); 16062 switch (Op.getOpcode()) { 16063 default: break; 16064 case PPCISD::LBRX: { 16065 // lhbrx is known to have the top bits cleared out. 16066 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 16067 Known.Zero = 0xFFFF0000; 16068 break; 16069 } 16070 case ISD::INTRINSIC_WO_CHAIN: { 16071 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 16072 default: break; 16073 case Intrinsic::ppc_altivec_vcmpbfp_p: 16074 case Intrinsic::ppc_altivec_vcmpeqfp_p: 16075 case Intrinsic::ppc_altivec_vcmpequb_p: 16076 case Intrinsic::ppc_altivec_vcmpequh_p: 16077 case Intrinsic::ppc_altivec_vcmpequw_p: 16078 case Intrinsic::ppc_altivec_vcmpequd_p: 16079 case Intrinsic::ppc_altivec_vcmpequq_p: 16080 case Intrinsic::ppc_altivec_vcmpgefp_p: 16081 case Intrinsic::ppc_altivec_vcmpgtfp_p: 16082 case Intrinsic::ppc_altivec_vcmpgtsb_p: 16083 case Intrinsic::ppc_altivec_vcmpgtsh_p: 16084 case Intrinsic::ppc_altivec_vcmpgtsw_p: 16085 case Intrinsic::ppc_altivec_vcmpgtsd_p: 16086 case Intrinsic::ppc_altivec_vcmpgtsq_p: 16087 case Intrinsic::ppc_altivec_vcmpgtub_p: 16088 case Intrinsic::ppc_altivec_vcmpgtuh_p: 16089 case Intrinsic::ppc_altivec_vcmpgtuw_p: 16090 case Intrinsic::ppc_altivec_vcmpgtud_p: 16091 case Intrinsic::ppc_altivec_vcmpgtuq_p: 16092 Known.Zero = ~1U; // All bits but the low one are known to be zero. 16093 break; 16094 } 16095 break; 16096 } 16097 case ISD::INTRINSIC_W_CHAIN: { 16098 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 16099 default: 16100 break; 16101 case Intrinsic::ppc_load2r: 16102 // Top bits are cleared for load2r (which is the same as lhbrx). 16103 Known.Zero = 0xFFFF0000; 16104 break; 16105 } 16106 break; 16107 } 16108 } 16109 } 16110 16111 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 16112 switch (Subtarget.getCPUDirective()) { 16113 default: break; 16114 case PPC::DIR_970: 16115 case PPC::DIR_PWR4: 16116 case PPC::DIR_PWR5: 16117 case PPC::DIR_PWR5X: 16118 case PPC::DIR_PWR6: 16119 case PPC::DIR_PWR6X: 16120 case PPC::DIR_PWR7: 16121 case PPC::DIR_PWR8: 16122 case PPC::DIR_PWR9: 16123 case PPC::DIR_PWR10: 16124 case PPC::DIR_PWR_FUTURE: { 16125 if (!ML) 16126 break; 16127 16128 if (!DisableInnermostLoopAlign32) { 16129 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 16130 // so that we can decrease cache misses and branch-prediction misses. 16131 // Actual alignment of the loop will depend on the hotness check and other 16132 // logic in alignBlocks. 16133 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 16134 return Align(32); 16135 } 16136 16137 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 16138 16139 // For small loops (between 5 and 8 instructions), align to a 32-byte 16140 // boundary so that the entire loop fits in one instruction-cache line. 16141 uint64_t LoopSize = 0; 16142 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 16143 for (const MachineInstr &J : **I) { 16144 LoopSize += TII->getInstSizeInBytes(J); 16145 if (LoopSize > 32) 16146 break; 16147 } 16148 16149 if (LoopSize > 16 && LoopSize <= 32) 16150 return Align(32); 16151 16152 break; 16153 } 16154 } 16155 16156 return TargetLowering::getPrefLoopAlignment(ML); 16157 } 16158 16159 /// getConstraintType - Given a constraint, return the type of 16160 /// constraint it is for this target. 16161 PPCTargetLowering::ConstraintType 16162 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 16163 if (Constraint.size() == 1) { 16164 switch (Constraint[0]) { 16165 default: break; 16166 case 'b': 16167 case 'r': 16168 case 'f': 16169 case 'd': 16170 case 'v': 16171 case 'y': 16172 return C_RegisterClass; 16173 case 'Z': 16174 // FIXME: While Z does indicate a memory constraint, it specifically 16175 // indicates an r+r address (used in conjunction with the 'y' modifier 16176 // in the replacement string). Currently, we're forcing the base 16177 // register to be r0 in the asm printer (which is interpreted as zero) 16178 // and forming the complete address in the second register. This is 16179 // suboptimal. 16180 return C_Memory; 16181 } 16182 } else if (Constraint == "wc") { // individual CR bits. 16183 return C_RegisterClass; 16184 } else if (Constraint == "wa" || Constraint == "wd" || 16185 Constraint == "wf" || Constraint == "ws" || 16186 Constraint == "wi" || Constraint == "ww") { 16187 return C_RegisterClass; // VSX registers. 16188 } 16189 return TargetLowering::getConstraintType(Constraint); 16190 } 16191 16192 /// Examine constraint type and operand type and determine a weight value. 16193 /// This object must already have been set up with the operand type 16194 /// and the current alternative constraint selected. 16195 TargetLowering::ConstraintWeight 16196 PPCTargetLowering::getSingleConstraintMatchWeight( 16197 AsmOperandInfo &info, const char *constraint) const { 16198 ConstraintWeight weight = CW_Invalid; 16199 Value *CallOperandVal = info.CallOperandVal; 16200 // If we don't have a value, we can't do a match, 16201 // but allow it at the lowest weight. 16202 if (!CallOperandVal) 16203 return CW_Default; 16204 Type *type = CallOperandVal->getType(); 16205 16206 // Look at the constraint type. 16207 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 16208 return CW_Register; // an individual CR bit. 16209 else if ((StringRef(constraint) == "wa" || 16210 StringRef(constraint) == "wd" || 16211 StringRef(constraint) == "wf") && 16212 type->isVectorTy()) 16213 return CW_Register; 16214 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 16215 return CW_Register; // just hold 64-bit integers data. 16216 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 16217 return CW_Register; 16218 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 16219 return CW_Register; 16220 16221 switch (*constraint) { 16222 default: 16223 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 16224 break; 16225 case 'b': 16226 if (type->isIntegerTy()) 16227 weight = CW_Register; 16228 break; 16229 case 'f': 16230 if (type->isFloatTy()) 16231 weight = CW_Register; 16232 break; 16233 case 'd': 16234 if (type->isDoubleTy()) 16235 weight = CW_Register; 16236 break; 16237 case 'v': 16238 if (type->isVectorTy()) 16239 weight = CW_Register; 16240 break; 16241 case 'y': 16242 weight = CW_Register; 16243 break; 16244 case 'Z': 16245 weight = CW_Memory; 16246 break; 16247 } 16248 return weight; 16249 } 16250 16251 std::pair<unsigned, const TargetRegisterClass *> 16252 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 16253 StringRef Constraint, 16254 MVT VT) const { 16255 if (Constraint.size() == 1) { 16256 // GCC RS6000 Constraint Letters 16257 switch (Constraint[0]) { 16258 case 'b': // R1-R31 16259 if (VT == MVT::i64 && Subtarget.isPPC64()) 16260 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 16261 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 16262 case 'r': // R0-R31 16263 if (VT == MVT::i64 && Subtarget.isPPC64()) 16264 return std::make_pair(0U, &PPC::G8RCRegClass); 16265 return std::make_pair(0U, &PPC::GPRCRegClass); 16266 // 'd' and 'f' constraints are both defined to be "the floating point 16267 // registers", where one is for 32-bit and the other for 64-bit. We don't 16268 // really care overly much here so just give them all the same reg classes. 16269 case 'd': 16270 case 'f': 16271 if (Subtarget.hasSPE()) { 16272 if (VT == MVT::f32 || VT == MVT::i32) 16273 return std::make_pair(0U, &PPC::GPRCRegClass); 16274 if (VT == MVT::f64 || VT == MVT::i64) 16275 return std::make_pair(0U, &PPC::SPERCRegClass); 16276 } else { 16277 if (VT == MVT::f32 || VT == MVT::i32) 16278 return std::make_pair(0U, &PPC::F4RCRegClass); 16279 if (VT == MVT::f64 || VT == MVT::i64) 16280 return std::make_pair(0U, &PPC::F8RCRegClass); 16281 } 16282 break; 16283 case 'v': 16284 if (Subtarget.hasAltivec() && VT.isVector()) 16285 return std::make_pair(0U, &PPC::VRRCRegClass); 16286 else if (Subtarget.hasVSX()) 16287 // Scalars in Altivec registers only make sense with VSX. 16288 return std::make_pair(0U, &PPC::VFRCRegClass); 16289 break; 16290 case 'y': // crrc 16291 return std::make_pair(0U, &PPC::CRRCRegClass); 16292 } 16293 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 16294 // An individual CR bit. 16295 return std::make_pair(0U, &PPC::CRBITRCRegClass); 16296 } else if ((Constraint == "wa" || Constraint == "wd" || 16297 Constraint == "wf" || Constraint == "wi") && 16298 Subtarget.hasVSX()) { 16299 // A VSX register for either a scalar (FP) or vector. There is no 16300 // support for single precision scalars on subtargets prior to Power8. 16301 if (VT.isVector()) 16302 return std::make_pair(0U, &PPC::VSRCRegClass); 16303 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16304 return std::make_pair(0U, &PPC::VSSRCRegClass); 16305 return std::make_pair(0U, &PPC::VSFRCRegClass); 16306 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 16307 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16308 return std::make_pair(0U, &PPC::VSSRCRegClass); 16309 else 16310 return std::make_pair(0U, &PPC::VSFRCRegClass); 16311 } else if (Constraint == "lr") { 16312 if (VT == MVT::i64) 16313 return std::make_pair(0U, &PPC::LR8RCRegClass); 16314 else 16315 return std::make_pair(0U, &PPC::LRRCRegClass); 16316 } 16317 16318 // Handle special cases of physical registers that are not properly handled 16319 // by the base class. 16320 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16321 // If we name a VSX register, we can't defer to the base class because it 16322 // will not recognize the correct register (their names will be VSL{0-31} 16323 // and V{0-31} so they won't match). So we match them here. 16324 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16325 int VSNum = atoi(Constraint.data() + 3); 16326 assert(VSNum >= 0 && VSNum <= 63 && 16327 "Attempted to access a vsr out of range"); 16328 if (VSNum < 32) 16329 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16330 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16331 } 16332 16333 // For float registers, we can't defer to the base class as it will match 16334 // the SPILLTOVSRRC class. 16335 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16336 int RegNum = atoi(Constraint.data() + 2); 16337 if (RegNum > 31 || RegNum < 0) 16338 report_fatal_error("Invalid floating point register number"); 16339 if (VT == MVT::f32 || VT == MVT::i32) 16340 return Subtarget.hasSPE() 16341 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16342 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16343 if (VT == MVT::f64 || VT == MVT::i64) 16344 return Subtarget.hasSPE() 16345 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16346 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16347 } 16348 } 16349 16350 std::pair<unsigned, const TargetRegisterClass *> R = 16351 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16352 16353 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16354 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16355 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16356 // register. 16357 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16358 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16359 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16360 PPC::GPRCRegClass.contains(R.first)) 16361 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16362 PPC::sub_32, &PPC::G8RCRegClass), 16363 &PPC::G8RCRegClass); 16364 16365 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16366 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16367 R.first = PPC::CR0; 16368 R.second = &PPC::CRRCRegClass; 16369 } 16370 // FIXME: This warning should ideally be emitted in the front end. 16371 const auto &TM = getTargetMachine(); 16372 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16373 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16374 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16375 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16376 errs() << "warning: vector registers 20 to 32 are reserved in the " 16377 "default AIX AltiVec ABI and cannot be used\n"; 16378 } 16379 16380 return R; 16381 } 16382 16383 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16384 /// vector. If it is invalid, don't add anything to Ops. 16385 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16386 std::string &Constraint, 16387 std::vector<SDValue>&Ops, 16388 SelectionDAG &DAG) const { 16389 SDValue Result; 16390 16391 // Only support length 1 constraints. 16392 if (Constraint.length() > 1) return; 16393 16394 char Letter = Constraint[0]; 16395 switch (Letter) { 16396 default: break; 16397 case 'I': 16398 case 'J': 16399 case 'K': 16400 case 'L': 16401 case 'M': 16402 case 'N': 16403 case 'O': 16404 case 'P': { 16405 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16406 if (!CST) return; // Must be an immediate to match. 16407 SDLoc dl(Op); 16408 int64_t Value = CST->getSExtValue(); 16409 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16410 // numbers are printed as such. 16411 switch (Letter) { 16412 default: llvm_unreachable("Unknown constraint letter!"); 16413 case 'I': // "I" is a signed 16-bit constant. 16414 if (isInt<16>(Value)) 16415 Result = DAG.getTargetConstant(Value, dl, TCVT); 16416 break; 16417 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16418 if (isShiftedUInt<16, 16>(Value)) 16419 Result = DAG.getTargetConstant(Value, dl, TCVT); 16420 break; 16421 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16422 if (isShiftedInt<16, 16>(Value)) 16423 Result = DAG.getTargetConstant(Value, dl, TCVT); 16424 break; 16425 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16426 if (isUInt<16>(Value)) 16427 Result = DAG.getTargetConstant(Value, dl, TCVT); 16428 break; 16429 case 'M': // "M" is a constant that is greater than 31. 16430 if (Value > 31) 16431 Result = DAG.getTargetConstant(Value, dl, TCVT); 16432 break; 16433 case 'N': // "N" is a positive constant that is an exact power of two. 16434 if (Value > 0 && isPowerOf2_64(Value)) 16435 Result = DAG.getTargetConstant(Value, dl, TCVT); 16436 break; 16437 case 'O': // "O" is the constant zero. 16438 if (Value == 0) 16439 Result = DAG.getTargetConstant(Value, dl, TCVT); 16440 break; 16441 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16442 if (isInt<16>(-Value)) 16443 Result = DAG.getTargetConstant(Value, dl, TCVT); 16444 break; 16445 } 16446 break; 16447 } 16448 } 16449 16450 if (Result.getNode()) { 16451 Ops.push_back(Result); 16452 return; 16453 } 16454 16455 // Handle standard constraint letters. 16456 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16457 } 16458 16459 void PPCTargetLowering::CollectTargetIntrinsicOperands(const CallInst &I, 16460 SmallVectorImpl<SDValue> &Ops, 16461 SelectionDAG &DAG) const { 16462 if (I.getNumOperands() <= 1) 16463 return; 16464 if (!isa<ConstantSDNode>(Ops[1].getNode())) 16465 return; 16466 auto IntrinsicID = cast<ConstantSDNode>(Ops[1].getNode())->getZExtValue(); 16467 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw && 16468 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap) 16469 return; 16470 16471 if (I.hasMetadata("annotation")) { 16472 MDNode *MDN = I.getMetadata("annotation"); 16473 Ops.push_back(DAG.getMDNode(MDN)); 16474 } 16475 } 16476 16477 // isLegalAddressingMode - Return true if the addressing mode represented 16478 // by AM is legal for this target, for a load/store of the specified type. 16479 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16480 const AddrMode &AM, Type *Ty, 16481 unsigned AS, 16482 Instruction *I) const { 16483 // Vector type r+i form is supported since power9 as DQ form. We don't check 16484 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16485 // imm form is preferred and the offset can be adjusted to use imm form later 16486 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16487 // max offset to check legal addressing mode, we should be a little aggressive 16488 // to contain other offsets for that LSRUse. 16489 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16490 return false; 16491 16492 // PPC allows a sign-extended 16-bit immediate field. 16493 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16494 return false; 16495 16496 // No global is ever allowed as a base. 16497 if (AM.BaseGV) 16498 return false; 16499 16500 // PPC only support r+r, 16501 switch (AM.Scale) { 16502 case 0: // "r+i" or just "i", depending on HasBaseReg. 16503 break; 16504 case 1: 16505 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16506 return false; 16507 // Otherwise we have r+r or r+i. 16508 break; 16509 case 2: 16510 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16511 return false; 16512 // Allow 2*r as r+r. 16513 break; 16514 default: 16515 // No other scales are supported. 16516 return false; 16517 } 16518 16519 return true; 16520 } 16521 16522 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16523 SelectionDAG &DAG) const { 16524 MachineFunction &MF = DAG.getMachineFunction(); 16525 MachineFrameInfo &MFI = MF.getFrameInfo(); 16526 MFI.setReturnAddressIsTaken(true); 16527 16528 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16529 return SDValue(); 16530 16531 SDLoc dl(Op); 16532 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16533 16534 // Make sure the function does not optimize away the store of the RA to 16535 // the stack. 16536 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16537 FuncInfo->setLRStoreRequired(); 16538 bool isPPC64 = Subtarget.isPPC64(); 16539 auto PtrVT = getPointerTy(MF.getDataLayout()); 16540 16541 if (Depth > 0) { 16542 // The link register (return address) is saved in the caller's frame 16543 // not the callee's stack frame. So we must get the caller's frame 16544 // address and load the return address at the LR offset from there. 16545 SDValue FrameAddr = 16546 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16547 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16548 SDValue Offset = 16549 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16550 isPPC64 ? MVT::i64 : MVT::i32); 16551 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16552 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16553 MachinePointerInfo()); 16554 } 16555 16556 // Just load the return address off the stack. 16557 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16558 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16559 MachinePointerInfo()); 16560 } 16561 16562 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16563 SelectionDAG &DAG) const { 16564 SDLoc dl(Op); 16565 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16566 16567 MachineFunction &MF = DAG.getMachineFunction(); 16568 MachineFrameInfo &MFI = MF.getFrameInfo(); 16569 MFI.setFrameAddressIsTaken(true); 16570 16571 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16572 bool isPPC64 = PtrVT == MVT::i64; 16573 16574 // Naked functions never have a frame pointer, and so we use r1. For all 16575 // other functions, this decision must be delayed until during PEI. 16576 unsigned FrameReg; 16577 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16578 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16579 else 16580 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16581 16582 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16583 PtrVT); 16584 while (Depth--) 16585 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16586 FrameAddr, MachinePointerInfo()); 16587 return FrameAddr; 16588 } 16589 16590 // FIXME? Maybe this could be a TableGen attribute on some registers and 16591 // this table could be generated automatically from RegInfo. 16592 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16593 const MachineFunction &MF) const { 16594 bool isPPC64 = Subtarget.isPPC64(); 16595 16596 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16597 if (!is64Bit && VT != LLT::scalar(32)) 16598 report_fatal_error("Invalid register global variable type"); 16599 16600 Register Reg = StringSwitch<Register>(RegName) 16601 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16602 .Case("r2", isPPC64 ? Register() : PPC::R2) 16603 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16604 .Default(Register()); 16605 16606 if (Reg) 16607 return Reg; 16608 report_fatal_error("Invalid register name global variable"); 16609 } 16610 16611 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16612 // 32-bit SVR4 ABI access everything as got-indirect. 16613 if (Subtarget.is32BitELFABI()) 16614 return true; 16615 16616 // AIX accesses everything indirectly through the TOC, which is similar to 16617 // the GOT. 16618 if (Subtarget.isAIXABI()) 16619 return true; 16620 16621 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16622 // If it is small or large code model, module locals are accessed 16623 // indirectly by loading their address from .toc/.got. 16624 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16625 return true; 16626 16627 // JumpTable and BlockAddress are accessed as got-indirect. 16628 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16629 return true; 16630 16631 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16632 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16633 16634 return false; 16635 } 16636 16637 bool 16638 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16639 // The PowerPC target isn't yet aware of offsets. 16640 return false; 16641 } 16642 16643 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16644 const CallInst &I, 16645 MachineFunction &MF, 16646 unsigned Intrinsic) const { 16647 switch (Intrinsic) { 16648 case Intrinsic::ppc_atomicrmw_xchg_i128: 16649 case Intrinsic::ppc_atomicrmw_add_i128: 16650 case Intrinsic::ppc_atomicrmw_sub_i128: 16651 case Intrinsic::ppc_atomicrmw_nand_i128: 16652 case Intrinsic::ppc_atomicrmw_and_i128: 16653 case Intrinsic::ppc_atomicrmw_or_i128: 16654 case Intrinsic::ppc_atomicrmw_xor_i128: 16655 case Intrinsic::ppc_cmpxchg_i128: 16656 Info.opc = ISD::INTRINSIC_W_CHAIN; 16657 Info.memVT = MVT::i128; 16658 Info.ptrVal = I.getArgOperand(0); 16659 Info.offset = 0; 16660 Info.align = Align(16); 16661 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16662 MachineMemOperand::MOVolatile; 16663 return true; 16664 case Intrinsic::ppc_atomic_load_i128: 16665 Info.opc = ISD::INTRINSIC_W_CHAIN; 16666 Info.memVT = MVT::i128; 16667 Info.ptrVal = I.getArgOperand(0); 16668 Info.offset = 0; 16669 Info.align = Align(16); 16670 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16671 return true; 16672 case Intrinsic::ppc_atomic_store_i128: 16673 Info.opc = ISD::INTRINSIC_VOID; 16674 Info.memVT = MVT::i128; 16675 Info.ptrVal = I.getArgOperand(2); 16676 Info.offset = 0; 16677 Info.align = Align(16); 16678 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16679 return true; 16680 case Intrinsic::ppc_altivec_lvx: 16681 case Intrinsic::ppc_altivec_lvxl: 16682 case Intrinsic::ppc_altivec_lvebx: 16683 case Intrinsic::ppc_altivec_lvehx: 16684 case Intrinsic::ppc_altivec_lvewx: 16685 case Intrinsic::ppc_vsx_lxvd2x: 16686 case Intrinsic::ppc_vsx_lxvw4x: 16687 case Intrinsic::ppc_vsx_lxvd2x_be: 16688 case Intrinsic::ppc_vsx_lxvw4x_be: 16689 case Intrinsic::ppc_vsx_lxvl: 16690 case Intrinsic::ppc_vsx_lxvll: { 16691 EVT VT; 16692 switch (Intrinsic) { 16693 case Intrinsic::ppc_altivec_lvebx: 16694 VT = MVT::i8; 16695 break; 16696 case Intrinsic::ppc_altivec_lvehx: 16697 VT = MVT::i16; 16698 break; 16699 case Intrinsic::ppc_altivec_lvewx: 16700 VT = MVT::i32; 16701 break; 16702 case Intrinsic::ppc_vsx_lxvd2x: 16703 case Intrinsic::ppc_vsx_lxvd2x_be: 16704 VT = MVT::v2f64; 16705 break; 16706 default: 16707 VT = MVT::v4i32; 16708 break; 16709 } 16710 16711 Info.opc = ISD::INTRINSIC_W_CHAIN; 16712 Info.memVT = VT; 16713 Info.ptrVal = I.getArgOperand(0); 16714 Info.offset = -VT.getStoreSize()+1; 16715 Info.size = 2*VT.getStoreSize()-1; 16716 Info.align = Align(1); 16717 Info.flags = MachineMemOperand::MOLoad; 16718 return true; 16719 } 16720 case Intrinsic::ppc_altivec_stvx: 16721 case Intrinsic::ppc_altivec_stvxl: 16722 case Intrinsic::ppc_altivec_stvebx: 16723 case Intrinsic::ppc_altivec_stvehx: 16724 case Intrinsic::ppc_altivec_stvewx: 16725 case Intrinsic::ppc_vsx_stxvd2x: 16726 case Intrinsic::ppc_vsx_stxvw4x: 16727 case Intrinsic::ppc_vsx_stxvd2x_be: 16728 case Intrinsic::ppc_vsx_stxvw4x_be: 16729 case Intrinsic::ppc_vsx_stxvl: 16730 case Intrinsic::ppc_vsx_stxvll: { 16731 EVT VT; 16732 switch (Intrinsic) { 16733 case Intrinsic::ppc_altivec_stvebx: 16734 VT = MVT::i8; 16735 break; 16736 case Intrinsic::ppc_altivec_stvehx: 16737 VT = MVT::i16; 16738 break; 16739 case Intrinsic::ppc_altivec_stvewx: 16740 VT = MVT::i32; 16741 break; 16742 case Intrinsic::ppc_vsx_stxvd2x: 16743 case Intrinsic::ppc_vsx_stxvd2x_be: 16744 VT = MVT::v2f64; 16745 break; 16746 default: 16747 VT = MVT::v4i32; 16748 break; 16749 } 16750 16751 Info.opc = ISD::INTRINSIC_VOID; 16752 Info.memVT = VT; 16753 Info.ptrVal = I.getArgOperand(1); 16754 Info.offset = -VT.getStoreSize()+1; 16755 Info.size = 2*VT.getStoreSize()-1; 16756 Info.align = Align(1); 16757 Info.flags = MachineMemOperand::MOStore; 16758 return true; 16759 } 16760 case Intrinsic::ppc_stdcx: 16761 case Intrinsic::ppc_stwcx: 16762 case Intrinsic::ppc_sthcx: 16763 case Intrinsic::ppc_stbcx: { 16764 EVT VT; 16765 auto Alignment = Align(8); 16766 switch (Intrinsic) { 16767 case Intrinsic::ppc_stdcx: 16768 VT = MVT::i64; 16769 break; 16770 case Intrinsic::ppc_stwcx: 16771 VT = MVT::i32; 16772 Alignment = Align(4); 16773 break; 16774 case Intrinsic::ppc_sthcx: 16775 VT = MVT::i16; 16776 Alignment = Align(2); 16777 break; 16778 case Intrinsic::ppc_stbcx: 16779 VT = MVT::i8; 16780 Alignment = Align(1); 16781 break; 16782 } 16783 Info.opc = ISD::INTRINSIC_W_CHAIN; 16784 Info.memVT = VT; 16785 Info.ptrVal = I.getArgOperand(0); 16786 Info.offset = 0; 16787 Info.align = Alignment; 16788 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16789 return true; 16790 } 16791 default: 16792 break; 16793 } 16794 16795 return false; 16796 } 16797 16798 /// It returns EVT::Other if the type should be determined using generic 16799 /// target-independent logic. 16800 EVT PPCTargetLowering::getOptimalMemOpType( 16801 const MemOp &Op, const AttributeList &FuncAttributes) const { 16802 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16803 // We should use Altivec/VSX loads and stores when available. For unaligned 16804 // addresses, unaligned VSX loads are only fast starting with the P8. 16805 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16806 (Op.isAligned(Align(16)) || 16807 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16808 return MVT::v4i32; 16809 } 16810 16811 if (Subtarget.isPPC64()) { 16812 return MVT::i64; 16813 } 16814 16815 return MVT::i32; 16816 } 16817 16818 /// Returns true if it is beneficial to convert a load of a constant 16819 /// to just the constant itself. 16820 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16821 Type *Ty) const { 16822 assert(Ty->isIntegerTy()); 16823 16824 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16825 return !(BitSize == 0 || BitSize > 64); 16826 } 16827 16828 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16829 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16830 return false; 16831 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16832 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16833 return NumBits1 == 64 && NumBits2 == 32; 16834 } 16835 16836 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16837 if (!VT1.isInteger() || !VT2.isInteger()) 16838 return false; 16839 unsigned NumBits1 = VT1.getSizeInBits(); 16840 unsigned NumBits2 = VT2.getSizeInBits(); 16841 return NumBits1 == 64 && NumBits2 == 32; 16842 } 16843 16844 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16845 // Generally speaking, zexts are not free, but they are free when they can be 16846 // folded with other operations. 16847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16848 EVT MemVT = LD->getMemoryVT(); 16849 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16850 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16851 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16852 LD->getExtensionType() == ISD::ZEXTLOAD)) 16853 return true; 16854 } 16855 16856 // FIXME: Add other cases... 16857 // - 32-bit shifts with a zext to i64 16858 // - zext after ctlz, bswap, etc. 16859 // - zext after and by a constant mask 16860 16861 return TargetLowering::isZExtFree(Val, VT2); 16862 } 16863 16864 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16865 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16866 "invalid fpext types"); 16867 // Extending to float128 is not free. 16868 if (DestVT == MVT::f128) 16869 return false; 16870 return true; 16871 } 16872 16873 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16874 return isInt<16>(Imm) || isUInt<16>(Imm); 16875 } 16876 16877 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16878 return isInt<16>(Imm) || isUInt<16>(Imm); 16879 } 16880 16881 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16882 MachineMemOperand::Flags, 16883 unsigned *Fast) const { 16884 if (DisablePPCUnaligned) 16885 return false; 16886 16887 // PowerPC supports unaligned memory access for simple non-vector types. 16888 // Although accessing unaligned addresses is not as efficient as accessing 16889 // aligned addresses, it is generally more efficient than manual expansion, 16890 // and generally only traps for software emulation when crossing page 16891 // boundaries. 16892 16893 if (!VT.isSimple()) 16894 return false; 16895 16896 if (VT.isFloatingPoint() && !VT.isVector() && 16897 !Subtarget.allowsUnalignedFPAccess()) 16898 return false; 16899 16900 if (VT.getSimpleVT().isVector()) { 16901 if (Subtarget.hasVSX()) { 16902 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16903 VT != MVT::v4f32 && VT != MVT::v4i32) 16904 return false; 16905 } else { 16906 return false; 16907 } 16908 } 16909 16910 if (VT == MVT::ppcf128) 16911 return false; 16912 16913 if (Fast) 16914 *Fast = 1; 16915 16916 return true; 16917 } 16918 16919 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16920 SDValue C) const { 16921 // Check integral scalar types. 16922 if (!VT.isScalarInteger()) 16923 return false; 16924 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16925 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16926 return false; 16927 // This transformation will generate >= 2 operations. But the following 16928 // cases will generate <= 2 instructions during ISEL. So exclude them. 16929 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16930 // HW instruction, ie. MULLI 16931 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16932 // instruction is needed than case 1, ie. MULLI and RLDICR 16933 int64_t Imm = ConstNode->getSExtValue(); 16934 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16935 Imm >>= Shift; 16936 if (isInt<16>(Imm)) 16937 return false; 16938 uint64_t UImm = static_cast<uint64_t>(Imm); 16939 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16940 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16941 return true; 16942 } 16943 return false; 16944 } 16945 16946 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16947 EVT VT) const { 16948 return isFMAFasterThanFMulAndFAdd( 16949 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16950 } 16951 16952 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16953 Type *Ty) const { 16954 if (Subtarget.hasSPE()) 16955 return false; 16956 switch (Ty->getScalarType()->getTypeID()) { 16957 case Type::FloatTyID: 16958 case Type::DoubleTyID: 16959 return true; 16960 case Type::FP128TyID: 16961 return Subtarget.hasP9Vector(); 16962 default: 16963 return false; 16964 } 16965 } 16966 16967 // FIXME: add more patterns which are not profitable to hoist. 16968 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16969 if (!I->hasOneUse()) 16970 return true; 16971 16972 Instruction *User = I->user_back(); 16973 assert(User && "A single use instruction with no uses."); 16974 16975 switch (I->getOpcode()) { 16976 case Instruction::FMul: { 16977 // Don't break FMA, PowerPC prefers FMA. 16978 if (User->getOpcode() != Instruction::FSub && 16979 User->getOpcode() != Instruction::FAdd) 16980 return true; 16981 16982 const TargetOptions &Options = getTargetMachine().Options; 16983 const Function *F = I->getFunction(); 16984 const DataLayout &DL = F->getParent()->getDataLayout(); 16985 Type *Ty = User->getOperand(0)->getType(); 16986 16987 return !( 16988 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16989 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16990 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16991 } 16992 case Instruction::Load: { 16993 // Don't break "store (load float*)" pattern, this pattern will be combined 16994 // to "store (load int32)" in later InstCombine pass. See function 16995 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16996 // cycles than loading a 32 bit integer. 16997 LoadInst *LI = cast<LoadInst>(I); 16998 // For the loads that combineLoadToOperationType does nothing, like 16999 // ordered load, it should be profitable to hoist them. 17000 // For swifterror load, it can only be used for pointer to pointer type, so 17001 // later type check should get rid of this case. 17002 if (!LI->isUnordered()) 17003 return true; 17004 17005 if (User->getOpcode() != Instruction::Store) 17006 return true; 17007 17008 if (I->getType()->getTypeID() != Type::FloatTyID) 17009 return true; 17010 17011 return false; 17012 } 17013 default: 17014 return true; 17015 } 17016 return true; 17017 } 17018 17019 const MCPhysReg * 17020 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 17021 // LR is a callee-save register, but we must treat it as clobbered by any call 17022 // site. Hence we include LR in the scratch registers, which are in turn added 17023 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 17024 // to CTR, which is used by any indirect call. 17025 static const MCPhysReg ScratchRegs[] = { 17026 PPC::X12, PPC::LR8, PPC::CTR8, 0 17027 }; 17028 17029 return ScratchRegs; 17030 } 17031 17032 Register PPCTargetLowering::getExceptionPointerRegister( 17033 const Constant *PersonalityFn) const { 17034 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 17035 } 17036 17037 Register PPCTargetLowering::getExceptionSelectorRegister( 17038 const Constant *PersonalityFn) const { 17039 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 17040 } 17041 17042 bool 17043 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 17044 EVT VT , unsigned DefinedValues) const { 17045 if (VT == MVT::v2i64) 17046 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 17047 17048 if (Subtarget.hasVSX()) 17049 return true; 17050 17051 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 17052 } 17053 17054 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 17055 if (DisableILPPref || Subtarget.enableMachineScheduler()) 17056 return TargetLowering::getSchedulingPreference(N); 17057 17058 return Sched::ILP; 17059 } 17060 17061 // Create a fast isel object. 17062 FastISel * 17063 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 17064 const TargetLibraryInfo *LibInfo) const { 17065 return PPC::createFastISel(FuncInfo, LibInfo); 17066 } 17067 17068 // 'Inverted' means the FMA opcode after negating one multiplicand. 17069 // For example, (fma -a b c) = (fnmsub a b c) 17070 static unsigned invertFMAOpcode(unsigned Opc) { 17071 switch (Opc) { 17072 default: 17073 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 17074 case ISD::FMA: 17075 return PPCISD::FNMSUB; 17076 case PPCISD::FNMSUB: 17077 return ISD::FMA; 17078 } 17079 } 17080 17081 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 17082 bool LegalOps, bool OptForSize, 17083 NegatibleCost &Cost, 17084 unsigned Depth) const { 17085 if (Depth > SelectionDAG::MaxRecursionDepth) 17086 return SDValue(); 17087 17088 unsigned Opc = Op.getOpcode(); 17089 EVT VT = Op.getValueType(); 17090 SDNodeFlags Flags = Op.getNode()->getFlags(); 17091 17092 switch (Opc) { 17093 case PPCISD::FNMSUB: 17094 if (!Op.hasOneUse() || !isTypeLegal(VT)) 17095 break; 17096 17097 const TargetOptions &Options = getTargetMachine().Options; 17098 SDValue N0 = Op.getOperand(0); 17099 SDValue N1 = Op.getOperand(1); 17100 SDValue N2 = Op.getOperand(2); 17101 SDLoc Loc(Op); 17102 17103 NegatibleCost N2Cost = NegatibleCost::Expensive; 17104 SDValue NegN2 = 17105 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 17106 17107 if (!NegN2) 17108 return SDValue(); 17109 17110 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 17111 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 17112 // These transformations may change sign of zeroes. For example, 17113 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 17114 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 17115 // Try and choose the cheaper one to negate. 17116 NegatibleCost N0Cost = NegatibleCost::Expensive; 17117 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 17118 N0Cost, Depth + 1); 17119 17120 NegatibleCost N1Cost = NegatibleCost::Expensive; 17121 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 17122 N1Cost, Depth + 1); 17123 17124 if (NegN0 && N0Cost <= N1Cost) { 17125 Cost = std::min(N0Cost, N2Cost); 17126 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 17127 } else if (NegN1) { 17128 Cost = std::min(N1Cost, N2Cost); 17129 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 17130 } 17131 } 17132 17133 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 17134 if (isOperationLegal(ISD::FMA, VT)) { 17135 Cost = N2Cost; 17136 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 17137 } 17138 17139 break; 17140 } 17141 17142 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 17143 Cost, Depth); 17144 } 17145 17146 // Override to enable LOAD_STACK_GUARD lowering on Linux. 17147 bool PPCTargetLowering::useLoadStackGuardNode() const { 17148 if (!Subtarget.isTargetLinux()) 17149 return TargetLowering::useLoadStackGuardNode(); 17150 return true; 17151 } 17152 17153 // Override to disable global variable loading on Linux and insert AIX canary 17154 // word declaration. 17155 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 17156 if (Subtarget.isAIXABI()) { 17157 M.getOrInsertGlobal(AIXSSPCanaryWordName, 17158 Type::getInt8PtrTy(M.getContext())); 17159 return; 17160 } 17161 if (!Subtarget.isTargetLinux()) 17162 return TargetLowering::insertSSPDeclarations(M); 17163 } 17164 17165 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 17166 if (Subtarget.isAIXABI()) 17167 return M.getGlobalVariable(AIXSSPCanaryWordName); 17168 return TargetLowering::getSDagStackGuard(M); 17169 } 17170 17171 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 17172 bool ForCodeSize) const { 17173 if (!VT.isSimple() || !Subtarget.hasVSX()) 17174 return false; 17175 17176 switch(VT.getSimpleVT().SimpleTy) { 17177 default: 17178 // For FP types that are currently not supported by PPC backend, return 17179 // false. Examples: f16, f80. 17180 return false; 17181 case MVT::f32: 17182 case MVT::f64: { 17183 if (Subtarget.hasPrefixInstrs()) { 17184 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 17185 return true; 17186 } 17187 bool IsExact; 17188 APSInt IntResult(16, false); 17189 // The rounding mode doesn't really matter because we only care about floats 17190 // that can be converted to integers exactly. 17191 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact); 17192 // For exact values in the range [-16, 15] we can materialize the float. 17193 if (IsExact && IntResult <= 15 && IntResult >= -16) 17194 return true; 17195 return Imm.isZero(); 17196 } 17197 case MVT::ppcf128: 17198 return Imm.isPosZero(); 17199 } 17200 } 17201 17202 // For vector shift operation op, fold 17203 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 17204 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 17205 SelectionDAG &DAG) { 17206 SDValue N0 = N->getOperand(0); 17207 SDValue N1 = N->getOperand(1); 17208 EVT VT = N0.getValueType(); 17209 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 17210 unsigned Opcode = N->getOpcode(); 17211 unsigned TargetOpcode; 17212 17213 switch (Opcode) { 17214 default: 17215 llvm_unreachable("Unexpected shift operation"); 17216 case ISD::SHL: 17217 TargetOpcode = PPCISD::SHL; 17218 break; 17219 case ISD::SRL: 17220 TargetOpcode = PPCISD::SRL; 17221 break; 17222 case ISD::SRA: 17223 TargetOpcode = PPCISD::SRA; 17224 break; 17225 } 17226 17227 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 17228 N1->getOpcode() == ISD::AND) 17229 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 17230 if (Mask->getZExtValue() == OpSizeInBits - 1) 17231 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 17232 17233 return SDValue(); 17234 } 17235 17236 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 17237 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17238 return Value; 17239 17240 SDValue N0 = N->getOperand(0); 17241 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 17242 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 17243 N0.getOpcode() != ISD::SIGN_EXTEND || 17244 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 17245 N->getValueType(0) != MVT::i64) 17246 return SDValue(); 17247 17248 // We can't save an operation here if the value is already extended, and 17249 // the existing shift is easier to combine. 17250 SDValue ExtsSrc = N0.getOperand(0); 17251 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 17252 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 17253 return SDValue(); 17254 17255 SDLoc DL(N0); 17256 SDValue ShiftBy = SDValue(CN1, 0); 17257 // We want the shift amount to be i32 on the extswli, but the shift could 17258 // have an i64. 17259 if (ShiftBy.getValueType() == MVT::i64) 17260 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 17261 17262 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 17263 ShiftBy); 17264 } 17265 17266 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 17267 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17268 return Value; 17269 17270 return SDValue(); 17271 } 17272 17273 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 17274 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17275 return Value; 17276 17277 return SDValue(); 17278 } 17279 17280 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 17281 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 17282 // When C is zero, the equation (addi Z, -C) can be simplified to Z 17283 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 17284 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 17285 const PPCSubtarget &Subtarget) { 17286 if (!Subtarget.isPPC64()) 17287 return SDValue(); 17288 17289 SDValue LHS = N->getOperand(0); 17290 SDValue RHS = N->getOperand(1); 17291 17292 auto isZextOfCompareWithConstant = [](SDValue Op) { 17293 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 17294 Op.getValueType() != MVT::i64) 17295 return false; 17296 17297 SDValue Cmp = Op.getOperand(0); 17298 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 17299 Cmp.getOperand(0).getValueType() != MVT::i64) 17300 return false; 17301 17302 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 17303 int64_t NegConstant = 0 - Constant->getSExtValue(); 17304 // Due to the limitations of the addi instruction, 17305 // -C is required to be [-32768, 32767]. 17306 return isInt<16>(NegConstant); 17307 } 17308 17309 return false; 17310 }; 17311 17312 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 17313 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 17314 17315 // If there is a pattern, canonicalize a zext operand to the RHS. 17316 if (LHSHasPattern && !RHSHasPattern) 17317 std::swap(LHS, RHS); 17318 else if (!LHSHasPattern && !RHSHasPattern) 17319 return SDValue(); 17320 17321 SDLoc DL(N); 17322 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 17323 SDValue Cmp = RHS.getOperand(0); 17324 SDValue Z = Cmp.getOperand(0); 17325 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 17326 int64_t NegConstant = 0 - Constant->getSExtValue(); 17327 17328 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 17329 default: break; 17330 case ISD::SETNE: { 17331 // when C == 0 17332 // --> addze X, (addic Z, -1).carry 17333 // / 17334 // add X, (zext(setne Z, C))-- 17335 // \ when -32768 <= -C <= 32767 && C != 0 17336 // --> addze X, (addic (addi Z, -C), -1).carry 17337 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17338 DAG.getConstant(NegConstant, DL, MVT::i64)); 17339 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17340 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17341 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 17342 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17343 SDValue(Addc.getNode(), 1)); 17344 } 17345 case ISD::SETEQ: { 17346 // when C == 0 17347 // --> addze X, (subfic Z, 0).carry 17348 // / 17349 // add X, (zext(sete Z, C))-- 17350 // \ when -32768 <= -C <= 32767 && C != 0 17351 // --> addze X, (subfic (addi Z, -C), 0).carry 17352 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17353 DAG.getConstant(NegConstant, DL, MVT::i64)); 17354 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17355 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17356 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 17357 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17358 SDValue(Subc.getNode(), 1)); 17359 } 17360 } 17361 17362 return SDValue(); 17363 } 17364 17365 // Transform 17366 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 17367 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 17368 // In this case both C1 and C2 must be known constants. 17369 // C1+C2 must fit into a 34 bit signed integer. 17370 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 17371 const PPCSubtarget &Subtarget) { 17372 if (!Subtarget.isUsingPCRelativeCalls()) 17373 return SDValue(); 17374 17375 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 17376 // If we find that node try to cast the Global Address and the Constant. 17377 SDValue LHS = N->getOperand(0); 17378 SDValue RHS = N->getOperand(1); 17379 17380 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17381 std::swap(LHS, RHS); 17382 17383 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17384 return SDValue(); 17385 17386 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17387 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17388 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17389 17390 // Check that both casts succeeded. 17391 if (!GSDN || !ConstNode) 17392 return SDValue(); 17393 17394 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17395 SDLoc DL(GSDN); 17396 17397 // The signed int offset needs to fit in 34 bits. 17398 if (!isInt<34>(NewOffset)) 17399 return SDValue(); 17400 17401 // The new global address is a copy of the old global address except 17402 // that it has the updated Offset. 17403 SDValue GA = 17404 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17405 NewOffset, GSDN->getTargetFlags()); 17406 SDValue MatPCRel = 17407 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17408 return MatPCRel; 17409 } 17410 17411 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17412 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17413 return Value; 17414 17415 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17416 return Value; 17417 17418 return SDValue(); 17419 } 17420 17421 // Detect TRUNCATE operations on bitcasts of float128 values. 17422 // What we are looking for here is the situtation where we extract a subset 17423 // of bits from a 128 bit float. 17424 // This can be of two forms: 17425 // 1) BITCAST of f128 feeding TRUNCATE 17426 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17427 // The reason this is required is because we do not have a legal i128 type 17428 // and so we want to prevent having to store the f128 and then reload part 17429 // of it. 17430 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17431 DAGCombinerInfo &DCI) const { 17432 // If we are using CRBits then try that first. 17433 if (Subtarget.useCRBits()) { 17434 // Check if CRBits did anything and return that if it did. 17435 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17436 return CRTruncValue; 17437 } 17438 17439 SDLoc dl(N); 17440 SDValue Op0 = N->getOperand(0); 17441 17442 // Looking for a truncate of i128 to i64. 17443 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17444 return SDValue(); 17445 17446 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17447 17448 // SRL feeding TRUNCATE. 17449 if (Op0.getOpcode() == ISD::SRL) { 17450 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17451 // The right shift has to be by 64 bits. 17452 if (!ConstNode || ConstNode->getZExtValue() != 64) 17453 return SDValue(); 17454 17455 // Switch the element number to extract. 17456 EltToExtract = EltToExtract ? 0 : 1; 17457 // Update Op0 past the SRL. 17458 Op0 = Op0.getOperand(0); 17459 } 17460 17461 // BITCAST feeding a TRUNCATE possibly via SRL. 17462 if (Op0.getOpcode() == ISD::BITCAST && 17463 Op0.getValueType() == MVT::i128 && 17464 Op0.getOperand(0).getValueType() == MVT::f128) { 17465 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17466 return DCI.DAG.getNode( 17467 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17468 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17469 } 17470 return SDValue(); 17471 } 17472 17473 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17474 SelectionDAG &DAG = DCI.DAG; 17475 17476 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17477 if (!ConstOpOrElement) 17478 return SDValue(); 17479 17480 // An imul is usually smaller than the alternative sequence for legal type. 17481 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17482 isOperationLegal(ISD::MUL, N->getValueType(0))) 17483 return SDValue(); 17484 17485 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17486 switch (this->Subtarget.getCPUDirective()) { 17487 default: 17488 // TODO: enhance the condition for subtarget before pwr8 17489 return false; 17490 case PPC::DIR_PWR8: 17491 // type mul add shl 17492 // scalar 4 1 1 17493 // vector 7 2 2 17494 return true; 17495 case PPC::DIR_PWR9: 17496 case PPC::DIR_PWR10: 17497 case PPC::DIR_PWR_FUTURE: 17498 // type mul add shl 17499 // scalar 5 2 2 17500 // vector 7 2 2 17501 17502 // The cycle RATIO of related operations are showed as a table above. 17503 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17504 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17505 // are 4, it is always profitable; but for 3 instrs patterns 17506 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17507 // So we should only do it for vector type. 17508 return IsAddOne && IsNeg ? VT.isVector() : true; 17509 } 17510 }; 17511 17512 EVT VT = N->getValueType(0); 17513 SDLoc DL(N); 17514 17515 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17516 bool IsNeg = MulAmt.isNegative(); 17517 APInt MulAmtAbs = MulAmt.abs(); 17518 17519 if ((MulAmtAbs - 1).isPowerOf2()) { 17520 // (mul x, 2^N + 1) => (add (shl x, N), x) 17521 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17522 17523 if (!IsProfitable(IsNeg, true, VT)) 17524 return SDValue(); 17525 17526 SDValue Op0 = N->getOperand(0); 17527 SDValue Op1 = 17528 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17529 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17530 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17531 17532 if (!IsNeg) 17533 return Res; 17534 17535 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17536 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17537 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17538 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17539 17540 if (!IsProfitable(IsNeg, false, VT)) 17541 return SDValue(); 17542 17543 SDValue Op0 = N->getOperand(0); 17544 SDValue Op1 = 17545 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17546 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17547 17548 if (!IsNeg) 17549 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17550 else 17551 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17552 17553 } else { 17554 return SDValue(); 17555 } 17556 } 17557 17558 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17559 // in combiner since we need to check SD flags and other subtarget features. 17560 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17561 DAGCombinerInfo &DCI) const { 17562 SDValue N0 = N->getOperand(0); 17563 SDValue N1 = N->getOperand(1); 17564 SDValue N2 = N->getOperand(2); 17565 SDNodeFlags Flags = N->getFlags(); 17566 EVT VT = N->getValueType(0); 17567 SelectionDAG &DAG = DCI.DAG; 17568 const TargetOptions &Options = getTargetMachine().Options; 17569 unsigned Opc = N->getOpcode(); 17570 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17571 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17572 SDLoc Loc(N); 17573 17574 if (!isOperationLegal(ISD::FMA, VT)) 17575 return SDValue(); 17576 17577 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17578 // since (fnmsub a b c)=-0 while c-ab=+0. 17579 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17580 return SDValue(); 17581 17582 // (fma (fneg a) b c) => (fnmsub a b c) 17583 // (fnmsub (fneg a) b c) => (fma a b c) 17584 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17585 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17586 17587 // (fma a (fneg b) c) => (fnmsub a b c) 17588 // (fnmsub a (fneg b) c) => (fma a b c) 17589 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17590 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17591 17592 return SDValue(); 17593 } 17594 17595 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17596 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17597 if (!Subtarget.is64BitELFABI()) 17598 return false; 17599 17600 // If not a tail call then no need to proceed. 17601 if (!CI->isTailCall()) 17602 return false; 17603 17604 // If sibling calls have been disabled and tail-calls aren't guaranteed 17605 // there is no reason to duplicate. 17606 auto &TM = getTargetMachine(); 17607 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17608 return false; 17609 17610 // Can't tail call a function called indirectly, or if it has variadic args. 17611 const Function *Callee = CI->getCalledFunction(); 17612 if (!Callee || Callee->isVarArg()) 17613 return false; 17614 17615 // Make sure the callee and caller calling conventions are eligible for tco. 17616 const Function *Caller = CI->getParent()->getParent(); 17617 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17618 CI->getCallingConv())) 17619 return false; 17620 17621 // If the function is local then we have a good chance at tail-calling it 17622 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17623 } 17624 17625 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17626 if (!Subtarget.hasVSX()) 17627 return false; 17628 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17629 return true; 17630 return VT == MVT::f32 || VT == MVT::f64 || 17631 VT == MVT::v4f32 || VT == MVT::v2f64; 17632 } 17633 17634 bool PPCTargetLowering:: 17635 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17636 const Value *Mask = AndI.getOperand(1); 17637 // If the mask is suitable for andi. or andis. we should sink the and. 17638 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17639 // Can't handle constants wider than 64-bits. 17640 if (CI->getBitWidth() > 64) 17641 return false; 17642 int64_t ConstVal = CI->getZExtValue(); 17643 return isUInt<16>(ConstVal) || 17644 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17645 } 17646 17647 // For non-constant masks, we can always use the record-form and. 17648 return true; 17649 } 17650 17651 // For type v4i32/v8ii16/v16i8, transform 17652 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (abdu a, b) 17653 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (abdu a, b) 17654 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (abdu a, b) 17655 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (abdu a, b) 17656 // TODO: Move this to DAGCombiner? 17657 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17658 DAGCombinerInfo &DCI) const { 17659 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17660 assert(Subtarget.hasP9Altivec() && 17661 "Only combine this when P9 altivec supported!"); 17662 17663 SelectionDAG &DAG = DCI.DAG; 17664 SDLoc dl(N); 17665 SDValue Cond = N->getOperand(0); 17666 SDValue TrueOpnd = N->getOperand(1); 17667 SDValue FalseOpnd = N->getOperand(2); 17668 EVT VT = N->getOperand(1).getValueType(); 17669 17670 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17671 FalseOpnd.getOpcode() != ISD::SUB) 17672 return SDValue(); 17673 17674 // ABSD only available for type v4i32/v8i16/v16i8 17675 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17676 return SDValue(); 17677 17678 // At least to save one more dependent computation 17679 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17680 return SDValue(); 17681 17682 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17683 17684 // Can only handle unsigned comparison here 17685 switch (CC) { 17686 default: 17687 return SDValue(); 17688 case ISD::SETUGT: 17689 case ISD::SETUGE: 17690 break; 17691 case ISD::SETULT: 17692 case ISD::SETULE: 17693 std::swap(TrueOpnd, FalseOpnd); 17694 break; 17695 } 17696 17697 SDValue CmpOpnd1 = Cond.getOperand(0); 17698 SDValue CmpOpnd2 = Cond.getOperand(1); 17699 17700 // SETCC CmpOpnd1 CmpOpnd2 cond 17701 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17702 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17703 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17704 TrueOpnd.getOperand(1) == CmpOpnd2 && 17705 FalseOpnd.getOperand(0) == CmpOpnd2 && 17706 FalseOpnd.getOperand(1) == CmpOpnd1) { 17707 return DAG.getNode(ISD::ABDU, dl, N->getOperand(1).getValueType(), CmpOpnd1, 17708 CmpOpnd2, DAG.getTargetConstant(0, dl, MVT::i32)); 17709 } 17710 17711 return SDValue(); 17712 } 17713 17714 /// getAddrModeForFlags - Based on the set of address flags, select the most 17715 /// optimal instruction format to match by. 17716 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17717 // This is not a node we should be handling here. 17718 if (Flags == PPC::MOF_None) 17719 return PPC::AM_None; 17720 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17721 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17722 if ((Flags & FlagSet) == FlagSet) 17723 return PPC::AM_DForm; 17724 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17725 if ((Flags & FlagSet) == FlagSet) 17726 return PPC::AM_DSForm; 17727 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17728 if ((Flags & FlagSet) == FlagSet) 17729 return PPC::AM_DQForm; 17730 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17731 if ((Flags & FlagSet) == FlagSet) 17732 return PPC::AM_PrefixDForm; 17733 // If no other forms are selected, return an X-Form as it is the most 17734 // general addressing mode. 17735 return PPC::AM_XForm; 17736 } 17737 17738 /// Set alignment flags based on whether or not the Frame Index is aligned. 17739 /// Utilized when computing flags for address computation when selecting 17740 /// load and store instructions. 17741 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17742 SelectionDAG &DAG) { 17743 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17744 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17745 if (!FI) 17746 return; 17747 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17748 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17749 // If this is (add $FI, $S16Imm), the alignment flags are already set 17750 // based on the immediate. We just need to clear the alignment flags 17751 // if the FI alignment is weaker. 17752 if ((FrameIndexAlign % 4) != 0) 17753 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17754 if ((FrameIndexAlign % 16) != 0) 17755 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17756 // If the address is a plain FrameIndex, set alignment flags based on 17757 // FI alignment. 17758 if (!IsAdd) { 17759 if ((FrameIndexAlign % 4) == 0) 17760 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17761 if ((FrameIndexAlign % 16) == 0) 17762 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17763 } 17764 } 17765 17766 /// Given a node, compute flags that are used for address computation when 17767 /// selecting load and store instructions. The flags computed are stored in 17768 /// FlagSet. This function takes into account whether the node is a constant, 17769 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17770 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17771 SelectionDAG &DAG) { 17772 // Set the alignment flags for the node depending on if the node is 17773 // 4-byte or 16-byte aligned. 17774 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17775 if ((Imm & 0x3) == 0) 17776 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17777 if ((Imm & 0xf) == 0) 17778 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17779 }; 17780 17781 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17782 // All 32-bit constants can be computed as LIS + Disp. 17783 const APInt &ConstImm = CN->getAPIntValue(); 17784 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17785 FlagSet |= PPC::MOF_AddrIsSImm32; 17786 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17787 setAlignFlagsForFI(N, FlagSet, DAG); 17788 } 17789 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17790 FlagSet |= PPC::MOF_RPlusSImm34; 17791 else // Let constant materialization handle large constants. 17792 FlagSet |= PPC::MOF_NotAddNorCst; 17793 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17794 // This address can be represented as an addition of: 17795 // - Register + Imm16 (possibly a multiple of 4/16) 17796 // - Register + Imm34 17797 // - Register + PPCISD::Lo 17798 // - Register + Register 17799 // In any case, we won't have to match this as Base + Zero. 17800 SDValue RHS = N.getOperand(1); 17801 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17802 const APInt &ConstImm = CN->getAPIntValue(); 17803 if (ConstImm.isSignedIntN(16)) { 17804 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17805 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17806 setAlignFlagsForFI(N, FlagSet, DAG); 17807 } 17808 if (ConstImm.isSignedIntN(34)) 17809 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17810 else 17811 FlagSet |= PPC::MOF_RPlusR; // Register. 17812 } else if (RHS.getOpcode() == PPCISD::Lo && 17813 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17814 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17815 else 17816 FlagSet |= PPC::MOF_RPlusR; 17817 } else { // The address computation is not a constant or an addition. 17818 setAlignFlagsForFI(N, FlagSet, DAG); 17819 FlagSet |= PPC::MOF_NotAddNorCst; 17820 } 17821 } 17822 17823 static bool isPCRelNode(SDValue N) { 17824 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17825 isValidPCRelNode<ConstantPoolSDNode>(N) || 17826 isValidPCRelNode<GlobalAddressSDNode>(N) || 17827 isValidPCRelNode<JumpTableSDNode>(N) || 17828 isValidPCRelNode<BlockAddressSDNode>(N)); 17829 } 17830 17831 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17832 /// the address flags of the load/store instruction that is to be matched. 17833 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17834 SelectionDAG &DAG) const { 17835 unsigned FlagSet = PPC::MOF_None; 17836 17837 // Compute subtarget flags. 17838 if (!Subtarget.hasP9Vector()) 17839 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17840 else { 17841 FlagSet |= PPC::MOF_SubtargetP9; 17842 if (Subtarget.hasPrefixInstrs()) 17843 FlagSet |= PPC::MOF_SubtargetP10; 17844 } 17845 if (Subtarget.hasSPE()) 17846 FlagSet |= PPC::MOF_SubtargetSPE; 17847 17848 // Check if we have a PCRel node and return early. 17849 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17850 return FlagSet; 17851 17852 // If the node is the paired load/store intrinsics, compute flags for 17853 // address computation and return early. 17854 unsigned ParentOp = Parent->getOpcode(); 17855 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17856 (ParentOp == ISD::INTRINSIC_VOID))) { 17857 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17858 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) { 17859 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) 17860 ? Parent->getOperand(2) 17861 : Parent->getOperand(3); 17862 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17863 FlagSet |= PPC::MOF_Vector; 17864 return FlagSet; 17865 } 17866 } 17867 17868 // Mark this as something we don't want to handle here if it is atomic 17869 // or pre-increment instruction. 17870 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17871 if (LSB->isIndexed()) 17872 return PPC::MOF_None; 17873 17874 // Compute in-memory type flags. This is based on if there are scalars, 17875 // floats or vectors. 17876 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17877 assert(MN && "Parent should be a MemSDNode!"); 17878 EVT MemVT = MN->getMemoryVT(); 17879 unsigned Size = MemVT.getSizeInBits(); 17880 if (MemVT.isScalarInteger()) { 17881 assert(Size <= 128 && 17882 "Not expecting scalar integers larger than 16 bytes!"); 17883 if (Size < 32) 17884 FlagSet |= PPC::MOF_SubWordInt; 17885 else if (Size == 32) 17886 FlagSet |= PPC::MOF_WordInt; 17887 else 17888 FlagSet |= PPC::MOF_DoubleWordInt; 17889 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17890 if (Size == 128) 17891 FlagSet |= PPC::MOF_Vector; 17892 else if (Size == 256) { 17893 assert(Subtarget.pairedVectorMemops() && 17894 "256-bit vectors are only available when paired vector memops is " 17895 "enabled!"); 17896 FlagSet |= PPC::MOF_Vector; 17897 } else 17898 llvm_unreachable("Not expecting illegal vectors!"); 17899 } else { // Floating point type: can be scalar, f128 or vector types. 17900 if (Size == 32 || Size == 64) 17901 FlagSet |= PPC::MOF_ScalarFloat; 17902 else if (MemVT == MVT::f128 || MemVT.isVector()) 17903 FlagSet |= PPC::MOF_Vector; 17904 else 17905 llvm_unreachable("Not expecting illegal scalar floats!"); 17906 } 17907 17908 // Compute flags for address computation. 17909 computeFlagsForAddressComputation(N, FlagSet, DAG); 17910 17911 // Compute type extension flags. 17912 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17913 switch (LN->getExtensionType()) { 17914 case ISD::SEXTLOAD: 17915 FlagSet |= PPC::MOF_SExt; 17916 break; 17917 case ISD::EXTLOAD: 17918 case ISD::ZEXTLOAD: 17919 FlagSet |= PPC::MOF_ZExt; 17920 break; 17921 case ISD::NON_EXTLOAD: 17922 FlagSet |= PPC::MOF_NoExt; 17923 break; 17924 } 17925 } else 17926 FlagSet |= PPC::MOF_NoExt; 17927 17928 // For integers, no extension is the same as zero extension. 17929 // We set the extension mode to zero extension so we don't have 17930 // to add separate entries in AddrModesMap for loads and stores. 17931 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17932 FlagSet |= PPC::MOF_ZExt; 17933 FlagSet &= ~PPC::MOF_NoExt; 17934 } 17935 17936 // If we don't have prefixed instructions, 34-bit constants should be 17937 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17938 bool IsNonP1034BitConst = 17939 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17940 FlagSet) == PPC::MOF_RPlusSImm34; 17941 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17942 IsNonP1034BitConst) 17943 FlagSet |= PPC::MOF_NotAddNorCst; 17944 17945 return FlagSet; 17946 } 17947 17948 /// SelectForceXFormMode - Given the specified address, force it to be 17949 /// represented as an indexed [r+r] operation (an XForm instruction). 17950 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17951 SDValue &Base, 17952 SelectionDAG &DAG) const { 17953 17954 PPC::AddrMode Mode = PPC::AM_XForm; 17955 int16_t ForceXFormImm = 0; 17956 if (provablyDisjointOr(DAG, N) && 17957 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17958 Disp = N.getOperand(0); 17959 Base = N.getOperand(1); 17960 return Mode; 17961 } 17962 17963 // If the address is the result of an add, we will utilize the fact that the 17964 // address calculation includes an implicit add. However, we can reduce 17965 // register pressure if we do not materialize a constant just for use as the 17966 // index register. We only get rid of the add if it is not an add of a 17967 // value and a 16-bit signed constant and both have a single use. 17968 if (N.getOpcode() == ISD::ADD && 17969 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17970 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17971 Disp = N.getOperand(0); 17972 Base = N.getOperand(1); 17973 return Mode; 17974 } 17975 17976 // Otherwise, use R0 as the base register. 17977 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17978 N.getValueType()); 17979 Base = N; 17980 17981 return Mode; 17982 } 17983 17984 bool PPCTargetLowering::splitValueIntoRegisterParts( 17985 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 17986 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const { 17987 EVT ValVT = Val.getValueType(); 17988 // If we are splitting a scalar integer into f64 parts (i.e. so they 17989 // can be placed into VFRC registers), we need to zero extend and 17990 // bitcast the values. This will ensure the value is placed into a 17991 // VSR using direct moves or stack operations as needed. 17992 if (PartVT == MVT::f64 && 17993 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) { 17994 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 17995 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val); 17996 Parts[0] = Val; 17997 return true; 17998 } 17999 return false; 18000 } 18001 18002 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op, 18003 SelectionDAG &DAG) const { 18004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 18005 TargetLowering::CallLoweringInfo CLI(DAG); 18006 EVT RetVT = Op.getValueType(); 18007 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 18008 SDValue Callee = 18009 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout())); 18010 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false); 18011 TargetLowering::ArgListTy Args; 18012 TargetLowering::ArgListEntry Entry; 18013 for (const SDValue &N : Op->op_values()) { 18014 EVT ArgVT = N.getValueType(); 18015 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 18016 Entry.Node = N; 18017 Entry.Ty = ArgTy; 18018 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend); 18019 Entry.IsZExt = !Entry.IsSExt; 18020 Args.push_back(Entry); 18021 } 18022 18023 SDValue InChain = DAG.getEntryNode(); 18024 SDValue TCChain = InChain; 18025 const Function &F = DAG.getMachineFunction().getFunction(); 18026 bool isTailCall = 18027 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 18028 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 18029 if (isTailCall) 18030 InChain = TCChain; 18031 CLI.setDebugLoc(SDLoc(Op)) 18032 .setChain(InChain) 18033 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args)) 18034 .setTailCall(isTailCall) 18035 .setSExtResult(SignExtend) 18036 .setZExtResult(!SignExtend) 18037 .setIsPostTypeLegalization(true); 18038 return TLI.LowerCallTo(CLI).first; 18039 } 18040 18041 SDValue PPCTargetLowering::lowerLibCallBasedOnType( 18042 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op, 18043 SelectionDAG &DAG) const { 18044 if (Op.getValueType() == MVT::f32) 18045 return lowerToLibCall(LibCallFloatName, Op, DAG); 18046 18047 if (Op.getValueType() == MVT::f64) 18048 return lowerToLibCall(LibCallDoubleName, Op, DAG); 18049 18050 return SDValue(); 18051 } 18052 18053 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const { 18054 SDNodeFlags Flags = Op.getNode()->getFlags(); 18055 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() && 18056 Flags.hasNoNaNs() && Flags.hasNoInfs(); 18057 } 18058 18059 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const { 18060 return Op.getNode()->getFlags().hasApproximateFuncs(); 18061 } 18062 18063 bool PPCTargetLowering::isScalarMASSConversionEnabled() const { 18064 return getTargetMachine().Options.PPCGenScalarMASSEntries; 18065 } 18066 18067 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName, 18068 const char *LibCallFloatName, 18069 const char *LibCallDoubleNameFinite, 18070 const char *LibCallFloatNameFinite, 18071 SDValue Op, 18072 SelectionDAG &DAG) const { 18073 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op)) 18074 return SDValue(); 18075 18076 if (!isLowringToMASSFiniteSafe(Op)) 18077 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op, 18078 DAG); 18079 18080 return lowerLibCallBasedOnType(LibCallFloatNameFinite, 18081 LibCallDoubleNameFinite, Op, DAG); 18082 } 18083 18084 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const { 18085 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite", 18086 "__xl_powf_finite", Op, DAG); 18087 } 18088 18089 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const { 18090 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite", 18091 "__xl_sinf_finite", Op, DAG); 18092 } 18093 18094 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const { 18095 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite", 18096 "__xl_cosf_finite", Op, DAG); 18097 } 18098 18099 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const { 18100 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite", 18101 "__xl_logf_finite", Op, DAG); 18102 } 18103 18104 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const { 18105 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite", 18106 "__xl_log10f_finite", Op, DAG); 18107 } 18108 18109 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const { 18110 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite", 18111 "__xl_expf_finite", Op, DAG); 18112 } 18113 18114 // If we happen to match to an aligned D-Form, check if the Frame Index is 18115 // adequately aligned. If it is not, reset the mode to match to X-Form. 18116 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 18117 PPC::AddrMode &Mode) { 18118 if (!isa<FrameIndexSDNode>(N)) 18119 return; 18120 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 18121 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 18122 Mode = PPC::AM_XForm; 18123 } 18124 18125 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 18126 /// compute the address flags of the node, get the optimal address mode based 18127 /// on the flags, and set the Base and Disp based on the address mode. 18128 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 18129 SDValue N, SDValue &Disp, 18130 SDValue &Base, 18131 SelectionDAG &DAG, 18132 MaybeAlign Align) const { 18133 SDLoc DL(Parent); 18134 18135 // Compute the address flags. 18136 unsigned Flags = computeMOFlags(Parent, N, DAG); 18137 18138 // Get the optimal address mode based on the Flags. 18139 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 18140 18141 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 18142 // Select an X-Form load if it is not. 18143 setXFormForUnalignedFI(N, Flags, Mode); 18144 18145 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 18146 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 18147 assert(Subtarget.isUsingPCRelativeCalls() && 18148 "Must be using PC-Relative calls when a valid PC-Relative node is " 18149 "present!"); 18150 Mode = PPC::AM_PCRel; 18151 } 18152 18153 // Set Base and Disp accordingly depending on the address mode. 18154 switch (Mode) { 18155 case PPC::AM_DForm: 18156 case PPC::AM_DSForm: 18157 case PPC::AM_DQForm: { 18158 // This is a register plus a 16-bit immediate. The base will be the 18159 // register and the displacement will be the immediate unless it 18160 // isn't sufficiently aligned. 18161 if (Flags & PPC::MOF_RPlusSImm16) { 18162 SDValue Op0 = N.getOperand(0); 18163 SDValue Op1 = N.getOperand(1); 18164 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 18165 if (!Align || isAligned(*Align, Imm)) { 18166 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 18167 Base = Op0; 18168 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 18169 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18170 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 18171 } 18172 break; 18173 } 18174 } 18175 // This is a register plus the @lo relocation. The base is the register 18176 // and the displacement is the global address. 18177 else if (Flags & PPC::MOF_RPlusLo) { 18178 Disp = N.getOperand(1).getOperand(0); // The global address. 18179 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 18180 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 18181 Disp.getOpcode() == ISD::TargetConstantPool || 18182 Disp.getOpcode() == ISD::TargetJumpTable); 18183 Base = N.getOperand(0); 18184 break; 18185 } 18186 // This is a constant address at most 32 bits. The base will be 18187 // zero or load-immediate-shifted and the displacement will be 18188 // the low 16 bits of the address. 18189 else if (Flags & PPC::MOF_AddrIsSImm32) { 18190 auto *CN = cast<ConstantSDNode>(N); 18191 EVT CNType = CN->getValueType(0); 18192 uint64_t CNImm = CN->getZExtValue(); 18193 // If this address fits entirely in a 16-bit sext immediate field, codegen 18194 // this as "d, 0". 18195 int16_t Imm; 18196 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 18197 Disp = DAG.getTargetConstant(Imm, DL, CNType); 18198 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 18199 CNType); 18200 break; 18201 } 18202 // Handle 32-bit sext immediate with LIS + Addr mode. 18203 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 18204 (!Align || isAligned(*Align, CNImm))) { 18205 int32_t Addr = (int32_t)CNImm; 18206 // Otherwise, break this down into LIS + Disp. 18207 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 18208 Base = 18209 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 18210 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 18211 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 18212 break; 18213 } 18214 } 18215 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 18216 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 18217 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 18218 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18219 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 18220 } else 18221 Base = N; 18222 break; 18223 } 18224 case PPC::AM_PrefixDForm: { 18225 int64_t Imm34 = 0; 18226 unsigned Opcode = N.getOpcode(); 18227 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 18228 (isIntS34Immediate(N.getOperand(1), Imm34))) { 18229 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 18230 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18231 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 18232 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18233 else 18234 Base = N.getOperand(0); 18235 } else if (isIntS34Immediate(N, Imm34)) { 18236 // The address is a 34-bit signed immediate. 18237 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18238 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 18239 } 18240 break; 18241 } 18242 case PPC::AM_PCRel: { 18243 // When selecting PC-Relative instructions, "Base" is not utilized as 18244 // we select the address as [PC+imm]. 18245 Disp = N; 18246 break; 18247 } 18248 case PPC::AM_None: 18249 break; 18250 default: { // By default, X-Form is always available to be selected. 18251 // When a frame index is not aligned, we also match by XForm. 18252 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 18253 Base = FI ? N : N.getOperand(1); 18254 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 18255 N.getValueType()) 18256 : N.getOperand(0); 18257 break; 18258 } 18259 } 18260 return Mode; 18261 } 18262 18263 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 18264 bool Return, 18265 bool IsVarArg) const { 18266 switch (CC) { 18267 case CallingConv::Cold: 18268 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 18269 default: 18270 return CC_PPC64_ELF_FIS; 18271 } 18272 } 18273 18274 bool PPCTargetLowering::shouldInlineQuadwordAtomics() const { 18275 // TODO: 16-byte atomic type support for AIX is in progress; we should be able 18276 // to inline 16-byte atomic ops on AIX too in the future. 18277 return Subtarget.isPPC64() && 18278 (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) && 18279 Subtarget.hasQuadwordAtomics(); 18280 } 18281 18282 TargetLowering::AtomicExpansionKind 18283 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18284 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18285 if (shouldInlineQuadwordAtomics() && Size == 128) 18286 return AtomicExpansionKind::MaskedIntrinsic; 18287 18288 switch (AI->getOperation()) { 18289 case AtomicRMWInst::UIncWrap: 18290 case AtomicRMWInst::UDecWrap: 18291 return AtomicExpansionKind::CmpXChg; 18292 default: 18293 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 18294 } 18295 18296 llvm_unreachable("unreachable atomicrmw operation"); 18297 } 18298 18299 TargetLowering::AtomicExpansionKind 18300 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18301 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 18302 if (shouldInlineQuadwordAtomics() && Size == 128) 18303 return AtomicExpansionKind::MaskedIntrinsic; 18304 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 18305 } 18306 18307 static Intrinsic::ID 18308 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 18309 switch (BinOp) { 18310 default: 18311 llvm_unreachable("Unexpected AtomicRMW BinOp"); 18312 case AtomicRMWInst::Xchg: 18313 return Intrinsic::ppc_atomicrmw_xchg_i128; 18314 case AtomicRMWInst::Add: 18315 return Intrinsic::ppc_atomicrmw_add_i128; 18316 case AtomicRMWInst::Sub: 18317 return Intrinsic::ppc_atomicrmw_sub_i128; 18318 case AtomicRMWInst::And: 18319 return Intrinsic::ppc_atomicrmw_and_i128; 18320 case AtomicRMWInst::Or: 18321 return Intrinsic::ppc_atomicrmw_or_i128; 18322 case AtomicRMWInst::Xor: 18323 return Intrinsic::ppc_atomicrmw_xor_i128; 18324 case AtomicRMWInst::Nand: 18325 return Intrinsic::ppc_atomicrmw_nand_i128; 18326 } 18327 } 18328 18329 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 18330 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 18331 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 18332 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18333 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18334 Type *ValTy = Incr->getType(); 18335 assert(ValTy->getPrimitiveSizeInBits() == 128); 18336 Function *RMW = Intrinsic::getDeclaration( 18337 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 18338 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18339 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 18340 Value *IncrHi = 18341 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 18342 Value *Addr = 18343 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18344 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 18345 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18346 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18347 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18348 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18349 return Builder.CreateOr( 18350 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18351 } 18352 18353 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 18354 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 18355 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 18356 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18357 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18358 Type *ValTy = CmpVal->getType(); 18359 assert(ValTy->getPrimitiveSizeInBits() == 128); 18360 Function *IntCmpXchg = 18361 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 18362 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18363 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 18364 Value *CmpHi = 18365 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 18366 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 18367 Value *NewHi = 18368 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 18369 Value *Addr = 18370 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18371 emitLeadingFence(Builder, CI, Ord); 18372 Value *LoHi = 18373 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 18374 emitTrailingFence(Builder, CI, Ord); 18375 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18376 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18377 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18378 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18379 return Builder.CreateOr( 18380 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18381 } 18382